summaryrefslogtreecommitdiff
path: root/internal/tui/tui_test.go
blob: ad529fc6780c9869874cd2315d1d663d64413a2d (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
package tui

import (
	"context"
	"errors"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
	"time"

	coreflamegraph "ior/internal/flamegraph"
	"ior/internal/probemanager"
	"ior/internal/statsengine"
	dashboardui "ior/internal/tui/dashboard"
	"ior/internal/tui/eventstream"
	tuiexport "ior/internal/tui/export"
	"ior/internal/tui/messages"

	"ior/internal/flags"
	"ior/internal/tui/probes"

	"charm.land/bubbles/v2/key"
	tea "charm.land/bubbletea/v2"
	"charm.land/lipgloss/v2"
)

type fakeProbeManager struct {
	states []probemanager.ProbeState
}

func (f fakeProbeManager) States() []probemanager.ProbeState { return f.states }
func (f fakeProbeManager) Toggle(string) error               { return nil }
func (f fakeProbeManager) ActiveCount() (int, int)           { return len(f.states), len(f.states) }

func TestPidSelectedTransitionsToDashboardAndSetsPIDFilter(t *testing.T) {
	flags.SetPidFilter(-1)
	flags.SetTidFilter(99)
	m := NewModel(-1, func(context.Context) error { return nil })

	next, cmd := m.Update(PidSelectedMsg{Pid: 42})
	if cmd == nil {
		t.Fatalf("expected tracing start command")
	}

	updated := next.(Model)
	if updated.screen != ScreenDashboard {
		t.Fatalf("expected dashboard screen, got %v", updated.screen)
	}
	if !updated.attaching {
		t.Fatalf("expected attaching state to be true")
	}
	if updated.pidFilter != 42 {
		t.Fatalf("expected pid filter 42, got %d", updated.pidFilter)
	}
	if updated.tidFilter != -1 {
		t.Fatalf("expected tid filter reset to -1, got %d", updated.tidFilter)
	}
}

func TestInitialPIDSkipsPickerAndStartsTracing(t *testing.T) {
	flags.SetPidFilter(-1)
	m := NewModel(7, func(context.Context) error { return nil })

	if m.screen != ScreenDashboard {
		t.Fatalf("expected initial screen dashboard, got %v", m.screen)
	}

	cmd := m.Init()
	if cmd == nil {
		t.Fatalf("expected init command when initial pid is set")
	}
}

func TestPidSelectedAllSetsNoFilter(t *testing.T) {
	flags.SetPidFilter(999)
	m := NewModel(-1, func(context.Context) error { return nil })

	next, _ := m.Update(PidSelectedMsg{Pid: 0})
	updated := next.(Model)

	if updated.pidFilter != -1 {
		t.Fatalf("expected pid filter -1 for all pids, got %d", updated.pidFilter)
	}
}

func TestTracingErrorMessageClearsAttachingState(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.attaching = true

	next, _ := m.Update(TracingErrorMsg{Err: errors.New("boom")})
	updated := next.(Model)
	if updated.attaching {
		t.Fatalf("expected attaching to be false after tracing error")
	}
	if updated.lastErr == nil || updated.lastErr.Error() != "boom" {
		t.Fatalf("expected tracing error to be stored")
	}
}

func TestViewShowsAttachingAndErrorStates(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.attaching = true
	attachingView := m.View().Content
	if !strings.Contains(attachingView, "Attaching tracepoints...") {
		t.Fatalf("expected attaching view, got %q", attachingView)
	}

	m.attaching = false
	m.lastErr = errors.New("failed")
	errorView := m.View().Content
	if !strings.Contains(errorView, "failed") {
		t.Fatalf("expected error view, got %q", errorView)
	}
}

func TestQuitKeySetsQuittingState(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })

	next, cmd := m.Update(tea.KeyPressMsg{Code: []rune{'q'}[0], Text: string([]rune{'q'})})
	if cmd == nil {
		t.Fatalf("expected quit cmd")
	}
	if _, ok := cmd().(tea.QuitMsg); !ok {
		t.Fatalf("expected tea.QuitMsg")
	}

	updated := next.(Model)
	if !updated.quitting {
		t.Fatalf("expected quitting state")
	}
}

func TestQuitKeyMatchesSingleBindingWithoutPanic(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.keys.Quit = key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "quit"))

	_, _ = m.Update(tea.KeyPressMsg{Code: []rune{'z'}[0], Text: string([]rune{'z'})})

	next, cmd := m.Update(tea.KeyPressMsg{Code: []rune{'x'}[0], Text: string([]rune{'x'})})
	if cmd == nil {
		t.Fatalf("expected quit cmd")
	}
	updated := next.(Model)
	if !updated.quitting {
		t.Fatalf("expected quitting state")
	}
}

func TestStartTraceCmdLaunchesBeforeStarterReturns(t *testing.T) {
	cmd := startTraceCmd(func(context.Context) error { return nil }, context.Background())
	msg := cmd()
	if _, ok := msg.(TracingStartedMsg); !ok {
		t.Fatalf("expected TracingStartedMsg, got %T", msg)
	}
}

func TestStartTraceCmdEmitsErrorMsg(t *testing.T) {
	cmd := startTraceCmd(func(context.Context) error { return errors.New("trace failed") }, context.Background())
	msg := cmd()
	traceErr, ok := msg.(TracingErrorMsg)
	if !ok {
		t.Fatalf("expected TracingErrorMsg, got %T", msg)
	}
	if traceErr.Err == nil || traceErr.Err.Error() != "trace failed" {
		t.Fatalf("unexpected trace error message: %+v", traceErr)
	}
}

func TestQuitInvokesTraceStop(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	done := make(chan struct{})
	m.traceStop = func() {
		close(done)
	}

	_, quitCmd := m.Update(tea.KeyPressMsg{Code: []rune{'q'}[0], Text: string([]rune{'q'})})
	if quitCmd == nil {
		t.Fatalf("expected quit command")
	}

	select {
	case <-done:
	case <-time.After(200 * time.Millisecond):
		t.Fatalf("expected stopTrace to be invoked on quit")
	}
}

type fakeDashboardSource struct {
	snap *statsengine.Snapshot
}

func (f fakeDashboardSource) Snapshot() *statsengine.Snapshot {
	return f.snap
}

type fakeResettableDashboardSource struct {
	snap       *statsengine.Snapshot
	resetCalls int
}

func (f *fakeResettableDashboardSource) Snapshot() *statsengine.Snapshot {
	return f.snap
}

func (f *fakeResettableDashboardSource) Reset() {
	f.resetCalls++
	f.snap = &statsengine.Snapshot{TotalSyscalls: 0}
}

func TestDashboardRefreshPicksLateBoundSource(t *testing.T) {
	runtime := newRuntimeBindings()
	source := lateBoundDashboardSource{runtime: runtime}

	want := &statsengine.Snapshot{TotalSyscalls: 77}
	runtime.SetDashboardSnapshotSource(fakeDashboardSource{snap: want})

	got := source.Snapshot()
	if got != want {
		t.Fatalf("expected late-bound source to use latest runtime source")
	}
}

func TestRuntimeBindingsStoreAndExposeLiveTrie(t *testing.T) {
	runtime := newRuntimeBindings()
	trie := coreflamegraph.NewLiveTrie([]string{"comm", "path"}, "count")
	runtime.SetLiveTrie(trie)
	if got := runtime.liveTrie(); got != trie {
		t.Fatalf("expected live trie to be stored and returned")
	}

	runtime.SetLiveTrie(nil)
	if got := runtime.liveTrie(); got != nil {
		t.Fatalf("expected live trie to clear on nil assignment")
	}
}

func TestProbeToggledMsgResetsDashboardStatsSource(t *testing.T) {
	src := &fakeResettableDashboardSource{snap: &statsengine.Snapshot{TotalSyscalls: 99}}

	m := NewModel(-1, func(context.Context) error { return nil })
	m.runtime.SetDashboardSnapshotSource(src)
	m.screen = ScreenDashboard
	m.attaching = false
	m.probeModal = probes.NewModel(fakeProbeManager{states: []probemanager.ProbeState{{Syscall: "read", Active: true}}}).Open()

	next, _ := m.Update(probes.ProbeToggledMsg{Syscall: "read"})
	updated := next.(Model)

	if src.resetCalls != 1 {
		t.Fatalf("expected one reset call, got %d", src.resetCalls)
	}
	snap := updated.dashboard.LatestSnapshot()
	if snap == nil || snap.TotalSyscalls != 0 {
		t.Fatalf("expected dashboard snapshot refreshed from reset source, got %+v", snap)
	}
}

func TestTracingStartedRebindsEventStreamSource(t *testing.T) {
	rb := eventstream.NewRingBuffer()
	rb.Push(eventstream.StreamEvent{Seq: 1, Syscall: "read", Comm: "proc", PID: 1, TID: 1})

	m := NewModel(-1, func(context.Context) error { return nil })
	m.runtime.SetEventStreamSource(rb)
	m.screen = ScreenDashboard
	m.attaching = true

	next, _ := m.Update(TracingStartedMsg{})
	m = next.(Model)

	next, _ = m.Update(tea.WindowSizeMsg{Width: 120, Height: 30})
	m = next.(Model)
	next, _ = m.Update(tea.KeyPressMsg{Code: []rune{'7'}[0], Text: string([]rune{'7'})})
	m = next.(Model)
	next, _ = m.Update(messages.StatsTickMsg{})
	m = next.(Model)

	if !strings.Contains(m.View().Content, "read") {
		t.Fatalf("expected stream tab to render rebound stream event")
	}
}

func TestTracingStartedUsesCurrentViewportForFlameNavigationWithoutResize(t *testing.T) {
	trie := coreflamegraph.NewLiveTrie([]string{"comm", "path", "tracepoint"}, "count")
	coreflamegraph.SeedTestFlameData(trie)

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = true
	m.width = 120
	m.height = 30
	m.runtime.SetLiveTrie(trie)

	next, _ := m.Update(TracingStartedMsg{})
	m = next.(Model)

	if strings.Contains(m.View().Content, "sel:none") {
		t.Fatalf("expected flamegraph selection to be available immediately after tracing start")
	}

	selectedLabel := func(view string) string {
		re := regexp.MustCompile(`sel:[0-9]+/[0-9]+ ([^|]+) \|`)
		match := re.FindStringSubmatch(view)
		if len(match) != 2 {
			return ""
		}
		return strings.TrimSpace(match[1])
	}

	moved := false
	before := selectedLabel(m.View().Content)
	for i := 0; i < 12 && !moved; i++ {
		next, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyRight})
		m = next.(Model)
		after := selectedLabel(m.View().Content)
		if after != "" && after != before {
			moved = true
			break
		}
	}
	if !moved {
		t.Fatalf("expected arrow navigation to move selection without requiring resize, view=%q", m.View().Content)
	}
}

func TestTracingStartedAppliesViewportWhenModelSizeIsUnset(t *testing.T) {
	trie := coreflamegraph.NewLiveTrie([]string{"comm", "path", "tracepoint"}, "count")
	coreflamegraph.SeedTestFlameData(trie)

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = true
	m.runtime.SetLiveTrie(trie)
	m.width = 0
	m.height = 0

	next, _ := m.Update(TracingStartedMsg{})
	m = next.(Model)

	view := m.View().Content
	if strings.Contains(view, "sel:none") {
		t.Fatalf("expected tracing start to apply an effective viewport even when width/height are unset")
	}
}

func TestExportKeyOpensModalOnDashboard(t *testing.T) {
	flags.SetTUIExportEnable(true)
	t.Cleanup(func() { flags.SetTUIExportEnable(true) })

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'e'}[0], Text: string([]rune{'e'})})
	updated := next.(Model)
	if !updated.exporter.Visible() {
		t.Fatalf("expected export modal to open on e key")
	}
}

func TestFlamePauseKeyDoesNotTriggerPIDReselect(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
	updated := next.(Model)
	if updated.screen != ScreenDashboard {
		t.Fatalf("expected flame space key to keep dashboard screen, got %v", updated.screen)
	}
	if !strings.Contains(updated.View().Content, "[PAUSED]") {
		t.Fatalf("expected flame space key to toggle flame paused state")
	}
}

func TestFlameSpaceKeyReleaseFallbackTogglesPause(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyReleaseMsg{Code: tea.KeySpace, Text: " "})
	updated := next.(Model)
	if !strings.Contains(updated.View().Content, "[PAUSED]") {
		t.Fatalf("expected key release fallback to toggle flame paused state")
	}
}

func TestFlameSpacePressReleaseDoesNotDoubleTogglePause(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
	updated := next.(Model)
	if !strings.Contains(updated.View().Content, "[PAUSED]") {
		t.Fatalf("expected key press to pause flame")
	}

	next, _ = updated.Update(tea.KeyReleaseMsg{Code: tea.KeySpace, Text: " "})
	updated = next.(Model)
	if !strings.Contains(updated.View().Content, "[PAUSED]") {
		t.Fatalf("expected key release after key press to be ignored as duplicate")
	}
}

func TestFlameSpaceReleasePressDoesNotDoubleTogglePause(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyReleaseMsg{Code: tea.KeySpace, Text: " "})
	updated := next.(Model)
	if !strings.Contains(updated.View().Content, "[PAUSED]") {
		t.Fatalf("expected key release fallback to pause flame")
	}

	next, _ = updated.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
	updated = next.(Model)
	if !strings.Contains(updated.View().Content, "[PAUSED]") {
		t.Fatalf("expected immediate matching key press after release fallback to be ignored")
	}
}

func TestNormalizeKeyEventReleaseFallbackSuppressesImmediatePressOnly(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })

	normalized, ok := m.normalizeKeyEvent(tea.KeyReleaseMsg{Code: tea.KeySpace, Text: " "})
	if !ok {
		t.Fatalf("expected release fallback to be handled")
	}
	if _, isPress := normalized.(tea.KeyPressMsg); !isPress {
		t.Fatalf("expected release fallback to normalize to KeyPressMsg, got %T", normalized)
	}

	if normalized, ok = m.normalizeKeyEvent(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "}); ok {
		t.Fatalf("expected immediate matching press to be suppressed, got %T", normalized)
	}

	time.Sleep(70 * time.Millisecond)
	if normalized, ok = m.normalizeKeyEvent(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "}); !ok {
		t.Fatalf("expected press to be accepted after suppression window")
	}
	if _, isPress := normalized.(tea.KeyPressMsg); !isPress {
		t.Fatalf("expected accepted message to be KeyPressMsg, got %T", normalized)
	}
}

func TestNormalizeKeyEventIgnoresUnidentifiedRelease(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })

	if normalized, ok := m.normalizeKeyEvent(tea.KeyReleaseMsg{}); ok {
		t.Fatalf("expected unidentified release to be ignored, got %T", normalized)
	}

	normalized, ok := m.normalizeKeyEvent(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
	if !ok {
		t.Fatalf("expected subsequent real key press to be handled")
	}
	if _, isPress := normalized.(tea.KeyPressMsg); !isPress {
		t.Fatalf("expected normalized message to be KeyPressMsg, got %T", normalized)
	}
}

func TestNormalizeKeyEventReleaseFallbackDoesNotSuppressArrowPress(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })

	normalized, ok := m.normalizeKeyEvent(tea.KeyReleaseMsg{Code: tea.KeyRight})
	if !ok {
		t.Fatalf("expected right release fallback to be handled")
	}
	if _, isPress := normalized.(tea.KeyPressMsg); !isPress {
		t.Fatalf("expected release fallback to normalize to KeyPressMsg, got %T", normalized)
	}

	normalized, ok = m.normalizeKeyEvent(tea.KeyPressMsg{Code: tea.KeyRight})
	if !ok {
		t.Fatalf("expected right key press to be accepted after release fallback")
	}
	if _, isPress := normalized.(tea.KeyPressMsg); !isPress {
		t.Fatalf("expected normalized message to be KeyPressMsg, got %T", normalized)
	}
}

func TestFlameOrderKeyDoesNotOpenProbeModal(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'o'}[0], Text: string([]rune{'o'})})
	updated := next.(Model)
	if updated.probeModal.Visible() {
		t.Fatalf("expected flame order key to stay in flame tab, not open probes modal")
	}
}

func TestFlameMetricKeyDoesNotOpenProbeModal(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'b'}[0], Text: string([]rune{'b'})})
	updated := next.(Model)
	if updated.probeModal.Visible() {
		t.Fatalf("expected flame metric key to stay in flame tab, not open probes modal")
	}
}

func TestSelectPIDKeyReturnsToFreshPickerAndStopsTrace(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30
	stopped := false
	m.traceStop = func() { stopped = true }

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'2'}[0], Text: string([]rune{'2'})})
	m = next.(Model)

	next, cmd := m.Update(tea.KeyPressMsg{Code: []rune{'p'}[0], Text: string([]rune{'p'})})
	updated := next.(Model)

	if !stopped {
		t.Fatalf("expected active tracing to be stopped before returning to picker")
	}
	if updated.screen != ScreenPIDPicker {
		t.Fatalf("expected PID picker screen, got %v", updated.screen)
	}
	if updated.attaching {
		t.Fatalf("expected attaching=false on picker screen")
	}
	if updated.traceStop != nil {
		t.Fatalf("expected traceStop to be cleared after stopping")
	}
	if cmd == nil {
		t.Fatalf("expected picker init command when returning to picker")
	}
}

func TestSelectTIDKeyReturnsToPickerWhenPIDFilterIsAll(t *testing.T) {
	flags.SetPidFilter(-1)
	flags.SetTidFilter(-1)
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	stopped := false
	m.traceStop = func() { stopped = true }

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'2'}[0], Text: string([]rune{'2'})})
	m = next.(Model)

	next, cmd := m.Update(tea.KeyPressMsg{Code: []rune{'t'}[0], Text: string([]rune{'t'})})
	updated := next.(Model)
	if !stopped {
		t.Fatalf("expected tracing stop before tid reselect")
	}
	if updated.screen != ScreenPIDPicker {
		t.Fatalf("expected picker screen, got %v", updated.screen)
	}
	if cmd == nil {
		t.Fatalf("expected picker init command")
	}
}

func TestSelectTIDKeyReturnsToPickerWhenSinglePIDSelected(t *testing.T) {
	flags.SetPidFilter(1234)
	flags.SetTidFilter(-1)
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	stopped := false
	m.traceStop = func() { stopped = true }

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'2'}[0], Text: string([]rune{'2'})})
	m = next.(Model)

	next, cmd := m.Update(tea.KeyPressMsg{Code: []rune{'t'}[0], Text: string([]rune{'t'})})
	updated := next.(Model)
	if !stopped {
		t.Fatalf("expected tracing stop before tid reselect")
	}
	if updated.screen != ScreenPIDPicker {
		t.Fatalf("expected picker screen, got %v", updated.screen)
	}
	if cmd == nil {
		t.Fatalf("expected picker init command")
	}
}

func TestTidSelectedTransitionsToDashboardAndSetsTIDFilter(t *testing.T) {
	flags.SetPidFilter(2222)
	flags.SetTidFilter(-1)
	m := NewModel(-1, func(context.Context) error { return nil })

	next, cmd := m.Update(TidSelectedMsg{Pid: 0, Tid: 3333})
	if cmd == nil {
		t.Fatalf("expected tracing start command")
	}
	updated := next.(Model)
	if updated.screen != ScreenDashboard {
		t.Fatalf("expected dashboard screen, got %v", updated.screen)
	}
	if !updated.attaching {
		t.Fatalf("expected attaching state to be true")
	}
	if updated.tidFilter != 3333 {
		t.Fatalf("expected tid filter 3333, got %d", updated.tidFilter)
	}
	if updated.pidFilter != 2222 {
		t.Fatalf("expected pid filter to remain 2222, got %d", updated.pidFilter)
	}
}

func TestTidSelectedFromAllPIDModeSetsOwningPID(t *testing.T) {
	flags.SetPidFilter(-1)
	flags.SetTidFilter(-1)
	m := NewModel(-1, func(context.Context) error { return nil })

	next, cmd := m.Update(TidSelectedMsg{Pid: 4444, Tid: 5555})
	if cmd == nil {
		t.Fatalf("expected tracing start command")
	}
	updated := next.(Model)
	if updated.screen != ScreenDashboard {
		t.Fatalf("expected dashboard screen, got %v", updated.screen)
	}
	if updated.pidFilter != 4444 {
		t.Fatalf("expected pid filter switched to owning pid 4444, got %d", updated.pidFilter)
	}
	if updated.tidFilter != 5555 {
		t.Fatalf("expected tid filter 5555, got %d", updated.tidFilter)
	}
}

func TestExportKeyIgnoredWhenExportDisabled(t *testing.T) {
	flags.SetTUIExportEnable(false)
	t.Cleanup(func() { flags.SetTUIExportEnable(true) })

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'e'}[0], Text: string([]rune{'e'})})
	updated := next.(Model)
	if updated.exporter.Visible() {
		t.Fatalf("expected export modal to remain closed when export is disabled")
	}
}

func TestStreamFilterModalConsumesEKeyInsteadOfOpeningExport(t *testing.T) {
	flags.SetTUIExportEnable(true)
	t.Cleanup(func() { flags.SetTUIExportEnable(true) })

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'7'}[0], Text: string([]rune{'7'})})
	m = next.(Model)
	next, _ = m.Update(tea.KeyPressMsg{Code: []rune{'f'}[0], Text: string([]rune{'f'})})
	m = next.(Model)
	next, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
	m = next.(Model)
	for _, r := range []rune{'o', 'p', 'e'} {
		next, _ = m.Update(tea.KeyPressMsg{Code: []rune{r}[0], Text: string([]rune{r})})
		m = next.(Model)
	}
	next, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEsc})
	m = next.(Model)

	if m.exporter.Visible() {
		t.Fatalf("expected export modal to remain closed while stream filter modal handles typing")
	}
	if !strings.Contains(m.View().Content, "syscall~ope") {
		t.Fatalf("expected typed syscall filter to be applied")
	}
}

func TestRunExportCmdCSVWritesFile(t *testing.T) {
	dir := t.TempDir()
	prev, err := os.Getwd()
	if err != nil {
		t.Fatalf("getwd: %v", err)
	}
	if err := os.Chdir(dir); err != nil {
		t.Fatalf("chdir temp dir: %v", err)
	}
	t.Cleanup(func() { _ = os.Chdir(prev) })

	snap := &statsengine.Snapshot{TotalSyscalls: 1}
	msg := runExportCmd(true, tuiexport.OptionCSV, snap)()
	done, ok := msg.(tuiexport.CompletedMsg)
	if !ok {
		t.Fatalf("expected CompletedMsg, got %T", msg)
	}
	if done.Path == "" {
		t.Fatalf("expected export path")
	}
	if _, err := os.Stat(filepath.Join(dir, done.Path)); err != nil {
		t.Fatalf("expected CSV file to exist: %v", err)
	}
}

func TestHelpKeyDoesNotToggleOverlay(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'?'}[0], Text: string([]rune{'?'})})
	updated := next.(Model)
	if updated.screen != ScreenPIDPicker {
		t.Fatalf("expected ? to have no effect, got screen %v", updated.screen)
	}
}

func TestViewShowsDashboardWithoutHelpOverlay(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.width = 100
	m.height = 30

	out := m.View().Content
	if !strings.Contains(out, "press H for help") {
		t.Fatalf("expected bottom help hint in dashboard")
	}
}

func TestHelpOverlayOpensWithUppercaseHAndClosesWithEsc(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 100
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'H'}[0], Text: string([]rune{'H'})})
	m = next.(Model)
	if !m.helpOverlayVisible {
		t.Fatalf("expected help overlay to become visible after H")
	}
	view := m.View().Content
	if !strings.Contains(view, "Help") || !strings.Contains(view, "Global") || !strings.Contains(view, "Esc close") {
		t.Fatalf("expected global help overlay content, got %q", view)
	}

	next, _ = m.Update(tea.KeyPressMsg{Code: tea.KeyEsc})
	m = next.(Model)
	if m.helpOverlayVisible {
		t.Fatalf("expected esc to close help overlay")
	}
	if !strings.Contains(m.View().Content, "press H for help") {
		t.Fatalf("expected dashboard help hint after closing overlay")
	}
}

func TestHelpOverlayCanOpenFromPIDPicker(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenPIDPicker
	m.width = 100
	m.height = 30

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'H'}[0], Text: string([]rune{'H'})})
	m = next.(Model)
	if !m.helpOverlayVisible {
		t.Fatalf("expected help overlay to open on pid picker screen")
	}
	if !strings.Contains(m.View().Content, "PID/TID Picker") {
		t.Fatalf("expected picker shortcuts in help overlay")
	}
}

func TestQuestionMarkDoesNotBlockUnderlyingActions(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'e'}[0], Text: string([]rune{'e'})})
	updated := next.(Model)
	if !updated.exporter.Visible() {
		t.Fatalf("expected export modal to open; ? overlay is removed")
	}
}

func TestQuestionMarkDoesNotBreakExportModalInput(t *testing.T) {
	flags.SetTUIExportEnable(true)
	t.Cleanup(func() { flags.SetTUIExportEnable(true) })

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'e'}[0], Text: string([]rune{'e'})})
	updated := next.(Model)
	if !updated.exporter.Visible() {
		t.Fatalf("expected export modal to open")
	}

	next, _ = updated.Update(tea.KeyPressMsg{Code: []rune{'?'}[0], Text: string([]rune{'?'})})
	updated = next.(Model)
	if !updated.exporter.Visible() {
		t.Fatalf("expected export modal to remain open after ? key")
	}

	next, _ = updated.Update(tea.KeyPressMsg{Code: tea.KeyEsc})
	updated = next.(Model)
	if updated.exporter.Visible() {
		t.Fatalf("expected esc to close export modal")
	}
}

func TestStatusBarHidesExportBindingWhenExportDisabled(t *testing.T) {
	flags.SetTUIExportEnable(false)
	t.Cleanup(func() { flags.SetTUIExportEnable(true) })

	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.width = 100
	m.height = 30

	out := m.View().Content
	if strings.Contains(out, "e snapshot export") {
		t.Fatalf("did not expect export shortcut in status bar when export is disabled")
	}
}

func TestExportModalStillAllowsDashboardStatsUpdates(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.exporter = m.exporter.Open()

	snap := &statsengine.Snapshot{TotalSyscalls: 99}
	next, _ := m.Update(StatsTickMsg{Snap: snap})
	updated := next.(Model)

	if got := updated.dashboard.LatestSnapshot(); got != snap {
		t.Fatalf("expected dashboard snapshot update while export modal visible")
	}
}

func TestDashboardTabKeysChangeActiveView(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30

	out := m.View().Content
	if !strings.Contains(out, "Flame: waiting for data") {
		t.Fatalf("expected flame waiting view by default")
	}

	next, _ := m.Update(tea.KeyPressMsg{Code: []rune{'2'}[0], Text: string([]rune{'2'})})
	updated := next.(Model)
	out = updated.View().Content
	if !strings.Contains(out, "Overview: waiting for stats") {
		t.Fatalf("expected overview waiting view after pressing 2")
	}

	next, _ = updated.Update(tea.KeyPressMsg{Code: tea.KeyTab})
	updated = next.(Model)
	out = updated.View().Content
	if !strings.Contains(out, "Syscalls: waiting for stats") {
		t.Fatalf("expected syscalls waiting view after tab")
	}
}

func TestProbeModalViewDoesNotStackDashboardContent(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.runtime.SetProbeManager(fakeProbeManager{states: []probemanager.ProbeState{{Syscall: "read", Active: true}}})
	m.probeModal = probes.NewModel(m.runtime.currentProbeManager())
	m.screen = ScreenDashboard
	m.attaching = false
	m.width = 120
	m.height = 30
	m.probeModal = m.probeModal.Open()

	out := m.View().Content
	if !strings.Contains(out, "Probes (") {
		t.Fatalf("expected probe modal content, got %q", out)
	}
	if strings.Contains(out, "Flame: waiting for data") || strings.Contains(out, "Overview: waiting for stats") {
		t.Fatalf("expected probe modal to render as standalone view, got stacked dashboard content")
	}
}

func TestBlurPausesDashboardRefreshAndFocusResumesIt(t *testing.T) {
	m := NewModel(-1, func(context.Context) error { return nil })
	m.screen = ScreenDashboard
	m.attaching = false
	m.dashboard = dashboardui.NewModelWithConfig(nil,