@@ -1,853 +0,0 @@
1-# TUI Testing Guide
2-
3-## Overview
4-
5-Symb's TUI test suite uses three complementary testing approaches:
6-1. **Unit tests** - Model state and business logic
7-2. **Golden file tests** - Visual regression testing
8-3. **Integration tests** - End-to-end user flows with teatest
9-
10-This document describes testing practices, patterns, and lessons learned.
11-
12-## Test Categories
13-
14-### 1. Unit Tests (`tui_test.go`, `focus_test.go`, etc.)
15-
16-Test model state transitions and business logic without rendering concerns.
17-
18-**What to test:**
19-- Model initialization and state
20-- Navigation logic (up/down, view switching)
21-- Input mode transitions
22-- Help toggle, history navigation
23-- Error handling
24-- Business logic (truncation, formatting)
25-
26-**Pattern:**
27-```go
28-func TestModelNavigation(t *testing.T) {
29- m, cleanup := setupTestModel(t)
30- defer cleanup()
31-
32- m, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
33- if m.selectedIdx != 1 {
34- t.Errorf("expected selectedIdx=1, got %d", m.selectedIdx)
35- }
36-}
37-```
38-
39-**DO NOT test:**
40-- Width arithmetic (use golden files instead)
41-- ANSI codes directly (use golden files instead)
42-- Implementation details (padding, spacing calculations)
43-
44-### 2. Golden File Tests (`golden_test.go`)
45-
46-Visual regression tests using snapshot comparison. Each test has ANSI and Stripped variants.
47-
48-**What to test:**
49-- Dashboard rendering
50-- Focus view layouts
51-- Log entry formatting
52-- JSON tree rendering
53-- Scrollbar positioning
54-- Any visual output
55-
56-**Pattern:**
57-```go
58-func TestDashboard(t *testing.T) {
59- defer setupGoldenTest(t)() // Force TrueColor output
60-
61- output := renderDashboard(...)
62-
63- t.Run("ANSI", func(t *testing.T) {
64- golden.RequireEqual(t, []byte(output))
65- })
66-
67- t.Run("Stripped", func(t *testing.T) {
68- stripped := stripANSIForGolden(output)
69- golden.RequireEqual(t, []byte(stripped))
70- })
71-}
72-```
73-
74-**Update golden files:**
75-```bash
76-go test ./internal/tui -update
77-```
78-
79-**Golden files location:** `internal/tui/testdata/`
80-
81-**Golden file naming convention:**
82-- Directory: `testdata/Test<FunctionName>/<test_case_name>/`
83-- Files: `ANSI.golden` (with ANSI codes) and `Stripped.golden` (content only)
84-- Example: `testdata/TestDashboard/empty_swarm/ANSI.golden`
85-
86-**Why two variants:**
87-- **ANSI** - Catches color and style regressions (RGB codes, bold, etc.)
88-- **Stripped** - Catches content and layout regressions (easier to read diffs)
89-
90-### 3. Integration Tests (`integration_test.go`)
91-
92-End-to-end tests using teatest to simulate full user interactions.
93-
94-**What to test:**
95-- Complete user flows (create mysis, send broadcast, etc.)
96-- Async event handling
97-- Window resize behavior
98-- Viewport scrolling
99-- Multi-step interactions
100-
101-**Pattern:**
102-```go
103-func TestIntegration_Example(t *testing.T) {
104- m, cleanup := setupTestModel(t)
105- defer cleanup()
106-
107- tm := teatest.NewTestModel(t, m,
108- teatest.WithInitialTermSize(120, 40))
109- defer tm.Quit()
110-
111- // Wait for initial render
112- teatest.WaitFor(t, tm.Output(), func(bts []byte) bool {
113- return bytes.Contains(bts, []byte("expected"))
114- }, teatest.WithDuration(2*time.Second))
115-
116- // Send input
117- tm.Send(tea.KeyMsg{Type: tea.KeyDown})
118-
119- // Wait briefly
120- time.Sleep(100 * time.Millisecond)
121-
122- // Send quit to allow FinalModel to complete
123- tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("q")})
124-
125- // Verify final state
126- fm := tm.FinalModel(t, teatest.WithFinalTimeout(time.Second))
127- finalModel := fm.(Model)
128- // ... assertions
129-}
130-```
131-
132-**Known Issue:** Integration tests must send quit command before calling `FinalModel()` to avoid timeouts.
133-
134-## Testing Guidelines
135-
136-### DO
137-- Test model state and logic with unit tests
138-- Test visual output with golden files
139-- Test user flows with integration tests
140-- Use `lipgloss.Width()` for display width calculations
141-- Use `setupGoldenTest(t)` for consistent ANSI output
142-- Update golden files when intentionally changing UI
143-
144-### DO NOT
145-- Test width arithmetic (false positives, environment-dependent)
146-- Test ANSI codes directly (use golden files)
147-- Use `len()` on styled strings (use `lipgloss.Width()`)
148-- Test implementation details (padding calculations, internal spacing)
149-- Skip golden file updates after UI changes
150-
151-## Lipgloss Testing Notes
152-
153-### Width Calculations
154-Multi-byte Unicode characters cause width bugs:
155-
156-- **`len()` returns BYTES, not display width**: Characters like `◈`, `◆`, `╭`, `─` are 3 bytes each but display as 1 column
157-- **ALWAYS use `lipgloss.Width()`**: Correctly calculates display width for Unicode and ANSI-styled strings
158-- **Test with Unicode-heavy content**: Section titles and borders use Unicode box-drawing characters
159-
160-### Style Padding and Alignment
161-- `lipgloss.Style.Padding(0, 1)` adds 1 space on each side
162-- If one element has padding and another doesn't, decorations won't align
163-- `lipgloss.Width()` sets CONTENT width - borders and padding are added on top
164-- Example: `style.Width(98)` with border produces total width 100
165-
166-### Background Color Rendering
167-**Critical lesson from Unicode character overlap fix:**
168-
169-When rendering elements with selection backgrounds, content inside the styled area gets the background applied. To prevent background from extending to decorative elements:
170-
171-**WRONG:**
172-```go
173-// Indicator is part of styled content - gets background
174-line := fmt.Sprintf("%s %s", indicator, content)
175-return mysisItemSelectedStyle.Render(line)
176-```
177-
178-**RIGHT:**
179-```go
180-// Indicator is outside styled content - no background
181-line := content
182-return " " + indicator + " " + mysisItemSelectedStyle.Render(line)
183-```
184-
185-**Pattern:** Render decorative elements (icons, indicators, spacing) OUTSIDE the styled area to prevent background color from applying to them.
186-
187-## Unicode Character Safety
188-
189-### East Asian Ambiguous Width
190-Characters like `●`, `○`, `◆`, `◈`, `◇` are "East Asian Ambiguous Width":
191-- Render as 1 cell in Western locales
192-- Render as 2 cells in East Asian locales (Chinese, Japanese, Korean)
193-
194-This causes visual overlap when width calculations assume 1 cell but terminals render 2 cells.
195-
196-### Safe Replacements
197-| Ambiguous | Safe | Unicode | Name |
198-|-----------|------|---------|------|
199-| `●` | `∙` | U+2219 | Bullet Operator |
200-| `○` | `◦` | U+25E6 | White Bullet |
201-| `◆` | `⬥` | U+2B25 | Black Medium Diamond |
202-| `◈` | `⬧` | U+2B27 | Black Medium Lozenge |
203-| `◇` | `⬦` | U+2B26 | White Medium Diamond |
204-
205-### Testing for Ambiguous Width
206-Use `TestUnicodeAmbiguousWidthSafety` to verify all Unicode characters are non-ambiguous:
207-
208-```go
209-func TestUnicodeAmbiguousWidthSafety(t *testing.T) {
210- chars := map[string]string{
211- "filled_circle": "∙",
212- "empty_circle": "◦",
213- // ...
214- }
215-
216- for name, char := range chars {
217- t.Run(name, func(t *testing.T) {
218- r := []rune(char)[0]
219-
220- runewidth.DefaultCondition.EastAsianWidth = false
221- narrowWidth := runewidth.RuneWidth(r)
222-
223- runewidth.DefaultCondition.EastAsianWidth = true
224- wideWidth := runewidth.RuneWidth(r)
225-
226- if narrowWidth != wideWidth {
227- t.Errorf("Character %q is ambiguous width", char)
228- }
229- })
230- }
231-}
232-```
233-
234-## Edge Case Testing
235-
236-### Dashboard Edge Cases (`golden_edge_cases_test.go`)
237-
238-The `TestDashboardEdgeCases` test covers:
239-- **Empty states** - No myses, no messages
240-- **Full states** - 16 myses (max swarm), 10 broadcasts (max display)
241-- **Error states** - All myses errored, stopped, idle
242-- **Mixed states** - Combination of running, idle, stopped, errored
243-- **Long content** - Very long broadcast messages (truncation)
244-- **Unicode content** - Emoji, CJK characters, box-drawing
245-- **Extreme dimensions** - 60 cols (narrow), 240 cols (wide), 100 lines (tall)
246-- **Loading states** - All myses loading simultaneously
247-- **Selection positions** - Top, middle, bottom of list
248-
249-### Focus View Edge Cases
250-
251-The `TestFocusViewEdgeCases` test covers:
252-- **Empty states** - No logs, fresh mysis
253-- **Long content** - Very long log entries, reasoning (wrapping)
254-- **Unicode content** - Emoji in logs, CJK text
255-- **Large JSON** - Huge tool results (truncation)
256-- **Many logs** - 100+ log entries (scrolling)
257-- **Narrow views** - 60 col focus view (wrapping)
258-- **All role types** - System, user (direct), user (broadcast), assistant, tool
259-
260-### Net Indicator Edge Cases
261-
262-The `TestNetIndicatorEdgeCases` test covers:
263-- **Activity states** - Idle, LLM, MCP
264-- **Animation positions** - Start, middle, end of bar
265-- **View modes** - Full bar, compact
266-- **All combinations** - 8 test cases covering state × position × mode
267-
268-### Edge Case Coverage Summary
269-
270-| Component | Test Cases | Edge Cases Covered |
271-|-----------|------------|-------------------|
272-| Dashboard | 15 | Empty, full, errors, Unicode, dimensions, selection |
273-| Focus View | 9 | Empty, long content, Unicode, JSON, many logs, narrow |
274-| Net Indicator | 8 | Idle, LLM, MCP, positions, compact |
275-| **Total** | **32** | **All major edge cases** |
276-
277-## Unicode Character Testing
278-
279-### Character Inventory Test
280-
281-The `TestUnicodeCharacterInventory` test documents all Unicode characters used in the TUI with their codepoints, names, and usage locations. This test serves as a comprehensive reference and ensures all characters are properly documented.
282-
283-**Verified characters:**
284-- **⬥** (U+2B25 BLACK MEDIUM DIAMOND) - Header corners, status bar, message prompt, spinner
285-- **⬧** (U+2B27 BLACK MEDIUM LOZENGE) - Section borders, broadcast prompt
286-- **⬡** (U+2B21 WHITE HEXAGON) - Title decoration, new mysis prompt, spinner frame 0/2
287-- **⬢** (U+2B22 BLACK HEXAGON) - Spinner frame 1/3
288-- **⬦** (U+2B26 WHITE MEDIUM DIAMOND) - Spinner frame 4/6, idle indicator
289-- **◦** (U+25E6 WHITE BULLET) - Idle state indicator
290-- **◌** (U+25CC DOTTED CIRCLE) - Stopped state indicator
291-- **✖** (U+2716 HEAVY MULTIPLICATION X) - Errored state indicator
292-- **⚙** (U+2699 GEAR) - Config provider prompt
293-
294-### Spinner Animation Tests
295-
296-The `TestSpinnerFrameRendering` test verifies all 8 spinner frames:
297-
298-1. Frame 0: ⬡ (U+2B21)
299-2. Frame 1: ⬢ (U+2B22)
300-3. Frame 2: ⬡ (U+2B21)
301-4. Frame 3: ⬢ (U+2B22)
302-5. Frame 4: ⬦ (U+2B26)
303-6. Frame 5: ⬥ (U+2B25)
304-7. Frame 6: ⬦ (U+2B26)
305-8. Frame 7: ⬥ (U+2B25)
306-
307-**Animation speed:** 125ms per frame (8 FPS)
308-**Pattern:** Hexagonal theme alternating between filled/hollow shapes
309-
310-### Width Consistency Tests
311-
312-The `TestUnicodeWidthConsistency` test verifies that all characters:
313-- Have width of 1 via `lipgloss.Width()`
314-- Have width of 1 via `runewidth.RuneWidth()`
315-- Are NOT ambiguous width (render consistently in East Asian locales)
316-
317-This prevents the Unicode overlap bug previously fixed in commit fb1d0b6.
318-
319-### Terminal Compatibility Testing
320-
321-**Manual testing checklist:**
322-
323-1. **Test in primary terminal** (Alacritty, Kitty, WezTerm recommended):
324- ```bash
325- ./bin/symb
326- ```
327-
328-2. **Verify spinner animation:**
329- - Create a mysis (press `n`)
330- - Observe running state indicator animates smoothly
331- - All 8 frames should be visible and distinct
332- - No frame causes layout shift
333-
334-3. **Verify state indicators:**
335- - Idle: ◦ (white bullet)
336- - Stopped: ◌ (dotted circle)
337- - Errored: ✖ (heavy X)
338- - All indicators should align vertically
339-
340-4. **Verify section decorations:**
341- - Header corners: ⬥
342- - Section borders: ⬧
343- - Title decorations: ⬡
344- - All decorations should render clearly
345-
346-5. **Verify input prompts:**
347- - Press `b` for broadcast: ⬧
348- - Press `m` for message: ⬥
349- - Press `n` for new mysis: ⬡
350- - Press `c` for config: ⚙
351-
352-**Terminal compatibility notes:**
353-
354-| Terminal | Status | Notes |
355-|----------|--------|-------|
356-| Alacritty | ✅ Excellent | Best rendering, all characters clear |
357-| Kitty | ✅ Excellent | Full Unicode support |
358-| WezTerm | ✅ Excellent | Native font fallback |
359-| iTerm2 | ✅ Good | May vary with font |
360-| Terminal.app | ⚠️ Fair | Font-dependent |
361-| Windows Terminal | ✅ Good | Requires Nerd Font or Unicode font |
362-| gnome-terminal | ✅ Good | Most fonts work well |
363-| xterm | ⚠️ Limited | May not render all characters |
364-
365-**Font recommendations:**
366-- **Nerd Fonts:** FiraCode Nerd Font, JetBrains Mono Nerd Font
367-- **Unicode fonts:** Cascadia Code, Ubuntu Mono, Inconsolata
368-- **Fallback:** DejaVu Sans Mono (decent Unicode coverage)
369-
370-### Character Replacement Strategy
371-
372-If a character renders poorly in a specific terminal:
373-
374-1. **Check font first:** Install a Nerd Font or Unicode-compatible font
375-2. **Test with `go test`:** Run `TestCharacterRenderingMatrix` to see all characters
376-3. **Report compatibility:** Document in KNOWN_ISSUES.md with terminal/font details
377-4. **Consider fallback:** Add configuration option for ASCII-only mode (future enhancement)
378-
379-### Adding New Unicode Characters
380-
381-When adding new Unicode characters to the TUI:
382-
383-1. **Choose non-ambiguous width characters:** Use `runewidth` to verify
384-2. **Update `TestUnicodeCharacterInventory`:** Add to inventory map with usage
385-3. **Verify width:** Run `TestUnicodeWidthConsistency` with new character
386-4. **Update golden files:** Run `go test ./internal/tui -update`
387-5. **Test manually:** Verify in multiple terminals (see checklist above)
388-
389-## Spinner Testing Guidelines
390-
391-### Animation Testing
392-
393-The spinner animation is tested via `TestSpinnerFrameRendering` which verifies:
394-- All 8 frames render correctly
395-- Each frame uses the correct Unicode character
396-- Frame sequence follows expected pattern (hexagonal theme)
397-- Animation speed matches specification (8 FPS, 125ms per frame)
398-
399-**Test Pattern:**
400-```go
401-func TestSpinnerFrameRendering(t *testing.T) {
402- frames := []string{"⬡", "⬢", "⬡", "⬢", "⬦", "⬥", "⬦", "⬥"}
403-
404- for i, expectedChar := range frames {
405- t.Run(fmt.Sprintf("frame_%d", i), func(t *testing.T) {
406- actual := getSpinnerFrame(i)
407- if actual != expectedChar {
408- t.Errorf("frame %d: expected %q, got %q", i, expectedChar, actual)
409- }
410- })
411- }
412-}
413-```
414-
415-**Manual Verification:**
416-1. Run `./bin/zoea --offline`
417-2. Create a mysis (press `n`)
418-3. Observe running state indicator animates smoothly
419-4. All frames should be visible and distinct
420-5. No frame should cause layout shift
421-
422-**Spinner Specifications:**
423-- Frames: 8 total
424-- Pattern: Hexagonal theme alternating between filled/hollow shapes
425-- Speed: 8 FPS (125ms per frame)
426-- Unicode characters: All verified non-ambiguous width
427-
428-## Golden File Update Process
429-
430-### When to Update
431-
432-Update golden files when:
433-1. **Intentionally changing UI** - Color changes, layout changes, new elements
434-2. **After Phase 1 border color fix** - Border RGB codes changed
435-3. **After Unicode character replacements** - Character codepoints changed
436-4. **After adding new golden tests** - Initial generation
437-
438-### How to Update
439-
440-```bash
441-# Update all golden files
442-go test ./internal/tui -update
443-
444-# Update specific test golden files
445-go test ./internal/tui -run TestDashboard -update
446-go test ./internal/tui -run TestFocusView -update
447-```
448-
449-### Verification After Update
450-
451-```bash
452-# 1. Verify all tests pass
453-go test ./internal/tui
454-
455-# 2. Review changes to golden files
456-git diff internal/tui/testdata/
457-
458-# 3. Check for expected changes
459-# - Phase 1: RGB color codes changed from 42,42,85 to 107,0,179
460-# - Phase 3: Unicode codepoints changed for replaced characters
461-# - Phase 4: Spinner frames use new characters
462-
463-# 4. Commit golden file updates with descriptive message
464-git add internal/tui/testdata/
465-git commit -m "test: update golden files after [phase description]"
466-```
467-
468-### Golden File Structure
469-
470-Each test has two variants:
471-- **ANSI.golden** - Full output with ANSI escape codes (RGB colors, styles)
472-- **Stripped.golden** - Content only, ANSI codes removed
473-
474-**Example:**
475-```
476-internal/tui/testdata/
477-├── TestDashboard/
478-│ ├── empty_swarm/
479-│ │ ├── ANSI.golden # Full ANSI with RGB codes
480-│ │ └── Stripped.golden # Content only
481-│ └── with_swarm_messages/
482-│ ├── ANSI.golden
483-│ └── Stripped.golden
484-```
485-
486-**Why Two Variants:**
487-- **ANSI** - Catches color and style regressions
488-- **Stripped** - Catches content and layout regressions (easier to read diffs)
489-
490-## Layout Testing Guidelines
491-
492-### Dashboard Layout
493-
494-The dashboard layout calculation is tested via `TestDashboardLayoutCalculations` and `TestDashboardHeightCalculation`:
495-
496-**What to test:**
497-- Terminal sizes from 80x20 to 200x100
498-- Various mysis counts (0, 1, 5, 10, 20)
499-- Various swarm message counts (0, 5, 10, 20)
500-- No panics during rendering
501-- Minimum height guards enforced
502-
503-**Test Pattern:**
504-```go
505-func TestDashboardLayoutCalculations(t *testing.T) {
506- testCases := []struct {
507- width, height int
508- mysisCount int
509- messageCount int
510- }{
511- {80, 20, 0, 0},
512- {120, 40, 5, 5},
513- {200, 100, 20, 10},
514- }
515-
516- for _, tc := range testCases {
517- t.Run(fmt.Sprintf("%dx%d_m%d_msg%d", tc.width, tc.height, tc.mysisCount, tc.messageCount), func(t *testing.T) {
518- // Render and verify no panics
519- output := RenderDashboard(...)
520- if output == "" {
521- t.Error("empty output")
522- }
523- })
524- }
525-}
526-```
527-
528-### Focus View Layout
529-
530-The focus view layout calculation is tested via `TestFocusViewLayoutCalculations` and `TestViewportHeightCalculation`:
531-
532-**What to test:**
533-- Terminal sizes from 80x10 to 200x100
534-- Various log entry counts (0, 5, 20, 50, 100, 500, 1000)
535-- Viewport height minimum enforcement (5 lines)
536-- No negative heights
537-- No panics during rendering
538-
539-**Test Pattern:**
540-```go
541-func TestFocusViewLayoutCalculations(t *testing.T) {
542- testCases := []struct {
543- width, height int
544- logCount int
545- }{
546- {80, 10, 0},
547- {120, 40, 50},
548- {200, 100, 1000},
549- }
550-
551- for _, tc := range testCases {
552- t.Run(fmt.Sprintf("%dx%d_logs%d", tc.width, tc.height, tc.logCount), func(t *testing.T) {
553- // Render and verify no panics
554- output := RenderFocusViewWithViewport(...)
555- if output == "" {
556- t.Error("empty output")
557- }
558- })
559- }
560-}
561-```
562-
563-### Minimum Dimension Guards
564-
565-**Critical safety checks:**
566-- Dashboard mysis list height: `if mysisListHeight < 3 { mysisListHeight = 3 }`
567-- Focus view viewport height: `if vpHeight < 5 { vpHeight = 5 }`
568-- Content width: `if contentWidth < 20 { contentWidth = 20 }`
569-
570-**Test Coverage:**
571-- `TestLayoutNoNegativeHeights` verifies no negative heights at extreme small sizes
572-- All guards tested with terminal heights from 5 to 100 lines
573-- All guards tested with terminal widths from 10 to 200 columns
574-
575-## Width Calculation Testing Guidelines
576-
577-### Lipgloss Width vs len()
578-
579-**Critical Rule:** NEVER use `len()` for width calculations with Unicode or styled strings.
580-
581-**Test Pattern:**
582-```go
583-func TestWidthCalculations(t *testing.T) {
584- // Unicode character that is 3 bytes but displays as 1 column
585- unicodeStr := "⬥"
586-
587- // WRONG: len() returns 3 (bytes)
588- bytesWidth := len(unicodeStr)
589-
590- // RIGHT: lipgloss.Width() returns 1 (display width)
591- displayWidth := lipgloss.Width(unicodeStr)
592-
593- if bytesWidth == displayWidth {
594- t.Error("len() should NOT equal lipgloss.Width() for Unicode")
595- }
596-
597- if displayWidth != 1 {
598- t.Errorf("expected display width 1, got %d", displayWidth)
599- }
600-}
601-```
602-
Cut short: this commit's diff is over 1000 lines.