summaryrefslogtreecommitdiff
path: root/tables.go
blob: 8302e91ae3fe68891f951b4eb3c812cc3d7a4fa6 (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
package main

import (
	"fmt"
	"os"
	"path"
	"strings"
	"time"

	"gf-lt/models"
	"gf-lt/pngmeta"
	"gf-lt/rag"

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

func makeChatTable(chatMap map[string]models.Chat) *tview.Table {
	actions := []string{"load", "rename", "delete", "update card", "move sysprompt onto 1st msg", "new_chat_from_card"}
	chatList := make([]string, len(chatMap))
	i := 0
	for name := range chatMap {
		chatList[i] = name
		i++
	}
	rows, cols := len(chatMap), len(actions)+2
	chatActTable := tview.NewTable().
		SetBorders(true)
	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			color := tcell.ColorWhite
			switch c {
			case 0:
				chatActTable.SetCell(r, c,
					tview.NewTableCell(chatList[r]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			case 1:
				chatActTable.SetCell(r, c,
					tview.NewTableCell(chatMap[chatList[r]].Msgs[len(chatMap[chatList[r]].Msgs)-30:]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			default:
				chatActTable.SetCell(r, c,
					tview.NewTableCell(actions[c-2]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			}
		}
	}
	chatActTable.Select(0, 0).SetFixed(1, 1).SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEsc || key == tcell.KeyF1 {
			pages.RemovePage(historyPage)
			return
		}
		if key == tcell.KeyEnter {
			chatActTable.SetSelectable(true, true)
		}
	}).SetSelectedFunc(func(row int, column int) {
		tc := chatActTable.GetCell(row, column)
		tc.SetTextColor(tcell.ColorRed)
		chatActTable.SetSelectable(false, false)
		selectedChat := chatList[row]
		defer pages.RemovePage(historyPage)
		switch tc.Text {
		case "load":
			history, err := loadHistoryChat(selectedChat)
			if err != nil {
				logger.Error("failed to read history file", "chat", selectedChat)
				pages.RemovePage(historyPage)
				return
			}
			chatBody.Messages = history
			textView.SetText(chatToText(cfg.ShowSys))
			activeChatName = selectedChat
			pages.RemovePage(historyPage)
			return
		case "rename":
			pages.RemovePage(historyPage)
			pages.AddPage(renamePage, renameWindow, true, true)
			return
		case "delete":
			sc, ok := chatMap[selectedChat]
			if !ok {
				// no chat found
				pages.RemovePage(historyPage)
				return
			}
			if err := store.RemoveChat(sc.ID); err != nil {
				logger.Error("failed to remove chat from db", "chat_id", sc.ID, "chat_name", sc.Name)
			}
			if err := notifyUser("chat deleted", selectedChat+" was deleted"); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			// load last chat
			chatBody.Messages = loadOldChatOrGetNew()
			textView.SetText(chatToText(cfg.ShowSys))
			pages.RemovePage(historyPage)
			return
		case "update card":
			// save updated card
			fi := strings.Index(selectedChat, "_")
			agentName := selectedChat[fi+1:]
			cc, ok := sysMap[agentName]
			if !ok {
				logger.Warn("no such card", "agent", agentName)
				//no:lint
				if err := notifyUser("error", "no such card: "+agentName); err != nil {
					logger.Warn("failed ot notify", "error", err)
				}
				return
			}
			// if chatBody.Messages[0].Role != "system" || chatBody.Messages[1].Role != agentName {
			// 	if err := notifyUser("error", "unexpected chat structure; card: "+agentName); err != nil {
			// 		logger.Warn("failed ot notify", "error", err)
			// 	}
			// 	return
			// }
			// change sys_prompt + first msg
			cc.SysPrompt = chatBody.Messages[0].Content
			cc.FirstMsg = chatBody.Messages[1].Content
			if err := pngmeta.WriteToPng(cc.ToSpec(cfg.UserRole), cc.FilePath, cc.FilePath); err != nil {
				logger.Error("failed to write charcard",
					"error", err)
			}
			return
		case "move sysprompt onto 1st msg":
			chatBody.Messages[1].Content = chatBody.Messages[0].Content + chatBody.Messages[1].Content
			chatBody.Messages[0].Content = rpDefenitionSysMsg
			textView.SetText(chatToText(cfg.ShowSys))
			activeChatName = selectedChat
			pages.RemovePage(historyPage)
			return
		case "new_chat_from_card":
			// Reread card from file and start fresh chat
			fi := strings.Index(selectedChat, "_")
			agentName := selectedChat[fi+1:]
			cc, ok := sysMap[agentName]
			if !ok {
				logger.Warn("no such card", "agent", agentName)
				if err := notifyUser("error", "no such card: "+agentName); err != nil {
					logger.Warn("failed to notify", "error", err)
				}
				return
			}
			// Reload card from disk
			newCard, err := pngmeta.ReadCard(cc.FilePath, cfg.UserRole)
			if err != nil {
				logger.Error("failed to reload charcard", "path", cc.FilePath, "error", err)
				newCard, err = pngmeta.ReadCardJson(cc.FilePath)
				if err != nil {
					logger.Error("failed to reload charcard", "path", cc.FilePath, "error", err)
					if err := notifyUser("error", "failed to reload card: "+cc.FilePath); err != nil {
						logger.Warn("failed to notify", "error", err)
					}
					return
				}
			}
			// Update sysMap with fresh card data
			sysMap[agentName] = newCard
			applyCharCard(newCard)
			startNewChat()
			pages.RemovePage(historyPage)
			return
		default:
			return
		}
	})
	return chatActTable
}

// nolint:unused
func makeRAGTable(fileList []string) *tview.Flex {
	actions := []string{"load", "delete"}
	rows, cols := len(fileList), len(actions)+1
	fileTable := tview.NewTable().
		SetBorders(true)
	longStatusView := tview.NewTextView()
	longStatusView.SetText("status text")
	longStatusView.SetBorder(true).SetTitle("status")
	longStatusView.SetChangedFunc(func() {
		app.Draw()
	})
	ragflex := tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(longStatusView, 0, 10, false).
		AddItem(fileTable, 0, 60, true)
	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			color := tcell.ColorWhite
			if c < 1 {
				fileTable.SetCell(r, c,
					tview.NewTableCell(fileList[r]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			} else {
				fileTable.SetCell(r, c,
					tview.NewTableCell(actions[c-1]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			}
		}
	}
	errCh := make(chan error, 1)
	go func() {
		defer pages.RemovePage(RAGPage)
		for {
			select {
			case err := <-errCh:
				if err == nil {
					logger.Error("somehow got a nil err", "error", err)
					continue
				}
				logger.Error("got an err in rag status", "error", err, "textview", longStatusView)
				longStatusView.SetText(fmt.Sprintf("%v", err))
				close(errCh)
				return
			case status := <-rag.LongJobStatusCh:
				longStatusView.SetText(status)
				// fmt.Fprintln(longStatusView, status)
				// app.Sync()
				if status == rag.FinishedRAGStatus {
					close(errCh)
					time.Sleep(2 * time.Second)
					return
				}
			}
		}
	}()
	fileTable.Select(0, 0).SetFixed(1, 1).SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEsc || key == tcell.KeyF1 {
			pages.RemovePage(RAGPage)
			return
		}
		if key == tcell.KeyEnter {
			fileTable.SetSelectable(true, true)
		}
	}).SetSelectedFunc(func(row int, column int) {
		// defer pages.RemovePage(RAGPage)
		tc := fileTable.GetCell(row, column)
		tc.SetTextColor(tcell.ColorRed)
		fileTable.SetSelectable(false, false)
		fpath := fileList[row]
		// notification := fmt.Sprintf("chat: %s; action: %s", fpath, tc.Text)
		switch tc.Text {
		case "load":
			fpath = path.Join(cfg.RAGDir, fpath)
			longStatusView.SetText("clicked load")
			go func() {
				if err := ragger.LoadRAG(fpath); err != nil {
					logger.Error("failed to embed file", "chat", fpath, "error", err)
					errCh <- err
					// pages.RemovePage(RAGPage)
					return
				}
			}()
			return
		case "delete":
			fpath = path.Join(cfg.RAGDir, fpath)
			if err := os.Remove(fpath); err != nil {
				logger.Error("failed to delete file", "filename", fpath, "error", err)
				return
			}
			if err := notifyUser("chat deleted", fpath+" was deleted"); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			return
		default:
			return
		}
	})
	return ragflex
}

// func makeLoadedRAGTable(fileList []string) *tview.Table {
// 	actions := []string{"delete"}
// 	rows, cols := len(fileList), len(actions)+1
// 	fileTable := tview.NewTable().
// 		SetBorders(true)
// 	for r := 0; r < rows; r++ {
// 		for c := 0; c < cols; c++ {
// 			color := tcell.ColorWhite
// 			if c < 1 {
// 				fileTable.SetCell(r, c,
// 					tview.NewTableCell(fileList[r]).
// 						SetTextColor(color).
// 						SetAlign(tview.AlignCenter))
// 			} else {
// 				fileTable.SetCell(r, c,
// 					tview.NewTableCell(actions[c-1]).
// 						SetTextColor(color).
// 						SetAlign(tview.AlignCenter))
// 			}
// 		}
// 	}
// 	fileTable.Select(0, 0).SetFixed(1, 1).SetDoneFunc(func(key tcell.Key) {
// 		if key == tcell.KeyEsc || key == tcell.KeyF1 {
// 			pages.RemovePage(RAGPage)
// 			return
// 		}
// 		if key == tcell.KeyEnter {
// 			fileTable.SetSelectable(true, true)
// 		}
// 	}).SetSelectedFunc(func(row int, column int) {
// 		defer pages.RemovePage(RAGPage)
// 		tc := fileTable.GetCell(row, column)
// 		tc.SetTextColor(tcell.ColorRed)
// 		fileTable.SetSelectable(false, false)
// 		fpath := fileList[row]
// 		// notification := fmt.Sprintf("chat: %s; action: %s", fpath, tc.Text)
// 		switch tc.Text {
// 		case "delete":
// 			if err := ragger.RemoveFile(fpath); err != nil {
// 				logger.Error("failed to delete file", "filename", fpath, "error", err)
// 				return
// 			}
// 			if err := notifyUser("chat deleted", fpath+" was deleted"); err != nil {
// 				logger.Error("failed to send notification", "error", err)
// 			}
// 			return
// 		default:
// 			// pages.RemovePage(RAGPage)
// 			return
// 		}
// 	})
// 	return fileTable
// }

func makeAgentTable(agentList []string) *tview.Table {
	actions := []string{"load"}
	rows, cols := len(agentList), len(actions)+1
	chatActTable := tview.NewTable().
		SetBorders(true)
	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			color := tcell.ColorWhite
			if c < 1 {
				chatActTable.SetCell(r, c,
					tview.NewTableCell(agentList[r]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			} else {
				chatActTable.SetCell(r, c,
					tview.NewTableCell(actions[c-1]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			}
		}
	}
	chatActTable.Select(0, 0).SetFixed(1, 1).SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEsc || key == tcell.KeyF1 {
			pages.RemovePage(agentPage)
			return
		}
		if key == tcell.KeyEnter {
			chatActTable.SetSelectable(true, true)
		}
	}).SetSelectedFunc(func(row int, column int) {
		tc := chatActTable.GetCell(row, column)
		tc.SetTextColor(tcell.ColorRed)
		chatActTable.SetSelectable(false, false)
		selected := agentList[row]
		// notification := fmt.Sprintf("chat: %s; action: %s", selectedChat, tc.Text)
		switch tc.Text {
		case "load":
			if ok := charToStart(selected); !ok {
				logger.Warn("no such sys msg", "name", selected)
				pages.RemovePage(agentPage)
				return
			}
			// replace textview
			textView.SetText(chatToText(cfg.ShowSys))
			colorText()
			updateStatusLine()
			// sysModal.ClearButtons()
			pages.RemovePage(agentPage)
			app.SetFocus(textArea)
			return
		case "rename":
			pages.RemovePage(agentPage)
			pages.AddPage(renamePage, renameWindow, true, true)
			return
		case "delete":
			sc, ok := chatMap[selected]
			if !ok {
				// no chat found
				pages.RemovePage(agentPage)
				return
			}
			if err := store.RemoveChat(sc.ID); err != nil {
				logger.Error("failed to remove chat from db", "chat_id", sc.ID, "chat_name", sc.Name)
			}
			if err := notifyUser("chat deleted", selected+" was deleted"); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			pages.RemovePage(agentPage)
			return
		default:
			pages.RemovePage(agentPage)
			return
		}
	})
	return chatActTable
}

func makeCodeBlockTable(codeBlocks []string) *tview.Table {
	actions := []string{"copy"}
	rows, cols := len(codeBlocks), len(actions)+1
	table := tview.NewTable().
		SetBorders(true)
	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			color := tcell.ColorWhite
			previewLen := 30
			if len(codeBlocks[r]) < 30 {
				previewLen = len(codeBlocks[r])
			}
			if c < 1 {
				table.SetCell(r, c,
					tview.NewTableCell(codeBlocks[r][:previewLen]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			} else {
				table.SetCell(r, c,
					tview.NewTableCell(actions[c-1]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			}
		}
	}
	table.Select(0, 0).SetFixed(1, 1).SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEsc || key == tcell.KeyF1 {
			pages.RemovePage(agentPage)
			return
		}
		if key == tcell.KeyEnter {
			table.SetSelectable(true, true)
		}
	}).SetSelectedFunc(func(row int, column int) {
		tc := table.GetCell(row, column)
		tc.SetTextColor(tcell.ColorRed)
		table.SetSelectable(false, false)
		selected := codeBlocks[row]
		// notification := fmt.Sprintf("chat: %s; action: %s", selectedChat, tc.Text)
		switch tc.Text {
		case "copy":
			if err := copyToClipboard(selected); err != nil {
				if err := notifyUser("error", err.Error()); err != nil {
					logger.Error("failed to send notification", "error", err)
				}
			}
			if err := notifyUser("copied", selected); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			pages.RemovePage(codeBlockPage)
			app.SetFocus(textArea)
			return
		default:
			pages.RemovePage(codeBlockPage)
			return
		}
	})
	return table
}

func makeImportChatTable(filenames []string) *tview.Table {
	actions := []string{"load"}
	rows, cols := len(filenames), len(actions)+1
	chatActTable := tview.NewTable().
		SetBorders(true)
	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			color := tcell.ColorWhite
			if c < 1 {
				chatActTable.SetCell(r, c,
					tview.NewTableCell(filenames[r]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			} else {
				chatActTable.SetCell(r, c,
					tview.NewTableCell(actions[c-1]).
						SetTextColor(color).
						SetAlign(tview.AlignCenter))
			}
		}
	}
	chatActTable.Select(0, 0).SetFixed(1, 1).SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEsc || key == tcell.KeyF1 {
			pages.RemovePage(historyPage)
			return
		}
		if key == tcell.KeyEnter {
			chatActTable.SetSelectable(true, true)
		}
	}).SetSelectedFunc(func(row int, column int) {
		tc := chatActTable.GetCell(row, column)
		tc.SetTextColor(tcell.ColorRed)
		chatActTable.SetSelectable(false, false)
		selected := filenames[row]
		// notification := fmt.Sprintf("chat: %s; action: %s", selectedChat, tc.Text)
		switch tc.Text {
		case "load":
			if err := importChat(selected); err != nil {
				logger.Warn("failed to import chat", "filename", selected)
				pages.RemovePage(historyPage)
				return
			}
			colorText()
			updateStatusLine()
			// redraw the text in text area
			textView.SetText(chatToText(cfg.ShowSys))
			pages.RemovePage(historyPage)
			app.SetFocus(textArea)
			return
		case "rename":
			pages.RemovePage(historyPage)
			pages.AddPage(renamePage, renameWindow, true, true)
			return
		case "delete":
			sc, ok := chatMap[selected]
			if !ok {
				// no chat found
				pages.RemovePage(historyPage)
				return
			}
			if err := store.RemoveChat(sc.ID); err != nil {
				logger.Error("failed to remove chat from db", "chat_id", sc.ID, "chat_name", sc.Name)
			}
			if err := notifyUser("chat deleted", selected+" was deleted"); err != nil {
				logger.Error("failed to send notification", "error", err)
			}
			pages.RemovePage(historyPage)
			return
		default:
			pages.RemovePage(historyPage)
			return
		}
	})
	return chatActTable
}

func makeFilePicker() *tview.Flex {
	// Initialize with directory from config or current directory
	startDir := cfg.FilePickerDir
	if startDir == "" {
		startDir = "."
	}

	// If startDir is ".", resolve it to the actual current working directory
	if startDir == "." {
		wd, err := os.Getwd()
		if err == nil {
			startDir = wd
		}
	}

	// Track navigation history
	dirStack := []string{startDir}
	currentStackPos := 0

	// Track selected file
	var selectedFile string

	// Track currently displayed directory (changes as user navigates)
	var currentDisplayDir string = startDir

	// Create UI elements
	listView := tview.NewList()
	listView.SetBorder(true).SetTitle("Files & Directories").SetTitleAlign(tview.AlignLeft)

	// Path input field
	pathInput := tview.NewInputField().
		SetLabel("Path: ").
		SetText(startDir).
		SetFieldWidth(50)
	pathInput.SetBorder(true).SetTitle("Enter Path").SetTitleAlign(tview.AlignLeft)

	statusView := tview.NewTextView()
	statusView.SetBorder(true).SetTitle("Selected File").SetTitleAlign(tview.AlignLeft)
	statusView.SetTextColor(tcell.ColorYellow)

	buttonBar := tview.NewFlex()

	// Button functions
	loadButton := tview.NewButton("Load")
	loadButton.SetSelectedFunc(func() {
		if selectedFile != "" {
			// Update the global text area with the selected file path
			textArea.SetText(selectedFile, true)
			app.SetFocus(textArea)
		}
		pages.RemovePage(filePickerPage)
	})

	cancelButton := tview.NewButton("Cancel")
	cancelButton.SetSelectedFunc(func() {
		pages.RemovePage(filePickerPage)
	})

	// Path input button - will be updated after refreshList is defined
	goButton := tview.NewButton("Go")

	buttonBar.AddItem(tview.NewBox().SetBackgroundColor(tcell.ColorDefault), 0, 1, false)
	buttonBar.AddItem(goButton, 5, 1, true)
	buttonBar.AddItem(tview.NewBox(), 1, 1, false)
	buttonBar.AddItem(loadButton, 8, 1, true)
	buttonBar.AddItem(tview.NewBox(), 1, 1, false)
	buttonBar.AddItem(cancelButton, 8, 1, true)
	buttonBar.AddItem(tview.NewBox().SetBackgroundColor(tcell.ColorDefault), 0, 1, false)

	// Layout - add path input field at the top
	flex := tview.NewFlex().SetDirection(tview.FlexRow)
	flex.AddItem(pathInput, 3, 0, false)
	flex.AddItem(listView, 0, 3, true)
	flex.AddItem(statusView, 3, 0, false)
	flex.AddItem(buttonBar, 3, 0, false)

	// Refresh the file list
	var refreshList func(string)
	refreshList = func(dir string) {
		listView.Clear()

		// Update the path input field and current display directory
		pathInput.SetText(dir)
		currentDisplayDir = dir // Update the current display directory

		// Add parent directory (..) if not at root
		if dir != "/" {
			parentDir := path.Dir(dir)
			// Special handling for edge cases - only return if we're truly at a system root
			// For Unix-like systems, path.Dir("/") returns "/" which would cause parentDir == dir
			if parentDir == dir && dir == "/" {
				// We're at the root ("/") and trying to go up, just don't add the parent item
			} else {
				listView.AddItem("../", "(Parent Directory)", 'p', func() {
					refreshList(parentDir)
					dirStack = append(dirStack, parentDir)
					currentStackPos = len(dirStack) - 1
				})
			}
		}

		// Read directory contents
		files, err := os.ReadDir(dir)
		if err != nil {
			statusView.SetText("Error reading directory: " + err.Error())
			return
		}

		// Add directories and files to the list
		for _, file := range files {
			name := file.Name()
			if file.IsDir() {
				// Capture the directory name for the closure to avoid loop variable issues
				dirName := name
				listView.AddItem(dirName+"/", "(Directory)", 0, func() {
					newDir := path.Join(dir, dirName)
					refreshList(newDir)
					dirStack = append(dirStack, newDir)
					currentStackPos = len(dirStack) - 1
					statusView.SetText("Current: " + newDir)
				})
			} else {
				// Capture the file name for the closure to avoid loop variable issues
				fileName := name
				listView.AddItem(fileName, "(File)", 0, func() {
					selectedFile = path.Join(dir, fileName)
					statusView.SetText("Selected: " + selectedFile)
				})
			}
		}

		statusView.SetText("Current: " + dir)
	}

	// Initialize the file list
	refreshList(startDir)

	// Set up keyboard navigation for the path input
	pathInput.SetDoneFunc(func(key tcell.Key) {
		if key == tcell.KeyEnter {
			// Trigger the Go functionality when Enter is pressed in the path input
			newPath := pathInput.GetText()
			if newPath != "" {
				// Check if path exists and is a directory
				if info, err := os.Stat(newPath); err == nil && info.IsDir() {
					refreshList(newPath)
					dirStack = append(dirStack, newPath)
					currentStackPos = len(dirStack) - 1
					statusView.SetText("Current: " + newPath)
				} else {
					statusView.SetText("Invalid directory: " + newPath)
				}
			}
		}
	})

	// Now that refreshList is defined, set the Go button's functionality
	goButton.SetSelectedFunc(func() {
		newPath := pathInput.GetText()
		if newPath != "" {
			// Check if path exists and is a directory
			if info, err := os.Stat(newPath); err == nil && info.IsDir() {
				refreshList(newPath)
				dirStack = append(dirStack, newPath)
				currentStackPos = len(dirStack) - 1
				statusView.SetText("Current: " + newPath)
			} else {
				statusView.SetText("Invalid directory: " + newPath)
			}
		}
	})

	// Set up keyboard navigation
	flex.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		switch event.Key() {
		case tcell.KeyEsc:
			pages.RemovePage(filePickerPage)
			return nil
		case tcell.KeyBackspace2: // Backspace to go to parent directory
			if currentStackPos > 0 {
				currentStackPos--
				prevDir := dirStack[currentStackPos]
				refreshList(prevDir)
				// Trim the stack to current position to avoid deep history
				dirStack = dirStack[:currentStackPos+1]
			}
			return nil
		case tcell.KeyEnter:
			// Get the currently highlighted item in the list
			itemIndex := listView.GetCurrentItem()
			if itemIndex >= 0 && itemIndex < listView.GetItemCount() {
				// We need to get the text of the currently selected item to determine if it's a directory
				// Since we can't directly get the item text, we'll keep track of items differently
				// Let's improve the approach by tracking the currently selected item
				itemText, _ := listView.GetItemText(itemIndex)

				logger.Info("choosing dir", "itemText", itemText)
				// Check if it's a directory (typically ends with /)
				if strings.HasSuffix(itemText, "/") {
					// This is a directory, we need to get the full path
					// Since the item text ends with "/" and represents a directory
					var targetDir string
					if strings.HasPrefix(itemText, "../") {
						// Parent directory - need to go up from current directory
						targetDir = path.Dir(currentDisplayDir)
						// Avoid going above root - if parent is same as current and it's system root
						if targetDir == currentDisplayDir && currentDisplayDir == "/" {
							// We're at root, don't navigate
							logger.Warn("went to root", "dir", targetDir)
							return nil
						}
					} else {
						// Regular subdirectory
						dirName := strings.TrimSuffix(itemText, "/")
						targetDir = path.Join(currentDisplayDir, dirName)
					}

					// Navigate to the selected directory
					logger.Info("going to the dir", "dir", targetDir)
					refreshList(targetDir)
					dirStack = append(dirStack, targetDir)
					currentStackPos = len(dirStack) - 1
					statusView.SetText("Current: " + targetDir)
					return nil
				} else {
					// It's a file - construct the full path from current directory and the item name
					// We can't rely only on the selectedFile variable since Enter key might be pressed
					// without having clicked the file first
					filePath := path.Join(currentDisplayDir, itemText)
					// Verify it's actually a file (not just lacking a directory suffix)
					if info, err := os.Stat(filePath); err == nil && !info.IsDir() {
						textArea.SetText(filePath, true)
						app.SetFocus(textArea)
						pages.RemovePage(filePickerPage)
					}
					return nil
				}
			}
			return nil
		}
		return event
	})

	return flex
}