summaryrefslogtreecommitdiff
path: root/tui.go
blob: c6eb453369a9f9b092db8f3b4d313c5fd779612f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
package main

import (
	"fmt"
	"gf-lt/extra"
	"gf-lt/models"
	"image"
	_ "image/jpeg"
	_ "image/png"
	"os"
	"os/exec"
	"path"
	"slices"
	"strconv"
	"strings"

	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
)

var (
	app             *tview.Application
	pages           *tview.Pages
	textArea        *tview.TextArea
	editArea        *tview.TextArea
	textView        *tview.TextView
	position        *tview.TextView
	helpView        *tview.TextView
	flex            *tview.Flex
	imgView         *tview.Image
	defaultImage    = "sysprompts/llama.png"
	indexPickWindow *tview.InputField
	renameWindow    *tview.InputField
	searchWindow    *tview.InputField
	fullscreenMode  bool
	// pages
	historyPage    = "historyPage"
	agentPage      = "agentPage"
	editMsgPage    = "editMsgPage"
	indexPage      = "indexPage"
	helpPage       = "helpPage"
	renamePage     = "renamePage"
	RAGPage        = "RAGPage"
	RAGLoadedPage  = "RAGLoadedPage"
	propsPage      = "propsPage"
	codeBlockPage  = "codeBlockPage"
	imgPage        = "imgPage"
	filePickerPage = "filePicker"
	exportDir      = "chat_exports"

	// For overlay search functionality
	searchField    *tview.InputField
	isSearching    bool
	searchPageName = "searchOverlay"
	// help text
	helpText = `
[yellow]Esc[white]: send msg
[yellow]PgUp/Down[white]: switch focus between input and chat widgets
[yellow]F1[white]: manage chats
[yellow]F2[white]: regen last
[yellow]F3[white]: delete last msg
[yellow]F4[white]: edit msg
[yellow]F5[white]: toggle system
[yellow]F6[white]: interrupt bot resp
[yellow]F7[white]: copy last msg to clipboard (linux xclip)
[yellow]F8[white]: copy n msg to clipboard (linux xclip)
[yellow]F9[white]: table to copy from; with all code blocks
[yellow]F10[white]: switch if LLM will respond on this message (for user to write multiple messages in a row)
[yellow]F11[white]: import chat file
[yellow]F12[white]: show this help page
[yellow]Ctrl+w[white]: resume generation on the last msg
[yellow]Ctrl+s[white]: load new char/agent
[yellow]Ctrl+e[white]: export chat to json file
[yellow]Ctrl+c[white]: close programm
[yellow]Ctrl+n[white]: start a new chat
[yellow]Ctrl+o[white]: open image file picker
[yellow]Ctrl+p[white]: props edit form (min-p, dry, etc.)
[yellow]Ctrl+v[white]: switch between /completion and /chat api (if provided in config)
[yellow]Ctrl+r[white]: start/stop recording from your microphone (needs stt server)
[yellow]Ctrl+t[white]: remove thinking (<think>) and tool messages from context (delete from chat)
[yellow]Ctrl+l[white]: rotate through free OpenRouter models (if openrouter api) or update connected model name (llamacpp)
[yellow]Ctrl+k[white]: switch tool use (recommend tool use to llm after user msg)
[yellow]Ctrl+j[white]: if chat agent is char.png will show the image; then any key to return
[yellow]Ctrl+a[white]: interrupt tts (needs tts server)
[yellow]Ctrl+g[white]: open RAG file manager (load files for context retrieval)
[yellow]Ctrl+y[white]: list loaded RAG files (view and manage loaded files)
[yellow]Ctrl+q[white]: cycle through mentioned chars in chat, to pick persona to send next msg as
[yellow]Ctrl+x[white]: cycle through mentioned chars in chat, to pick persona to send next msg as (for llm)
[yellow]Alt+5[white]: toggle fullscreen for input/chat window
[yellow]Alt+1[white]: toggle shell mode (execute commands locally)

=== scrolling chat window (some keys similar to vim) ===
[yellow]arrows up/down and j/k[white]: scroll up and down
[yellow]gg/G[white]: jump to the begging / end of the chat
[yellow]/[white]: start searching for text
[yellow]n[white]: go to next search result
[yellow]N[white]: go to previous search result

=== status line ===
%s

Press Enter to go back
`
	colorschemes = map[string]tview.Theme{
		"default": tview.Theme{
			PrimitiveBackgroundColor:    tcell.ColorDefault,
			ContrastBackgroundColor:     tcell.ColorGray,
			MoreContrastBackgroundColor: tcell.ColorSteelBlue,
			BorderColor:                 tcell.ColorGray,
			TitleColor:                  tcell.ColorRed,
			GraphicsColor:               tcell.ColorBlue,
			PrimaryTextColor:            tcell.ColorLightGray,
			SecondaryTextColor:          tcell.ColorYellow,
			TertiaryTextColor:           tcell.ColorOrange,
			InverseTextColor:            tcell.ColorPurple,
			ContrastSecondaryTextColor:  tcell.ColorLime,
		},
		"gruvbox": tview.Theme{
			PrimitiveBackgroundColor:    tcell.ColorBlack,         // Matches #1e1e2e
			ContrastBackgroundColor:     tcell.ColorDarkGoldenrod, // Selected option: warm yellow (#b57614)
			MoreContrastBackgroundColor: tcell.ColorDarkSlateGray, // Non-selected options: dark grayish-blue (#32302f)
			BorderColor:                 tcell.ColorLightGray,     // Light gray (#a89984)
			TitleColor:                  tcell.ColorRed,           // Red (#fb4934)
			GraphicsColor:               tcell.ColorDarkCyan,      // Cyan (#689d6a)
			PrimaryTextColor:            tcell.ColorLightGray,     // Light gray (#d5c4a1)
			SecondaryTextColor:          tcell.ColorYellow,        // Yellow (#fabd2f)
			TertiaryTextColor:           tcell.ColorOrange,        // Orange (#fe8019)
			InverseTextColor:            tcell.ColorWhite,         // White (#f9f5d7) for selected text
			ContrastSecondaryTextColor:  tcell.ColorLightGreen,    // Light green (#b8bb26)
		},
		"solarized": tview.Theme{
			PrimitiveBackgroundColor:    tcell.NewHexColor(0x1e1e2e), // #1e1e2e for main dropdown box
			ContrastBackgroundColor:     tcell.ColorDarkCyan,         // Selected option: cyan (#2aa198)
			MoreContrastBackgroundColor: tcell.ColorDarkSlateGray,    // Non-selected options: dark blue (#073642)
			BorderColor:                 tcell.ColorLightBlue,        // Light blue (#839496)
			TitleColor:                  tcell.ColorRed,              // Red (#dc322f)
			GraphicsColor:               tcell.ColorBlue,             // Blue (#268bd2)
			PrimaryTextColor:            tcell.ColorWhite,            // White (#fdf6e3)
			SecondaryTextColor:          tcell.ColorYellow,           // Yellow (#b58900)
			TertiaryTextColor:           tcell.ColorOrange,           // Orange (#cb4b16)
			InverseTextColor:            tcell.ColorWhite,            // White (#eee8d5) for selected text
			ContrastSecondaryTextColor:  tcell.ColorLightCyan,        // Light cyan (#93a1a1)
		},
		"dracula": tview.Theme{
			PrimitiveBackgroundColor:    tcell.NewHexColor(0x1e1e2e), // #1e1e2e for main dropdown box
			ContrastBackgroundColor:     tcell.ColorDarkMagenta,      // Selected option: magenta (#bd93f9)
			MoreContrastBackgroundColor: tcell.ColorDarkGray,         // Non-selected options: dark gray (#44475a)
			BorderColor:                 tcell.ColorLightGray,        // Light gray (#f8f8f2)
			TitleColor:                  tcell.ColorRed,              // Red (#ff5555)
			GraphicsColor:               tcell.ColorDarkCyan,         // Cyan (#8be9fd)
			PrimaryTextColor:            tcell.ColorWhite,            // White (#f8f8f2)
			SecondaryTextColor:          tcell.ColorYellow,           // Yellow (#f1fa8c)
			TertiaryTextColor:           tcell.ColorOrange,           // Orange (#ffb86c)
			InverseTextColor:            tcell.ColorWhite,            // White (#f8f8f2) for selected text
			ContrastSecondaryTextColor:  tcell.ColorLightGreen,       // Light green (#50fa7b)
		},
	}
)

func makePropsForm(props map[string]float32) *tview.Form {
	// https://github.com/rivo/tview/commit/0a18dea458148770d212d348f656988df75ff341
	// no way to close a form by a key press; a shame.
	modelList := []string{chatBody.Model, "deepseek-chat", "deepseek-reasoner"}
	modelList = append(modelList, ORFreeModels...)
	form := tview.NewForm().
		AddTextView("Notes", "Props for llamacpp completion call", 40, 2, true, false).
		AddCheckbox("Insert <think> (/completion only)", cfg.ThinkUse, func(checked bool) {
			cfg.ThinkUse = checked
		}).AddCheckbox("RAG use", cfg.RAGEnabled, func(checked bool) {
		cfg.RAGEnabled = checked
	}).AddCheckbox("Inject role", injectRole, func(checked bool) {
		injectRole = checked
	}).AddDropDown("Set log level (Enter): ", []string{"Debug", "Info", "Warn"}, 1,
		func(option string, optionIndex int) {
			setLogLevel(option)
		}).AddDropDown("Select an api: ", slices.Insert(cfg.ApiLinks, 0, cfg.CurrentAPI), 0,
		func(option string, optionIndex int) {
			cfg.CurrentAPI = option
		}).AddDropDown("Select a model: ", modelList, 0,
		func(option string, optionIndex int) {
			chatBody.Model = option
		}).AddDropDown("Write next message as: ", listRolesWithUser(), 0,
		func(option string, optionIndex int) {
			cfg.WriteNextMsgAs = option
		}).AddInputField("new char to write msg as: ", "", 32, tview.InputFieldMaxLength(32),
		func(text string) {
			if text != "" {
				cfg.WriteNextMsgAs = text
			}
		}).AddInputField("username: ", cfg.UserRole, 32, tview.InputFieldMaxLength(32), func(text string) {
		if text != "" {
			renameUser(cfg.UserRole, text)
			cfg.UserRole = text
		}
	}).
		AddButton("Quit", func() {
			pages.RemovePage(propsPage)
		})
	form.AddButton("Save", func() {
		defer updateStatusLine()
		defer pages.RemovePage(propsPage)
		for pn := range props {
			propField, ok := form.GetFormItemByLabel(pn).(*tview.InputField)
			if !ok {
				logger.Warn("failed to convert to inputfield", "prop_name", pn)
				continue
			}
			val, err := strconv.ParseFloat(propField.GetText(), 32)
			if err != nil {
				logger.Warn("failed parse to float", "value", propField.GetText())
				continue
			}
			props[pn] = float32(val)
		}
	})
	for propName, value := range props {
		form.AddInputField(propName, fmt.Sprintf("%v", value), 20, tview.InputFieldFloat, nil)
	}
	form.SetBorder(true).SetTitle("Enter some data").SetTitleAlign(tview.AlignLeft)
	return form
}

func toggleShellMode() {
	shellMode = !shellMode
	if shellMode {
		// Update input placeholder to indicate shell mode
		textArea.SetPlaceholder("SHELL MODE: Enter command and press <Esc> to execute")
	} else {
		// Reset to normal mode
		textArea.SetPlaceholder("input is multiline; press <Enter> to start the next line;\npress <Esc> to send the message. Alt+1 to exit shell mode")
	}
	updateStatusLine()
}

func executeCommandAndDisplay(cmdText string) {
	// Parse the command (split by spaces, but handle quoted arguments)
	cmdParts := parseCommand(cmdText)
	if len(cmdParts) == 0 {
		fmt.Fprintf(textView, "\n[red]Error: No command provided[-:-:-]\n")
		textView.ScrollToEnd()
		colorText()
		return
	}

	command := cmdParts[0]
	args := []string{}
	if len(cmdParts) > 1 {
		args = cmdParts[1:]
	}

	// Create the command execution
	cmd := exec.Command(command, args...)

	// Execute the command and get output
	output, err := cmd.CombinedOutput()

	// Add the command being executed to the chat
	fmt.Fprintf(textView, "\n[yellow]$ %s[-:-:-]\n", cmdText)

	if err != nil {
		// Include both output and error
		fmt.Fprintf(textView, "[red]Error: %s[-:-:-]\n", err.Error())
		if len(output) > 0 {
			fmt.Fprintf(textView, "[red]%s[-:-:-]\n", string(output))
		}
	} else {
		// Only output if successful
		if len(output) > 0 {
			fmt.Fprintf(textView, "[green]%s[-:-:-]\n", string(output))
		} else {
			fmt.Fprintf(textView, "[green]Command executed successfully (no output)[-:-:-]\n")
		}
	}

	// Scroll to end and update colors
	textView.ScrollToEnd()
	colorText()
}

// parseCommand splits command string handling quotes properly
func parseCommand(cmd string) []string {
	var args []string
	var current string
	var inQuotes bool
	var quoteChar rune

	for _, r := range cmd {
		switch r {
		case '"', '\'':
			if inQuotes {
				if r == quoteChar {
					inQuotes = false
				} else {
					current += string(r)
				}
			} else {
				inQuotes = true
				quoteChar = r
			}
		case ' ', '\t':
			if inQuotes {
				current += string(r)
			} else if current != "" {
				args = append(args, current)
				current = ""
			}
		default:
			current += string(r)
		}
	}

	if current != "" {
		args = append(args, current)
	}

	return args
}

// Global variables for search state
var searchResults []int
var searchResultLengths []int // To store the length of each match in the formatted string
var searchIndex int
var searchText string

// stripTags creates a plain text version of a tview formatted string and a mapping
// from plain text indices to formatted text indices.
func stripTags(formatted string) (string, []int) {
	var plain strings.Builder
	// The mapping will store the byte index in the formatted string for each byte in the plain string.
	mapping := make([]int, 0, len(formatted))

	i := 0
	for i < len(formatted) {
		if formatted[i] != '[' {
			mapping = append(mapping, i)
			plain.WriteByte(formatted[i])
			i++
			continue
		}

		// We are at a '['
		if i+1 < len(formatted) && formatted[i+1] == '[' { // Escaped '[['
			mapping = append(mapping, i)
			plain.WriteByte('[')
			i += 2
			continue
		}

		// It's a tag. Find its end.
		end := -1
		// Region tags are of the form ["..."]
		if i+1 < len(formatted) && formatted[i+1] == '"' {
			// Find `"]`
			for j := i + 2; j < len(formatted)-1; j++ {
				if formatted[j] == '"' && formatted[j+1] == ']' {
					end = j + 1
					break
				}
			}
		} else {
			// Color/attr tag [...]
			closeBracket := strings.IndexRune(formatted[i:], ']')
			if closeBracket != -1 {
				end = i + closeBracket
			}
		}

		if end == -1 {
			// Unterminated tag. Treat as literal.
			mapping = append(mapping, i)
			plain.WriteByte(formatted[i])
			i++
		} else {
			// Skip tag
			i = end + 1
		}
	}
	return plain.String(), mapping
}

// performSearch searches for the given term in the textView content and highlights matches
func performSearch(term string) {
	searchText = term
	if searchText == "" {
		searchResults = nil
		searchResultLengths = nil
		// Re-render text without highlights
		textView.SetText(chatToText(cfg.ShowSys))
		colorText()
		return
	}

	// Get formatted text
	formattedText := textView.GetText(true)
	plainText, mapping := stripTags(formattedText)

	// Find all occurrences of the search term in plain text
	plainSearchResults := []int{}

	start := 0
	for {
		// Use case-insensitive search
		index := strings.Index(strings.ToLower(plainText[start:]), strings.ToLower(searchText))
		if index == -1 {
			break
		}

		absoluteIndex := start + index
		plainSearchResults = append(plainSearchResults, absoluteIndex)
		start = absoluteIndex + len(searchText) // Advance past the last match
	}

	if len(plainSearchResults) > 0 {
		searchResults = make([]int, len(plainSearchResults))
		searchResultLengths = make([]int, len(plainSearchResults))

		for i, p_start := range plainSearchResults {
			p_end_exclusive := p_start + len(searchText)

			f_start := mapping[p_start]
			var f_end_exclusive int
			if p_end_exclusive < len(mapping) {
				f_end_exclusive = mapping[p_end_exclusive]
			} else {
				// Reached the end of the text
				f_end_exclusive = len(formattedText)
			}

			searchResults[i] = f_start
			searchResultLengths[i] = f_end_exclusive - f_start
		}

		searchIndex = 0
		highlightCurrentMatch()
	} else {
		// No matches found
		searchResults = nil
		searchResultLengths = nil
		notification := fmt.Sprintf("Pattern not found: %s", term)
		if err := notifyUser("search", notification); err != nil {
			logger.Error("failed to send notification", "error", err)
		}
	}
}

// highlightCurrentMatch highlights the current search match and scrolls to it
func highlightCurrentMatch() {
	if len(searchResults) == 0 || searchIndex >= len(searchResults) {
		return
	}

	// Get the stored formatted text
	formattedText := textView.GetText(true)

	// For tview to properly support highlighting and scrolling, we need to work with its region system
	// Instead of just applying highlights, we need to add region tags to the text
	highlightedText := addRegionTags(formattedText, searchResults, searchResultLengths, searchIndex, searchText)

	// Update the text view with the text that includes region tags
	textView.SetText(highlightedText)

	// Highlight the current region and scroll to it
	// Need to identify which position in the results array corresponds to the current match
	// The region ID will be search_<position>_<index>
	currentRegion := fmt.Sprintf("search_%d_%d", searchResults[searchIndex], searchIndex)
	textView.Highlight(currentRegion).ScrollToHighlight()

	// Send notification about which match we're at
	notification := fmt.Sprintf("Match %d of %d", searchIndex+1, len(searchResults))
	if err := notifyUser("search", notification); err != nil {
		logger.Error("failed to send notification", "error", err)
	}
}

// applyAllHighlights applies highlighting to all search matches in the text
func applyAllHighlights(text string, positions []int, currentIdx int, searchTerm string) string {
	if len(positions) == 0 {
		return text
	}

	// For performance and to avoid freezing, use a simpler approach just highlighting the positions
	// that were found in the initial search (even if not perfectly mapped to formatted text)
	var result strings.Builder

	// For simplicity and to prevent freezing, don't do complex recalculations
	// Instead, we'll just highlight based on the initial search results
	lastEnd := 0

	// Since positions come from plain text search, they may not align with formatted text
	// For robustness, only process positions that are within bounds
	for i, pos := range positions {
		// Only process if within text bounds
		if pos >= len(text) {
			continue
		}

		endPos := pos + len(searchTerm)
		if endPos > len(text) {
			continue
		}

		// Check if the actual text matches the search term (case insensitive)
		actualText := text[pos:endPos]
		if strings.ToLower(actualText) != strings.ToLower(searchTerm) {
			continue // Skip if the text doesn't actually match at this position
		}

		// Add text before this match
		if pos > lastEnd {
			result.WriteString(text[lastEnd:pos])
		}

		// Highlight this match
		highlight := `[gold:red:u]`  // All matches - gold on red
		if i == currentIdx {
			highlight = `[yellow:blue:b]`  // Current match - yellow on blue bold
		}
		result.WriteString(highlight)
		result.WriteString(actualText)
		result.WriteString(`[-:-:-]`)  // Reset formatting

		lastEnd = endPos
	}

	// Add the rest of the text after the last processed match
	if lastEnd < len(text) {
		result.WriteString(text[lastEnd:])
	}

	return result.String()
}

// showSearchBar shows the search input field as an overlay
func showSearchBar() {
	isSearching = true
	// Create a temporary flex to combine search and main content
	updatedFlex := tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(searchField, 3, 0, true).  // Search field at top
		AddItem(flex, 0, 1, false)  // Main flex layout below

	// Add the search overlay as a page
	pages.AddPage(searchPageName, updatedFlex, true, true)
	app.SetFocus(searchField)
}

// hideSearchBar hides the search input field
func hideSearchBar() {
	isSearching = false
	pages.RemovePage(searchPageName)
	// Return focus to the text view
	app.SetFocus(textView)
	// Clear the search field
	searchField.SetText("")
}

// addRegionTags adds region tags to search matches in the text for tview highlighting
func addRegionTags(text string, positions []int, lengths []int, currentIdx int, searchTerm string) string {
	if len(positions) == 0 {
		return text
	}

	var result strings.Builder
	lastEnd := 0

	for i, pos := range positions {
		endPos := pos + lengths[i]

		// Add text before this match
		if pos > lastEnd {
			result.WriteString(text[lastEnd:pos])
		}

		// The matched text, which may contain its own formatting tags
		actualText := text[pos:endPos]

		// Add region tag and highlighting for this match
		// Use a unique region id that includes the match index to avoid conflicts
		regionId := fmt.Sprintf("search_%d_%d", pos, i) // position + index to ensure uniqueness
		var highlightStart, highlightEnd string
		if i == currentIdx {
			// Current match - use different highlighting
			highlightStart = fmt.Sprintf(`["%s"][yellow:blue:b]`, regionId) // Current match with region and special highlight
			highlightEnd = `[-:-:-][""]`                                    // Reset formatting and close region
		} else {
			// Other matches - use regular highlighting
			highlightStart = fmt.Sprintf(`["%s"][gold:red:u]`, regionId) // Other matches with region and highlight
			highlightEnd = `[-:-:-][""]`                                 // Reset formatting and close region
		}

		result.WriteString(highlightStart)
		result.WriteString(actualText)
		result.WriteString(highlightEnd)

		lastEnd = endPos
	}

	// Add the rest of the text after the last processed match
	if lastEnd < len(text) {
		result.WriteString(text[lastEnd:])
	}

	return result.String()
}

// insertHighlightAtPosition inserts highlight tags around a specific position in the text
func insertHighlightAtPosition(originalText string, pos int, length int) string {
	if pos < 0 || pos >= len(originalText) || pos+length > len(originalText) {
		return originalText
	}

	// Insert highlight tags around the match
	var result strings.Builder
	result.WriteString(originalText[:pos])
	result.WriteString(`[gold:red:u]`)  // Highlight with gold text on red background and underline
	result.WriteString(originalText[pos : pos+length])
	result.WriteString(`[-]`)  // Reset to default formatting
	result.WriteString(originalText[pos+length:])

	return result.String()
}

// highlightTextWithRegions adds region tags to highlight search matches
func highlightTextWithRegions(originalText string, matchStart int, matchLength int) string {
	// For now, we'll return the original text and use tview's highlight system differently
	// The highlighting will be applied via the textView.Highlight() method
	return originalText
}

// searchNext finds the next occurrence of the search term
func searchNext() {
	if len(searchResults) == 0 {
		if err := notifyUser("search", "No search results to navigate"); err != nil {
			logger.Error("failed to send notification", "error", err)
		}
		return
	}

	searchIndex = (searchIndex + 1) % len(searchResults)
	highlightCurrentMatch()
}

// searchPrev finds the previous occurrence of the search term
func searchPrev() {
	if len(searchResults) == 0 {
		if err := notifyUser("search", "No search results to navigate"); err != nil {
			logger.Error("failed to send notification", "error", err)
		}
		return
	}

	if searchIndex == 0 {
		searchIndex = len(searchResults) - 1
	} else {
		searchIndex--
	}
	highlightCurrentMatch()
}

func init() {
	tview.Styles = colorschemes["default"]
	app = tview.NewApplication()
	pages = tview.NewPages()
	textArea = tview.NewTextArea().
		SetPlaceholder("input is multiline; press <Enter> to start the next line;\npress <Esc> to send the message.")
	textArea.SetBorder(true).SetTitle("input")
	textView = tview.NewTextView().
		SetDynamicColors(true).
		SetRegions(true).
		SetChangedFunc(func() {
			app.Draw()
		})

	flex = tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(textView, 0, 40, false).
		AddItem(textArea, 0, 10, true). // Restore original height
		AddItem(position, 0, 2, false)
	// textView.SetBorder(true).SetTitle("chat")
	textView.SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEnter {
			if len(searchResults) > 0 { // Check if a search is active
				hideSearchBar()        // Hide the search bar if visible
				searchResults = nil    // Clear search results
				searchResultLengths = nil // Clear search result lengths
				textView.SetText(chatToText(cfg.ShowSys)) // Reset text without search regions
				colorText()            // Apply normal chat coloring
			} else {
				// Original logic if no search is active
				currentSelection := textView.GetHighlights()
				if len(currentSelection) > 0 {
					textView.Highlight()
				} else {
					textView.Highlight("0").ScrollToHighlight()
				}
			}
		}
	})
	textView.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		// Handle vim-like navigation in TextView
		switch event.Key() {
		case tcell.KeyRune:
			switch event.Rune() {
			case 'j':
				// For line down
				return event
			case 'k':
				// For line up
				return event
			case 'g':
				// Go to beginning
				textView.ScrollToBeginning()
				return nil
			case 'G':
				// Go to end
				textView.ScrollToEnd()
				return nil
			case '/':
				// Search functionality - show search bar
				showSearchBar()
				return nil
			case 'n':
				// Next search result
				searchNext()
				return nil
			case 'N':
				// Previous search result
				searchPrev()
				return nil
			}
		}
		return event
	})
	focusSwitcher[textArea] = textView
	focusSwitcher[textView] = textArea
	position = tview.NewTextView().
		SetDynamicColors(true).
		SetTextAlign(tview.AlignCenter)
	position.SetChangedFunc(func() {
		app.Draw()
	})
	// Initially set up flex without search bar
	flex = tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(textView, 0, 40, false).
		AddItem(textArea, 0, 10, true). // Restore original height
		AddItem(position, 0, 2, false)
	editArea = tview.NewTextArea().
		SetPlaceholder("Replace msg...")
	editArea.SetBorder(true).SetTitle("input")
	editArea.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		// if event.Key() == tcell.KeyEscape && editMode {
		if event.Key() == tcell.KeyEscape {
			defer colorText()
			editedMsg := editArea.GetText()
			if editedMsg == "" {
				if err := notifyUser("edit", "no edit provided"); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
				pages.RemovePage(editMsgPage)
				return nil
			}
			chatBody.Messages[selectedIndex].Content = editedMsg
			// change textarea
			textView.SetText(chatToText(cfg.ShowSys))
			pages.RemovePage(editMsgPage)
			editMode = false
			return nil
		}
		return event
	})
	indexPickWindow = tview.NewInputField().
		SetLabel("Enter a msg index: ").
		SetFieldWidth(4).
		SetAcceptanceFunc(tview.InputFieldInteger).
		SetDoneFunc(func(key tcell.Key) {
			defer indexPickWindow.SetText("")
			pages.RemovePage(indexPage)
			// colorText()
			// updateStatusLine()
		})
	indexPickWindow.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		switch event.Key() {
		case tcell.KeyBackspace:
			return event
		case tcell.KeyEnter:
			si := indexPickWindow.GetText()
			siInt, err := strconv.Atoi(si)
			if err != nil {
				logger.Error("failed to convert provided index", "error", err, "si", si)
				if err := notifyUser("cancel", "no index provided, copying user input"); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
				if err := copyToClipboard(textArea.GetText()); err != nil {
					logger.Error("failed to copy to clipboard", "error", err)
				}
				pages.RemovePage(indexPage)
				return event
			}
			selectedIndex = siInt
			if len(chatBody.Messages)-1 < selectedIndex || selectedIndex < 0 {
				msg := "chosen index is out of bounds, will copy user input"
				logger.Warn(msg, "index", selectedIndex)
				if err := notifyUser("error", msg); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
				if err := copyToClipboard(textArea.GetText()); err != nil {
					logger.Error("failed to copy to clipboard", "error", err)
				}
				pages.RemovePage(indexPage)
				return event
			}
			m := chatBody.Messages[selectedIndex]
			if editMode && event.Key() == tcell.KeyEnter {
				pages.RemovePage(indexPage)
				pages.AddPage(editMsgPage, editArea, true, true)
				editArea.SetText(m.Content, true)
			}
			if !editMode && event.Key() == tcell.KeyEnter {
				if err := copyToClipboard(m.Content); err != nil {
					logger.Error("failed to copy to clipboard", "error", err)
				}
				previewLen := min(30, len(m.Content))
				notification := fmt.Sprintf("msg '%s' was copied to the clipboard", m.Content[:previewLen])
				if err := notifyUser("copied", notification); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
			}
			return event
		default:
			return event
		}
	})
	//
	renameWindow = tview.NewInputField().
		SetLabel("Enter a msg index: ").
		SetFieldWidth(20).
		SetAcceptanceFunc(tview.InputFieldMaxLength(100)).
		SetDoneFunc(func(key tcell.Key) {
			pages.RemovePage(renamePage)
		})
	renameWindow.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		if event.Key() == tcell.KeyEnter {
			nname := renameWindow.GetText()
			if nname == "" {
				return event
			}
			currentChat := chatMap[activeChatName]
			delete(chatMap, activeChatName)
			currentChat.Name = nname
			activeChatName = nname
			chatMap[activeChatName] = currentChat
			_, err := store.UpsertChat(currentChat)
			if err != nil {
				logger.Error("failed to upsert chat", "error", err, "chat", currentChat)
			}
			notification := fmt.Sprintf("renamed chat to '%s'", activeChatName)
			if err := notifyUser("renamed", notification); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
		}
		return event
	})
	//
	searchField = tview.NewInputField().
		SetPlaceholder("Search... (Enter: search, Esc: cancel)").
		SetDoneFunc(func(key tcell.Key) {
			if key == tcell.KeyEnter {
				term := searchField.GetText()
				if term != "" {
					performSearch(term)
					// Keep focus on textView after search
					app.SetFocus(textView)
				}
				hideSearchBar()
			} else if key == tcell.KeyEscape {
				hideSearchBar()
			}
		})
	searchField.SetBorder(true).SetTitle("Search")
	// Note: Initially hide the search field (handled by not showing it in the layout)
	//
	helpView = tview.NewTextView().SetDynamicColors(true).
		SetText(fmt.Sprintf(helpText, makeStatusLine())).
		SetDoneFunc(func(key tcell.Key) {
			pages.RemovePage(helpPage)
		})
	helpView.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		switch event.Key() {
		case tcell.KeyEsc, tcell.KeyEnter:
			return event
		}
		return nil
	})
	//
	imgView = tview.NewImage()
	imgView.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		switch event.Key() {
		case tcell.KeyEnter:
			pages.RemovePage(imgPage)
			return event
		}
		if isASCII(string(event.Rune())) {
			pages.RemovePage(imgPage)
			return event
		}
		return nil
	})
	//
	textArea.SetMovedFunc(updateStatusLine)
	updateStatusLine()
	textView.SetText(chatToText(cfg.ShowSys))
	colorText()
	textView.ScrollToEnd()
	// init sysmap
	_, err := initSysCards()
	if err != nil {
		logger.Error("failed to init sys cards", "error", err)
	}
	app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		if event.Key() == tcell.KeyRune && event.Rune() == '5' && event.Modifiers()&tcell.ModAlt != 0 {
			fullscreenMode = !fullscreenMode
			focused := app.GetFocus()
			if fullscreenMode {
				if focused == textArea || focused == textView {
					flex.Clear()
					flex.AddItem(focused, 0, 1, true)
				} else {
					// if focus is not on textarea or textview, cancel fullscreen
					fullscreenMode = false
				}
			} else {
				// focused is the fullscreened widget here
				flex.Clear().
					AddItem(textView, 0, 40, false).
					AddItem(textArea, 0, 10, false).
					AddItem(position, 0, 2, false)

				if focused == textView {
					app.SetFocus(textView)
				} else { // default to textArea
					app.SetFocus(textArea)
				}
			}
			return nil
		}
		if event.Key() == tcell.KeyF1 {
			// chatList, err := loadHistoryChats()
			chatList, err := store.GetChatByChar(cfg.AssistantRole)
			if err != nil {
				logger.Error("failed to load chat history", "error", err)
				return nil
			}
			chatMap := make(map[string]models.Chat)
			// nameList := make([]string, len(chatList))
			for _, chat := range chatList {
				// nameList[i] = chat.Name
				chatMap[chat.Name] = chat
			}
			chatActTable := makeChatTable(chatMap)
			pages.AddPage(historyPage, chatActTable, true, true)
			colorText()
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyF2 {
			// regen last msg
			chatBody.Messages = chatBody.Messages[:len(chatBody.Messages)-1]
			// there is no case where user msg is regenerated
			// lastRole := chatBody.Messages[len(chatBody.Messages)-1].Role
			textView.SetText(chatToText(cfg.ShowSys))
			go chatRound("", cfg.UserRole, textView, true, false)
			return nil
		}
		if event.Key() == tcell.KeyF3 && !botRespMode {
			// delete last msg
			// check textarea text; if it ends with bot icon delete only icon:
			text := textView.GetText(true)
			assistantIcon := roleToIcon(cfg.AssistantRole)
			if strings.HasSuffix(text, assistantIcon) {
				logger.Debug("deleting assistant icon", "icon", assistantIcon)
				textView.SetText(strings.TrimSuffix(text, assistantIcon))
				colorText()
				return nil
			}
			chatBody.Messages = chatBody.Messages[:len(chatBody.Messages)-1]
			textView.SetText(chatToText(cfg.ShowSys))
			colorText()
			return nil
		}
		if event.Key() == tcell.KeyF4 {
			// edit msg
			editMode = true
			pages.AddPage(indexPage, indexPickWindow, true, true)
			return nil
		}
		if event.Key() == tcell.KeyF5 {
			// switch cfg.ShowSys
			cfg.ShowSys = !cfg.ShowSys
			textView.SetText(chatToText(cfg.ShowSys))
			colorText()
		}
		if event.Key() == tcell.KeyF6 {
			interruptResp = true
			botRespMode = false
			return nil
		}
		if event.Key() == tcell.KeyF7 {
			// copy msg to clipboard
			editMode = false
			m := chatBody.Messages[len(chatBody.Messages)-1]
			if err := copyToClipboard(m.Content); err != nil {
				logger.Error("failed to copy to clipboard", "error", err)
			}
			previewLen := min(30, len(m.Content))
			notification := fmt.Sprintf("msg '%s' was copied to the clipboard", m.Content[:previewLen])
			if err := notifyUser("copied", notification); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			return nil
		}
		if event.Key() == tcell.KeyF8 {
			// copy msg to clipboard
			editMode = false
			pages.AddPage(indexPage, indexPickWindow, true, true)
			return nil
		}
		if event.Key() == tcell.KeyF9 {
			// table of codeblocks to copy
			text := textView.GetText(false)
			cb := codeBlockRE.FindAllString(text, -1)
			if len(cb) == 0 {
				if err := notifyUser("notify", "no code blocks in chat"); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
				return nil
			}
			table := makeCodeBlockTable(cb)
			pages.AddPage(codeBlockPage, table, true, true)
			return nil
		}
		if event.Key() == tcell.KeyF10 {
			cfg.SkipLLMResp = !cfg.SkipLLMResp
			updateStatusLine()
		}
		if event.Key() == tcell.KeyF11 {
			// read files in chat_exports
			filelist, err := os.ReadDir(exportDir)
			if err != nil {
				if err := notifyUser("failed to load exports", err.Error()); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
				return nil
			}
			fli := []string{}
			for _, f := range filelist {
				if f.IsDir() || !strings.HasSuffix(f.Name(), ".json") {
					continue
				}
				fpath := path.Join(exportDir, f.Name())
				fli = append(fli, fpath)
			}
			// check error
			exportsTable := makeImportChatTable(fli)
			pages.AddPage(historyPage, exportsTable, true, true)
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyF12 {
			// help window cheatsheet
			pages.AddPage(helpPage, helpView, true, true)
			return nil
		}
		if event.Key() == tcell.KeyCtrlE {
			// export loaded chat into json file
			if err := exportChat(); err != nil {
				logger.Error("failed to export chat;", "error", err, "chat_name", activeChatName)
				return nil
			}
			if err := notifyUser("exported chat", "chat: "+activeChatName+" was exported"); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			return nil
		}
		if event.Key() == tcell.KeyCtrlP {
			propsForm := makePropsForm(defaultLCPProps)
			pages.AddPage(propsPage, propsForm, true, true)
			return nil
		}
		if event.Key() == tcell.KeyCtrlN {
			startNewChat()
			return nil
		}
		if event.Key() == tcell.KeyCtrlO {
			// open file picker
			filePicker := makeFilePicker()
			pages.AddPage(filePickerPage, filePicker, true, true)
			return nil
		}
		if event.Key() == tcell.KeyCtrlL {
			// Check if the current API is an OpenRouter API
			if strings.Contains(cfg.CurrentAPI, "openrouter.ai/api/v1/") {
				// Rotate through OpenRouter free models
				if len(ORFreeModels) > 0 {
					currentORModelIndex = (currentORModelIndex + 1) % len(ORFreeModels)
					chatBody.Model = ORFreeModels[currentORModelIndex]
				}
				updateStatusLine()
			} else {
				// For non-OpenRouter APIs, use the old logic
				go func() {
					fetchLCPModelName() // blocks
					updateStatusLine()
				}()
			}
			return nil
		}
		if event.Key() == tcell.KeyCtrlT {
			// clear context
			// remove tools and thinking
			removeThinking(chatBody)
			textView.SetText(chatToText(cfg.ShowSys))
			colorText()
			return nil
		}
		if event.Key() == tcell.KeyCtrlV {
			// switch between API links using index-based rotation
			if len(cfg.ApiLinks) == 0 {
				// No API links to rotate through
				return nil
			}
			// Find current API in the list to get the current index
			currentIndex := -1
			for i, api := range cfg.ApiLinks {
				if api == cfg.CurrentAPI {
					currentIndex = i
					break
				}
			}
			// If current API is not in the list, start from beginning
			// Otherwise, advance to next API in the list (with wrap-around)
			if currentIndex == -1 {
				currentAPIIndex = 0
			} else {
				currentAPIIndex = (currentIndex + 1) % len(cfg.ApiLinks)
			}
			cfg.CurrentAPI = cfg.ApiLinks[currentAPIIndex]
			choseChunkParser()
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyCtrlS {
			// switch sys prompt
			labels, err := initSysCards()
			if err != nil {
				logger.Error("failed to read sys dir", "error", err)
				if err := notifyUser("error", "failed to read: "+cfg.SysDir); err != nil {
					logger.Debug("failed to notify user", "error", err)
				}
				return nil
			}
			at := makeAgentTable(labels)
			// sysModal.AddButtons(labels)
			// load all chars
			pages.AddPage(agentPage, at, true, true)
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyCtrlK {
			// add message from tools
			cfg.ToolUse = !cfg.ToolUse
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyCtrlJ {
			// show image - check for attached image first, then fall back to agent image
			if lastImg != "" {
				// Load the attached image
				file, err := os.Open(lastImg)
				if err != nil {
					logger.Error("failed to open attached image", "path", lastImg, "error", err)
					// Fall back to showing agent image
					loadImage()
				} else {
					defer file.Close()
					img, _, err := image.Decode(file)
					if err != nil {
						logger.Error("failed to decode attached image", "path", lastImg, "error", err)
						// Fall back to showing agent image
						loadImage()
					} else {
						imgView.SetImage(img)
					}
				}
			} else {
				// No attached image, show agent image as before
				loadImage()
			}
			pages.AddPage(imgPage, imgView, true, true)
			return nil
		}
		if event.Key() == tcell.KeyCtrlR && cfg.STT_ENABLED {
			defer updateStatusLine()
			if asr.IsRecording() {
				userSpeech, err := asr.StopRecording()
				if err != nil {
					msg := "failed to inference user speech; error:" + err.Error()
					logger.Error(msg)
					if err := notifyUser("stt error", msg); err != nil {
						logger.Error("failed to notify user", "error", err)
					}
					return nil
				}
				if userSpeech != "" {
					// append indtead of replacing
					prevText := textArea.GetText()
					textArea.SetText(prevText+userSpeech, true)
				} else {
					logger.Warn("empty user speech")
				}
				return nil
			}
			if err := asr.StartRecording(); err != nil {
				logger.Error("failed to start recording user speech", "error", err)
				return nil
			}
		}
		// I need keybind for tts to shut up
		if event.Key() == tcell.KeyCtrlA {
			// textArea.SetText("pressed ctrl+A", true)
			if cfg.TTS_ENABLED {
				// audioStream.TextChan <- chunk
				extra.TTSDoneChan <- true
			}
		}
		if event.Key() == tcell.KeyCtrlW {
			// INFO: continue bot/text message
			// without new role
			lastRole := chatBody.Messages[len(chatBody.Messages)-1].Role
			go chatRound("", lastRole, textView, false, true)
			return nil
		}
		if event.Key() == tcell.KeyCtrlQ {
			persona := cfg.UserRole
			if cfg.WriteNextMsgAs != "" {
				persona = cfg.WriteNextMsgAs
			}
			roles := listRolesWithUser()
			logger.Info("list roles", "roles", roles)
			for i, role := range roles {
				if strings.EqualFold(role, persona) {
					if i == len(roles)-1 {
						cfg.WriteNextMsgAs = roles[0] // reached last, get first
						break
					}
					cfg.WriteNextMsgAs = roles[i+1] // get next role
					logger.Info("picked role", "roles", roles, "index", i+1)
					break
				}
			}
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyCtrlX {
			persona := cfg.AssistantRole
			if cfg.WriteNextMsgAsCompletionAgent != "" {
				persona = cfg.WriteNextMsgAsCompletionAgent
			}
			roles := chatBody.ListRoles()
			if len(roles) == 0 {
				logger.Warn("empty roles in chat")
			}
			if !strInSlice(cfg.AssistantRole, roles) {
				roles = append(roles, cfg.AssistantRole)
			}
			for i, role := range roles {
				if strings.EqualFold(role, persona) {
					if i == len(roles)-1 {
						cfg.WriteNextMsgAsCompletionAgent = roles[0] // reached last, get first
						break
					}
					cfg.WriteNextMsgAsCompletionAgent = roles[i+1] // get next role
					logger.Info("picked role", "roles", roles, "index", i+1)
					break
				}
			}
			updateStatusLine()
			return nil
		}
		if event.Key() == tcell.KeyCtrlG {
			// cfg.RAGDir is the directory with files to use with RAG
			// rag load
			// menu of the text files from defined rag directory
			files, err := os.ReadDir(cfg.RAGDir)
			if err != nil {
				// Check if the error is because the directory doesn't exist
				if os.IsNotExist(err) {
					// Create the RAG directory if it doesn't exist
					if mkdirErr := os.MkdirAll(cfg.RAGDir, 0755); mkdirErr != nil {
						logger.Error("failed to create RAG directory", "dir", cfg.RAGDir, "error", mkdirErr)
						if notifyerr := notifyUser("failed to create RAG directory", mkdirErr.Error()); notifyerr != nil {
							logger.Error("failed to send notification", "error", notifyerr)
						}
						return nil
					}
					// Now try to read the directory again after creating it
					files, err = os.ReadDir(cfg.RAGDir)
					if err != nil {
						logger.Error("failed to read dir after creating it", "dir", cfg.RAGDir, "error", err)
						if notifyerr := notifyUser("failed to read RAG directory", err.Error()); notifyerr != nil {
							logger.Error("failed to send notification", "error", notifyerr)
						}
						return nil
					}
				} else {
					// Other error (permissions, etc.)
					logger.Error("failed to read dir", "dir", cfg.RAGDir, "error", err)
					if notifyerr := notifyUser("failed to open RAG files dir", err.Error()); notifyerr != nil {
						logger.Error("failed to send notification", "error", notifyerr)
					}
					return nil
				}
			}
			fileList := []string{}
			for _, f := range files {
				if f.IsDir() {
					continue
				}
				fileList = append(fileList, f.Name())
			}
			chatRAGTable := makeRAGTable(fileList)
			pages.AddPage(RAGPage, chatRAGTable, true, true)
			return nil
		}
		if event.Key() == tcell.KeyCtrlY { // Use Ctrl+Y to list loaded RAG files
			// List files already loaded into the RAG system
			fileList, err := ragger.ListLoaded()
			if err != nil {
				logger.Error("failed to list loaded RAG files", "error", err)
				if notifyerr := notifyUser("failed to list RAG files", err.Error()); notifyerr != nil {
					logger.Error("failed to send notification", "error", notifyerr)
				}
				return nil
			}
			chatLoadedRAGTable := makeLoadedRAGTable(fileList)
			pages.AddPage(RAGLoadedPage, chatLoadedRAGTable, true, true)
			return nil
		}
		if event.Key() == tcell.KeyRune && event.Modifiers() == tcell.ModAlt && event.Rune() == '1' {
			// Toggle shell mode: when enabled, commands are executed locally instead of sent to LLM
			toggleShellMode()
			return nil
		}
		// cannot send msg in editMode or botRespMode
		if event.Key() == tcell.KeyEscape && !editMode && !botRespMode {
			msgText := textArea.GetText()

			if shellMode && msgText != "" {
				// In shell mode, execute command instead of sending to LLM
				executeCommandAndDisplay(msgText)
				textArea.SetText("", true) // Clear the input area
				return nil
			} else if !shellMode {
				// Normal mode - send to LLM
				nl := "\n"
				prevText := textView.GetText(true)
				persona := cfg.UserRole
				// strings.LastIndex()
				// newline is not needed is prev msg ends with one
				if strings.HasSuffix(prevText, nl) {
					nl = ""
				}
				if msgText != "" {
					// as what char user sends msg?
					if cfg.WriteNextMsgAs != "" {
						persona = cfg.WriteNextMsgAs
					}
					// check if plain text
					if !injectRole {
						matches := roleRE.FindStringSubmatch(msgText)
						if len(matches) > 1 {
							persona = matches[1]
							msgText = strings.TrimLeft(msgText[len(matches[0]):], " ")
						}
					}
					// add user icon before user msg
					fmt.Fprintf(textView, "%s[-:-:b](%d) <%s>: [-:-:-]\n%s\n",
						nl, len(chatBody.Messages), persona, msgText)
					textArea.SetText("", true)
					textView.ScrollToEnd()
					colorText()
				}
				go chatRound(msgText, persona, textView, false, false)
				// Also clear any image attachment after sending the message
				go func() {
					// Wait a short moment for the message to be processed, then clear the image attachment
					// This allows the image to be sent with the current message if it was attached
					// But clears it for the next message
					ClearImageAttachment()
				}()
			}
			return nil
		}
		if event.Key() == tcell.KeyPgUp || event.Key() == tcell.KeyPgDn {
			currentF := app.GetFocus()
			app.SetFocus(focusSwitcher[currentF])
			return nil
		}


		if isASCII(string(event.Rune())) && !botRespMode {
			return event
		}
		return event
	})
}