xonecas.io
60255
Zn

Zoea-Nova / files

Zoea-Nova / internal / tui / tui_test.go

29.5 KB
1package tui
2
3import (
4	"regexp"
5	"strings"
6	"testing"
7	"time"
8
9	tea "github.com/charmbracelet/bubbletea"
10	"github.com/charmbracelet/lipgloss"
11	"github.com/mattn/go-runewidth"
12	"github.com/xonecas/zoea-nova/internal/config"
13	"github.com/xonecas/zoea-nova/internal/core"
14	"github.com/xonecas/zoea-nova/internal/provider"
15	"github.com/xonecas/zoea-nova/internal/store"
16)
17
18// ansiRegex matches ANSI escape codes
19var ansiRegex = regexp.MustCompile(`\x1b\[[0-9;]*m`)
20
21// stripANSI removes all ANSI escape codes from a string
22func stripANSI(s string) string {
23	return ansiRegex.ReplaceAllString(s, "")
24}
25
26func setupTestModel(t *testing.T) (Model, func()) {
27	t.Helper()
28
29	s, err := store.OpenMemory()
30	if err != nil {
31		t.Fatalf("OpenMemory() error: %v", err)
32	}
33
34	bus := core.NewEventBus(100)
35	eventCh := bus.Subscribe()
36
37	reg := provider.NewRegistry()
38	reg.RegisterFactory("ollama-qwen", provider.NewMockFactory("ollama-qwen", "mock response"))
39	reg.RegisterFactory("zen-nano", provider.NewMockFactory("zen-nano", "mock response"))
40	reg.RegisterFactory("zen-pickle", provider.NewMockFactory("zen-pickle", "mock response"))
41
42	cfg := &config.Config{
43		Swarm: config.SwarmConfig{
44			MaxMyses:        16,
45			DefaultProvider: "ollama-qwen",
46		},
47		Providers: map[string]config.ProviderConfig{
48			"ollama-qwen": {Endpoint: "http://mock", Model: "qwen3:8b", Temperature: 0.7},
49			"zen-nano":    {Endpoint: "http://mock", Model: "gpt-5-nano", Temperature: 0.7},
50			"zen-pickle":  {Endpoint: "http://mock", Model: "big-pickle", Temperature: 0.7},
51		},
52	}
53
54	commander := core.NewCommander(s, reg, bus, cfg, "")
55
56	model := New(commander, s, eventCh, false, cfg)
57	model.width = 80
58	model.height = 24
59
60	// Set fixed test time for deterministic timestamps
61	fixedTime := testTime()
62	model.testTime = &fixedTime
63
64	cleanup := func() {
65		commander.StopAll()
66		bus.Close()
67		s.Close()
68	}
69
70	return model, cleanup
71}
72
73func TestModelInit(t *testing.T) {
74	m, cleanup := setupTestModel(t)
75	defer cleanup()
76
77	cmd := m.Init()
78	if cmd == nil {
79		t.Error("expected Init to return a command")
80	}
81}
82
83func TestModelView(t *testing.T) {
84	m, cleanup := setupTestModel(t)
85	defer cleanup()
86
87	// Initial view should render without panic
88	view := m.View()
89	if view == "" {
90		t.Error("expected non-empty view")
91	}
92}
93
94func TestModelViewWithZeroSize(t *testing.T) {
95	m, cleanup := setupTestModel(t)
96	defer cleanup()
97
98	m.width = 0
99	m.height = 0
100
101	view := m.View()
102	if view != "Loading..." {
103		t.Errorf("expected 'Loading...', got %s", view)
104	}
105}
106
107func TestModelWindowResize(t *testing.T) {
108	m, cleanup := setupTestModel(t)
109	defer cleanup()
110
111	newModel, _ := m.Update(tea.WindowSizeMsg{Width: 120, Height: 40})
112	m = newModel.(Model)
113
114	if m.width != 120 {
115		t.Errorf("expected width=120, got %d", m.width)
116	}
117	if m.height != 40 {
118		t.Errorf("expected height=40, got %d", m.height)
119	}
120}
121
122func TestModelQuit(t *testing.T) {
123	m, cleanup := setupTestModel(t)
124	defer cleanup()
125
126	_, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'q'}})
127
128	// Check if quit command was returned
129	if cmd == nil {
130		t.Error("expected quit command")
131	}
132}
133
134func TestModelHelpToggle(t *testing.T) {
135	m, cleanup := setupTestModel(t)
136	defer cleanup()
137
138	if m.showHelp {
139		t.Error("help should be hidden initially")
140	}
141
142	// Toggle help on
143	newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'?'}})
144	m = newModel.(Model)
145
146	if !m.showHelp {
147		t.Error("help should be shown after pressing ?")
148	}
149
150	// Toggle help off
151	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'?'}})
152	m = newModel.(Model)
153
154	if m.showHelp {
155		t.Error("help should be hidden after pressing ? again")
156	}
157}
158
159func TestModelNavigation(t *testing.T) {
160	m, cleanup := setupTestModel(t)
161	defer cleanup()
162
163	// Create some myses
164	m.commander.CreateMysis("mysis-1", "ollama-qwen")
165	m.commander.CreateMysis("mysis-2", "ollama-qwen")
166	m.refreshMysisList()
167
168	if m.selectedIdx != 0 {
169		t.Errorf("expected selectedIdx=0, got %d", m.selectedIdx)
170	}
171
172	// Navigate down
173	newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyDown})
174	m = newModel.(Model)
175
176	if m.selectedIdx != 1 {
177		t.Errorf("expected selectedIdx=1, got %d", m.selectedIdx)
178	}
179
180	// Navigate up
181	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyUp})
182	m = newModel.(Model)
183
184	if m.selectedIdx != 0 {
185		t.Errorf("expected selectedIdx=0, got %d", m.selectedIdx)
186	}
187}
188
189func TestModelFocusView(t *testing.T) {
190	m, cleanup := setupTestModel(t)
191	defer cleanup()
192
193	// Create a mysis
194	mysis, _ := m.commander.CreateMysis("test-mysis", "ollama-qwen")
195	m.refreshMysisList()
196
197	// Press enter to focus
198	newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
199	m = newModel.(Model)
200
201	if m.view != ViewFocus {
202		t.Errorf("expected view=ViewFocus, got %d", m.view)
203	}
204	if m.focusID != mysis.ID() {
205		t.Errorf("expected focusID=%s, got %s", mysis.ID(), m.focusID)
206	}
207
208	// Press escape to go back
209	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc})
210	m = newModel.(Model)
211
212	if m.view != ViewDashboard {
213		t.Errorf("expected view=ViewDashboard, got %d", m.view)
214	}
215}
216
217func TestInputModel(t *testing.T) {
218	input := NewInputModel()
219
220	if input.IsActive() {
221		t.Error("input should not be active initially")
222	}
223
224	input.SetMode(InputModeBroadcast, "")
225	if !input.IsActive() {
226		t.Error("input should be active after SetMode")
227	}
228	if input.Mode() != InputModeBroadcast {
229		t.Errorf("expected mode=InputModeBroadcast, got %d", input.Mode())
230	}
231
232	input.Reset()
233	if input.IsActive() {
234		t.Error("input should not be active after Reset")
235	}
236}
237
238func TestRenderHelp(t *testing.T) {
239	help := RenderHelp(80, 24)
240	if help == "" {
241		t.Error("expected non-empty help")
242	}
243}
244
245func TestRenderDashboard(t *testing.T) {
246	myses := []MysisInfo{
247		{ID: "1", Name: "mysis-1", State: "running", Provider: "ollama-qwen"},
248		{ID: "2", Name: "mysis-2", State: "idle", Provider: "ollama-qwen"},
249	}
250
251	loadingSet := make(map[string]bool)
252	swarmMsgs := []SwarmMessageInfo{}
253	dashboard := RenderDashboard(myses, swarmMsgs, 0, 80, 24, loadingSet, "⠋", 0, nil)
254	if dashboard == "" {
255		t.Error("expected non-empty dashboard")
256	}
257
258	// Test with loading state
259	loadingSet["1"] = true
260	dashboardWithLoading := RenderDashboard(myses, swarmMsgs, 0, 80, 24, loadingSet, "⠋", 0, nil)
261	if dashboardWithLoading == "" {
262		t.Error("expected non-empty dashboard with loading")
263	}
264}
265
266func TestRenderDashboardEmpty(t *testing.T) {
267	dashboard := RenderDashboard([]MysisInfo{}, []SwarmMessageInfo{}, 0, 80, 24, make(map[string]bool), "⠋", 0, nil)
268	if dashboard == "" {
269		t.Error("expected non-empty dashboard even with no myses")
270	}
271}
272
273func TestRenderFocusView(t *testing.T) {
274	mysis := MysisInfo{ID: "1", Name: "test-mysis", State: "running", Provider: "ollama-qwen"}
275	logs := []LogEntry{
276		{Role: "user", Content: "Hello"},
277		{Role: "assistant", Content: "Hi there! This is a longer response that might span multiple lines when properly wrapped in the terminal window."},
278	}
279
280	view := RenderFocusView(mysis, logs, 80, 24, false, "⠋", false, 1, 1, 0, nil)
281	if view == "" {
282		t.Error("expected non-empty focus view")
283	}
284
285	// Test with loading state
286	viewLoading := RenderFocusView(mysis, logs, 80, 24, true, "⠋", false, 1, 1, 0, nil)
287	if viewLoading == "" {
288		t.Error("expected non-empty focus view with loading")
289	}
290}
291
292func TestStateStyle(t *testing.T) {
293	// Just ensure these don't panic
294	_ = StateStyle("running")
295	_ = StateStyle("idle")
296	_ = StateStyle("stopped")
297	_ = StateStyle("errored")
298	_ = StateStyle("unknown")
299}
300
301func TestRoleColor(t *testing.T) {
302	// Verify RoleColor returns distinct colors for each role
303	roles := []string{"user", "assistant", "system", "tool", "unknown"}
304	colors := make(map[string]lipgloss.Color)
305
306	for _, role := range roles {
307		color := RoleColor(role)
308		colors[role] = color
309
310		// Color should be a non-empty string
311		if string(color) == "" {
312			t.Errorf("role %q should have a non-empty color", role)
313		}
314	}
315
316	// Main roles should have distinct colors
317	if colors["user"] == colors["assistant"] {
318		t.Error("user and assistant should have distinct colors")
319	}
320	if colors["system"] == colors["tool"] {
321		t.Error("system and tool should have distinct colors")
322	}
323	if colors["user"] == colors["system"] {
324		t.Error("user and system should have distinct colors")
325	}
326}
327
328func TestRenderLogEntry(t *testing.T) {
329	tests := []struct {
330		name     string
331		role     string
332		content  string
333		maxWidth int
334	}{
335		{"user message", "user", "Hello world", 80},
336		{"assistant message", "assistant", "Hi there, how can I help?", 80},
337		{"system message", "system", "System initialized", 80},
338		{"tool message", "tool", "Tool result: success", 80},
339		{"unknown role", "unknown", "Unknown message", 80},
340		{"long message wrap", "user", "This is a very long message that should be wrapped across multiple lines when the width is constrained", 40},
341		{"multiline content", "assistant", "Line one\nLine two\nLine three", 80},
342		{"narrow width", "user", "Short", 20},
343	}
344
345	for _, tt := range tests {
346		t.Run(tt.name, func(t *testing.T) {
347			entry := LogEntry{Role: tt.role, Content: tt.content}
348			lines := renderLogEntryImpl(entry, tt.maxWidth, false, 0)
349			if len(lines) == 0 {
350				t.Error("expected at least one line of output")
351			}
352		})
353	}
354}
355
356func TestInputModelModes(t *testing.T) {
357	input := NewInputModel()
358
359	tests := []struct {
360		mode     InputMode
361		targetID string
362		wantDesc string
363	}{
364		{InputModeBroadcast, "", "broadcast mode"},
365		{InputModeMessage, "mysis-1", "message mode with target"},
366		{InputModeNewMysis, "", "new mysis mode"},
367		{InputModeConfigProvider, "mysis-1", "config mode with target"},
368		{InputModeNone, "", "none mode"},
369	}
370
371	for _, tt := range tests {
372		t.Run(tt.wantDesc, func(t *testing.T) {
373			input.SetMode(tt.mode, tt.targetID)
374
375			if input.Mode() != tt.mode {
376				t.Errorf("expected mode %d, got %d", tt.mode, input.Mode())
377			}
378			if tt.targetID != "" && input.TargetID() != tt.targetID {
379				t.Errorf("expected targetID %s, got %s", tt.targetID, input.TargetID())
380			}
381
382			// Verify view renders without panic
383			_ = input.View()
384		})
385	}
386}
387
388func TestInputModelPrompts(t *testing.T) {
389	input := NewInputModel()
390
391	tests := []struct {
392		mode         InputMode
393		wantSymbol   string
394		wantMinWidth int
395		desc         string
396	}{
397		{InputModeBroadcast, "⬧", 3, "broadcast prompt"},
398		{InputModeMessage, "⬥", 3, "message prompt"},
399		{InputModeNewMysis, "⬡", 3, "new mysis prompt"},
400		{InputModeConfigProvider, "⚙", 3, "config provider prompt"},
401		{InputModeConfigModel, "cfg", 5, "config model prompt"},
402	}
403
404	for _, tt := range tests {
405		t.Run(tt.desc, func(t *testing.T) {
406			input.SetMode(tt.mode, "test-id")
407
408			prompt := input.textInput.Prompt
409			stripped := stripANSI(prompt)
410
411			// Verify the symbol is present
412			if !strings.Contains(stripped, tt.wantSymbol) {
413				t.Errorf("prompt %q does not contain symbol %q", stripped, tt.wantSymbol)
414			}
415
416			// Verify minimum width (symbol + at least 2 spaces for separation)
417			if len(stripped) < tt.wantMinWidth {
418				t.Errorf("prompt %q is too short (len=%d, want>=%d)", stripped, len(stripped), tt.wantMinWidth)
419			}
420
421			// Verify no character overlap by checking for proper spacing
422			// The prompt should be: symbol + spaces (at least 2)
423			if !strings.HasSuffix(stripped, "  ") {
424				t.Errorf("prompt %q should end with at least 2 spaces to prevent overlap", stripped)
425			}
426		})
427	}
428}
429
430func TestInputModelHistory(t *testing.T) {
431	input := NewInputModel()
432
433	// Add some history
434	input.AddToHistory("first message")
435	input.AddToHistory("second message")
436	input.AddToHistory("third message")
437
438	// Verify no duplicate consecutive entries
439	input.AddToHistory("third message")
440
441	// Set to message mode to enable history navigation
442	input.SetMode(InputModeMessage, "test")
443
444	// Verify history works (navigate up)
445	input.navigateHistory(1) // up
446	if input.Value() != "third message" {
447		t.Errorf("expected 'third message', got '%s'", input.Value())
448	}
449
450	input.navigateHistory(1) // up again
451	if input.Value() != "second message" {
452		t.Errorf("expected 'second message', got '%s'", input.Value())
453	}
454
455	input.navigateHistory(-1) // down
456	if input.Value() != "third message" {
457		t.Errorf("expected 'third message', got '%s'", input.Value())
458	}
459}
460
461func TestNetIndicatorActivities(t *testing.T) {
462	tests := []struct {
463		activity NetActivity
464		wantDesc string
465	}{
466		{NetActivityIdle, "idle activity"},
467		{NetActivityLLM, "LLM activity"},
468		{NetActivityMCP, "MCP activity"},
469	}
470
471	for _, tt := range tests {
472		t.Run(tt.wantDesc, func(t *testing.T) {
473			n := NewNetIndicator()
474			n.SetActivity(tt.activity)
475
476			if n.Activity() != tt.activity {
477				t.Errorf("expected activity %d, got %d", tt.activity, n.Activity())
478			}
479
480			// Verify views render without panic
481			view := n.View()
482			if view == "" {
483				t.Error("expected non-empty view")
484			}
485
486			compact := n.ViewCompact()
487			if compact == "" {
488				t.Error("expected non-empty compact view")
489			}
490		})
491	}
492}
493
494func TestNetIndicatorBounce(t *testing.T) {
495	n := NewNetIndicator()
496	n.SetActivity(NetActivityLLM)
497
498	// Simulate several ticks
499	for i := 0; i < 20; i++ {
500		n, _ = n.Update(NetIndicatorTickMsg{})
501	}
502
503	// Ensure position stayed within bounds
504	if n.position < 0 || n.position >= n.width {
505		t.Errorf("position %d out of bounds [0, %d)", n.position, n.width)
506	}
507}
508
509func TestRenderDashboardWithSwarmMessages(t *testing.T) {
510	myses := []MysisInfo{
511		{ID: "1", Name: "mysis-1", State: "running", Provider: "ollama-qwen"},
512	}
513
514	swarmMsgs := []SwarmMessageInfo{
515		{SenderID: "mysis-1", SenderName: "alpha", Content: "Hello swarm", CreatedAt: time.Now()},
516		{SenderID: "mysis-2", SenderName: "beta", Content: "Do the thing", CreatedAt: time.Now()},
517	}
518
519	dashboard := RenderDashboard(myses, swarmMsgs, 0, 100, 30, make(map[string]bool), "⠋", 0, nil)
520	if dashboard == "" {
521		t.Error("expected non-empty dashboard with swarm messages")
522	}
523
524	// Should contain swarm broadcast section
525	if !strings.Contains(dashboard, "SWARM BROADCAST") {
526		t.Error("expected dashboard to contain 'SWARM BROADCAST'")
527	}
528}
529
530func TestRenderFocusViewWithAllRoles(t *testing.T) {
531	mysis := MysisInfo{ID: "1", Name: "test-mysis", State: "running", Provider: "ollama-qwen"}
532	logs := []LogEntry{
533		{Role: "system", Content: "System prompt"},
534		{Role: "user", Content: "User question"},
535		{Role: "assistant", Content: "AI response"},
536		{Role: "tool", Content: "Tool result"},
537	}
538
539	view := RenderFocusView(mysis, logs, 100, 30, false, "⠋", false, 1, 1, 0, nil)
540	if view == "" {
541		t.Error("expected non-empty focus view")
542	}
543
544	// Verify all role prefixes appear
545	prefixes := []string{"SYS:", "YOU:", "AI:", "TOOL:"}
546	for _, prefix := range prefixes {
547		if !strings.Contains(view, prefix) {
548			t.Errorf("expected view to contain '%s'", prefix)
549		}
550	}
551}
552
553func TestWrapText(t *testing.T) {
554	tests := []struct {
555		name     string
556		text     string
557		maxWidth int
558		wantMin  int // minimum number of lines expected
559	}{
560		{"short text", "Hello", 80, 1},
561		{"exact width", "Hello World", 11, 1},
562		{"needs wrap", "Hello World", 6, 2},
563		{"multiple paragraphs", "Line one\n\nLine three", 80, 3},
564		{"zero width defaults", "Test", 0, 1},
565		{"long word hard wrap", strings.Repeat("a", 100), 50, 2}, // Should hard-wrap long words
566	}
567
568	for _, tt := range tests {
569		t.Run(tt.name, func(t *testing.T) {
570			lines := wrapText(tt.text, tt.maxWidth)
571			if len(lines) < tt.wantMin {
572				t.Errorf("expected at least %d lines, got %d", tt.wantMin, len(lines))
573			}
574		})
575	}
576}
577
578func TestRenderHelpContent(t *testing.T) {
579	help := RenderHelp(100, 40)
580
581	// Verify key shortcuts are present
582	expectedKeys := []string{"q", "n", "d", "r", "s", "b", "m", "c", "Tab", "Enter", "Esc", "?"}
583	for _, key := range expectedKeys {
584		if !strings.Contains(help, key) {
585			t.Errorf("expected help to contain '%s'", key)
586		}
587	}
588}
589
590func TestRenderMysisLineStates(t *testing.T) {
591	spinnerView := "⠋"
592
593	tests := []struct {
594		state     string
595		isLoading bool
596	}{
597		{"running", false},
598		{"running", true},
599		{"idle", false},
600		{"stopped", false},
601		{"errored", false},
602	}
603
604	for _, tt := range tests {
605		t.Run(tt.state, func(t *testing.T) {
606			mysis := MysisInfo{
607				ID:          "test-id",
608				Name:        "test-mysis",
609				State:       tt.state,
610				Provider:    "ollama-qwen",
611				LastMessage: "Last message here",
612			}
613
614			// Test both selected and unselected
615			lines := renderMysisLine(mysis, false, tt.isLoading, spinnerView, 80, 0)
616			if len(lines) != 2 || lines[0] == "" || lines[1] == "" {
617				t.Error("expected two non-empty mysis lines")
618			}
619
620			selectedLines := renderMysisLine(mysis, true, tt.isLoading, spinnerView, 80, 0)
621			if len(selectedLines) != 2 || selectedLines[0] == "" || selectedLines[1] == "" {
622				t.Error("expected two non-empty selected mysis lines")
623			}
624		})
625	}
626}
627
628func TestMysisLineWidthFill(t *testing.T) {
629	// Test that mysis lines are styled with width to fill the panel
630	mysis := MysisInfo{
631		ID:       "test-id",
632		Name:     "test-mysis",
633		State:    "idle",
634		Provider: "ollama-qwen",
635	}
636
637	width := 80
638	lines := renderMysisLine(mysis, false, false, "⠋", width, 0)
639
640	// The lines should be rendered (non-empty, two lines)
641	if len(lines) != 2 || lines[0] == "" || lines[1] == "" {
642		t.Error("expected two non-empty mysis lines")
643	}
644
645	// Selected lines should also be rendered
646	selectedLines := renderMysisLine(mysis, true, false, "⠋", width, 0)
647	if len(selectedLines) != 2 || selectedLines[0] == "" || selectedLines[1] == "" {
648		t.Error("expected two non-empty selected mysis lines")
649	}
650}
651
652func TestSectionTitleWithSuffixWidth(t *testing.T) {
653	// Test section title with suffix
654	tests := []struct {
655		title  string
656		suffix string
657		width  int
658	}{
659		{"CONVERSATION LOG", "  ↑ SCROLLED", 100},
660		{"CONVERSATION LOG", "", 80},
661		{"TEST", "  suffix", 60},
662	}
663
664	for _, tt := range tests {
665		t.Run(tt.title, func(t *testing.T) {
666			rendered := renderSectionTitleWithSuffix(tt.title, tt.suffix, tt.width)
667
668			if !strings.Contains(rendered, tt.title) {
669				t.Errorf("should contain title %q", tt.title)
670			}
671			if tt.suffix != "" && !strings.Contains(rendered, tt.suffix) {
672				t.Errorf("should contain suffix")
673			}
674
675			// Check actual display width matches requested width
676			actualWidth := lipgloss.Width(rendered)
677			if actualWidth != tt.width {
678				t.Errorf("section title with suffix display width = %d, want %d", actualWidth, tt.width)
679			}
680		})
681	}
682}
683
684// TestUnicodeCharacterSpacing verifies that Unicode characters have proper spacing
685// to prevent visual overlap in the TUI.
686func TestUnicodeCharacterSpacing(t *testing.T) {
687	tests := []struct {
688		name     string
689		render   func() string
690		wantChar string
691		minSpace int // minimum spaces after the Unicode character
692	}{
693		{
694			name: "stats_bar_running",
695			render: func() string {
696				return "∙  1"
697			},
698			wantChar: "∙",
699			minSpace: 2,
700		},
701		{
702			name: "stats_bar_idle",
703			render: func() string {
704				return "◦  1"
705			},
706			wantChar: "◦",
707			minSpace: 2,
708		},
709		{
710			name: "stats_bar_stopped",
711			render: func() string {
712				return "◌  0"
713			},
714			wantChar: "◌",
715			minSpace: 2,
716		},
717		{
718			name: "stats_bar_errored",
719			render: func() string {
720				return "✖  0"
721			},
722			wantChar: "✖",
723			minSpace: 2,
724		},
725		{
726			name: "mysis_line_indicator",
727			render: func() string {
728				return "⬡  test-mysis"
729			},
730			wantChar: "⬡",
731			minSpace: 2,
732		},
733	}
734
735	for _, tt := range tests {
736		t.Run(tt.name, func(t *testing.T) {
737			output := tt.render()
738
739			// Find the Unicode character
740			idx := strings.Index(output, tt.wantChar)
741			if idx == -1 {
742				t.Fatalf("Unicode character %q not found in output %q", tt.wantChar, output)
743			}
744
745			// Check spacing after the character
746			afterChar := output[idx+len(tt.wantChar):]
747			spaceCount := 0
748			for i := 0; i < len(afterChar) && afterChar[i] == ' '; i++ {
749				spaceCount++
750			}
751
752			if spaceCount < tt.minSpace {
753				t.Errorf("insufficient spacing after %q: got %d spaces, want at least %d\nOutput: %q",
754					tt.wantChar, spaceCount, tt.minSpace, output)
755			}
756		})
757	}
758}
759
760// TestUnicodeAmbiguousWidthSafety verifies that all Unicode characters used in the TUI
761// are NOT East Asian Ambiguous Width characters, which can render as 2 cells wide
762// in some terminal locales, causing visual overlap.
763func TestUnicodeAmbiguousWidthSafety(t *testing.T) {
764	// All Unicode characters used in the TUI
765	chars := map[string]string{
766		"filled_circle":  "∙", // U+2219 - bullet operator (SAFE)
767		"empty_circle":   "◦", // U+25E6 - white bullet (SAFE)
768		"filled_diamond": "⬥", // U+2B25 - black medium diamond (SAFE)
769		"lozenge":        "⬧", // U+2B27 - black medium lozenge (SAFE)
770		"hexagon":        "⬡", // U+2B21 - white hexagon (SAFE)
771		"hexagon_filled": "⬢", // U+2B22 - black hexagon (SAFE)
772		"diamond_empty":  "⬦", // U+2B26 - white medium diamond (SAFE)
773		"stopped":        "◌", // U+25CC - dotted circle (SAFE)
774		"errored":        "✖", // U+2716 - heavy multiplication X (SAFE)
775		"gear":           "⚙", // U+2699 - gear (SAFE)
776		"braille":        "⠋", // U+280B - braille pattern (SAFE)
777	}
778
779	for name, char := range chars {
780		t.Run(name, func(t *testing.T) {
781			r := []rune(char)[0]
782
783			// Test with EastAsianWidth disabled (narrow)
784			runewidth.DefaultCondition.EastAsianWidth = false
785			narrowWidth := runewidth.RuneWidth(r)
786
787			// Test with EastAsianWidth enabled (wide)
788			runewidth.DefaultCondition.EastAsianWidth = true
789			wideWidth := runewidth.RuneWidth(r)
790
791			// Reset to default
792			runewidth.DefaultCondition.EastAsianWidth = false
793
794			// Character should have same width in both modes
795			if narrowWidth != wideWidth {
796				t.Errorf("Character %s (U+%04X) is AMBIGUOUS WIDTH: narrow=%d wide=%d\n"+
797					"This will cause visual overlap in East Asian locales!\n"+
798					"Replace with a non-ambiguous character.",
799					char, r, narrowWidth, wideWidth)
800			}
801
802			// Additionally, verify it's exactly 1 cell wide (except for known 2-cell chars)
803			if narrowWidth != 1 && name != "hexagon_filled" {
804				t.Errorf("Character %s (U+%04X) has unexpected width: %d (expected 1)",
805					char, r, narrowWidth)
806			}
807		})
808	}
809}
810
811// TestModelRefreshTick verifies that the Model refreshes its currentTick field
812// from the Commander's aggregate tick.
813func TestModelRefreshTick(t *testing.T) {
814	m, cleanup := setupTestModel(t)
815	defer cleanup()
816
817	// Initial tick should be 0 (no myses)
818	if m.currentTick != 0 {
819		t.Errorf("initial currentTick should be 0, got %d", m.currentTick)
820	}
821
822	// Call refreshTick (method to be implemented)
823	m.refreshTick()
824
825	// Should update currentTick to match commander.AggregateTick()
826	expectedTick := m.commander.AggregateTick()
827	if m.currentTick != expectedTick {
828		t.Errorf("expected currentTick=%d after refresh, got %d", expectedTick, m.currentTick)
829	}
830}
831
832func TestMysisCreation_TwoStageFlow(t *testing.T) {
833	m, cleanup := setupTestModel(t)
834	defer cleanup()
835
836	// Step 1: Press 'n' to start creation
837	newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
838	m = newModel.(Model)
839
840	if m.input.Mode() != InputModeNewMysis {
841		t.Fatalf("expected InputModeNewMysis, got %v", m.input.Mode())
842	}
843	if m.inputStage != InputStageName {
844		t.Fatalf("expected InputStageName, got %v", m.inputStage)
845	}
846
847	// Step 2: Type name "test-mysis"
848	for _, r := range "test-mysis" {
849		newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
850		m = newModel.(Model)
851	}
852
853	// Step 3: Press Enter (should advance to provider stage)
854	t.Logf("Before name Enter: inputValue='%s'", m.input.Value())
855	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
856	m = newModel.(Model)
857
858	t.Logf("After name Enter: inputMode=%v, inputStage=%v, pendingName=%s",
859		m.input.Mode(), m.inputStage, m.pendingMysisName)
860
861	if m.inputStage != InputStageProvider {
862		t.Errorf("expected InputStageProvider after entering name, got %v", m.inputStage)
863	}
864	if m.pendingMysisName != "test-mysis" {
865		t.Errorf("expected pendingMysisName='test-mysis', got '%s'", m.pendingMysisName)
866	}
867
868	// Step 4: Press Enter (empty = use default provider)
869	t.Logf("Before final Enter: inputStage=%v, pendingName=%s, config.DefaultProvider=%s, inputValue='%s'",
870		m.inputStage, m.pendingMysisName, m.config.Swarm.DefaultProvider, m.input.Value())
871
872	_, hasProvider := m.config.Providers[m.config.Swarm.DefaultProvider]
873	t.Logf("Provider exists in config: %v", hasProvider)
874
875	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
876	m = newModel.(Model)
877
878	t.Logf("After final Enter: inputMode=%v, inputStage=%v, err=%v", m.input.Mode(), m.inputStage, m.err)
879
880	// Should create mysis and reset
881	if m.input.Mode() != InputModeNone {
882		t.Errorf("expected InputModeNone after creation, got %v", m.input.Mode())
883	}
884
885	// Check mysis was created
886	myses := m.commander.ListMyses()
887	if len(myses) != 1 {
888		t.Fatalf("expected 1 mysis, got %d", len(myses))
889	}
890	if myses[0].Name() != "test-mysis" {
891		t.Errorf("expected name='test-mysis', got '%s'", myses[0].Name())
892	}
893}
894
895func TestMysisCreation_ZenNanoProvider(t *testing.T) {
896	m, cleanup := setupTestModel(t)
897	defer cleanup()
898
899	// Press 'n'
900	newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
901	m = newModel.(Model)
902
903	// Enter name
904	for _, r := range "zen-test" {
905		newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
906		m = newModel.(Model)
907	}
908	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
909	m = newModel.(Model)
910
911	// Enter provider "zen-nano"
912	for _, r := range "zen-nano" {
913		newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
914		m = newModel.(Model)
915	}
916	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
917	m = newModel.(Model)
918
919	// Should succeed
920	if m.err != nil {
921		t.Fatalf("unexpected error: %v (available providers: %v)", m.err, getProviderNames(m.config))
922	}
923
924	myses := m.commander.ListMyses()
925	if len(myses) != 1 {
926		t.Fatalf("expected 1 mysis, got %d", len(myses))
927	}
928}
929
930func TestMysisCreation_ZenPickleProvider(t *testing.T) {
931	m, cleanup := setupTestModel(t)
932	defer cleanup()
933
934	// Press 'n'
935	newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
936	m = newModel.(Model)
937
938	// Enter name
939	for _, r := range "pickle-test" {
940		newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
941		m = newModel.(Model)
942	}
943	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
944	m = newModel.(Model)
945
946	// Enter provider "zen-pickle"
947	for _, r := range "zen-pickle" {
948		newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
949		m = newModel.(Model)
950	}
951	newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyEnter})
952	m = newModel.(Model)
953
954	// Should succeed
955	if m.err != nil {
956		t.Fatalf("unexpected error: %v", m.err)
957	}
958
959	myses := m.commander.ListMyses()
960	if len(myses) != 1 {
961		t.Fatalf("expected 1 mysis, got %d", len(myses))
962	}
963}
964
965func getProviderNames(cfg *config.Config) []string {
966	var names []string
967	for name := range cfg.Providers {
968		names = append(names, name)
969	}
970	return names
971}
972
973// TestNetworkIndicator_AutonomousActivity verifies that the network indicator
974// correctly tracks autonomous Mysis activity (not just user-initiated messages).
975func TestNetworkIndicator_AutonomousActivity(t *testing.T) {
976	m, cleanup := setupTestModel(t)
977	defer cleanup()
978
979	// Initial state: indicator should be idle, counter at 0
980	if m.netIndicator.Activity() != NetActivityIdle {
981		t.Errorf("initial activity = %v, want NetActivityIdle", m.netIndicator.Activity())
982	}
983	if m.activeNetworkOps != 0 {
984		t.Errorf("initial activeNetworkOps = %d, want 0", m.activeNetworkOps)
985	}
986
987	// Simulate autonomous LLM activity (not user-initiated)
988	event := core.Event{
989		Type:      core.EventNetworkLLM,
990		MysisID:   "test-mysis-1",
991		MysisName: "TestMysis1",
992		Timestamp: time.Now(),
993	}
994	m.handleEvent(event)
995
996	// Indicator should show LLM activity, counter incremented
997	if m.netIndicator.Activity() != NetActivityLLM {
998		t.Errorf("after EventNetworkLLM: activity = %v, want NetActivityLLM", m.netIndicator.Activity())
999	}
1000	if m.activeNetworkOps != 1 {
1001		t.Errorf("after EventNetworkLLM: activeNetworkOps = %d, want 1", m.activeNetworkOps)
1002	}
1003
1004	// Simulate MCP activity from another Mysis
1005	event2 := core.Event{
1006		Type:      core.EventNetworkMCP,
1007		MysisID:   "test-mysis-2",
1008		MysisName: "TestMysis2",
1009		Timestamp: time.Now(),
1010	}
1011	m.handleEvent(event2)
1012
1013	// Indicator should show MCP activity, counter incremented again
1014	if m.netIndicator.Activity() != NetActivityMCP {
1015		t.Errorf("after EventNetworkMCP: activity = %v, want NetActivityMCP", m.netIndicator.Activity())
1016	}
1017	if m.activeNetworkOps != 2 {
1018		t.Errorf("after EventNetworkMCP: activeNetworkOps = %d, want 2", m.activeNetworkOps)
1019	}
1020
1021	// First Mysis completes
1022	idleEvent1 := core.Event{
1023		Type:      core.EventNetworkIdle,
1024		MysisID:   "test-mysis-1",
1025		Timestamp: time.Now(),
1026	}
1027	m.handleEvent(idleEvent1)
1028
1029	// Indicator should STILL be active (second Mysis still working)
1030	if m.netIndicator.Activity() == NetActivityIdle {
1031		t.Error("after first EventNetworkIdle: indicator should NOT be idle (second Mysis still active)")
1032	}
1033	if m.activeNetworkOps != 1 {
1034		t.Errorf("after first EventNetworkIdle: activeNetworkOps = %d, want 1", m.activeNetworkOps)
1035	}
1036
1037	// Second Mysis completes
1038	idleEvent2 := core.Event{
1039		Type:      core.EventNetworkIdle,
1040		MysisID:   "test-mysis-2",
1041		Timestamp: time.Now(),
1042	}
1043	m.handleEvent(idleEvent2)
1044
1045	// NOW indicator should go idle (all operations complete)
1046	if m.netIndicator.Activity() != NetActivityIdle {
1047		t.Errorf("after all EventNetworkIdle: activity = %v, want NetActivityIdle", m.netIndicator.Activity())
1048	}
1049	if m.activeNetworkOps != 0 {
1050		t.Errorf("after all EventNetworkIdle: activeNetworkOps = %d, want 0", m.activeNetworkOps)
1051	}
1052}
1053
1054// TestNetworkIndicator_NegativeCounterProtection verifies that the counter
1055// doesn't go negative if we receive more idle events than activity events.
1056func TestNetworkIndicator_NegativeCounterProtection(t *testing.T) {
1057	m, cleanup := setupTestModel(t)
1058	defer cleanup()
1059
1060	// Send idle event without corresponding activity event
1061	idleEvent := core.Event{
1062		Type:      core.EventNetworkIdle,
1063		MysisID:   "test-mysis",
1064		Timestamp: time.Now(),
1065	}
1066	m.handleEvent(idleEvent)
1067
1068	// Counter should be clamped at 0, not negative
1069	if m.activeNetworkOps < 0 {
1070		t.Errorf("activeNetworkOps = %d, should not be negative", m.activeNetworkOps)
1071	}
1072	if m.activeNetworkOps != 0 {
1073		t.Errorf("activeNetworkOps = %d, want 0", m.activeNetworkOps)
1074	}
1075}