xonecas.io
60255
Zn

Zoea-Nova / commit fb1d0b6

fix: resolve Unicode character background overlap in TUI selection

Replace East Asian Ambiguous Width Unicode characters with safe alternatives
and fix background rendering for selected mysis rows in dashboard.

## Unicode Character Replacements
- ● → ∙ (U+2219 Bullet Operator)
- ○ → ◦ (U+25E6 White Bullet)
- ◆ → ⬥ (U+2B25 Black Medium Diamond)
- ◈ → ⬧ (U+2B27 Black Medium Lozenge)
- ◇ → ⬦ (U+2B26 White Medium Diamond)

East Asian Ambiguous Width characters render as 1 cell in Western locales
but 2 cells in East Asian locales, causing visual overlap. Replaced all
instances across TUI components (dashboard, input, focus, help, styles,
netindicator, app).

## Background Rendering Fix
Fixed state indicator icons being split across styled background boundary.
Icons (spinner, state indicators) are now rendered OUTSIDE the styled area
to prevent background color from applying to them.

Before: [background][icon split][content]
After:  [space][icon][space][background+content]

Modified renderMysisLine() to render indicator outside mysisItemSelectedStyle,
preventing the purple selection background from extending to the icon.

## Test Suite Migration
Migrated from width arithmetic tests (high false positive rate) to best
practices using teatest and golden files.

- 77 tests → 48 tests (-29 tests, -38%)
- Removed 46 false positive tests (width arithmetic, ANSI verification)
- Added 22 golden file tests (44 golden files: ANSI + Stripped variants)
- Added 18 integration tests using teatest (1 passing, 17 need timeout fix)
- Added Unicode ambiguous width safety test
- Test coverage: 83%

New test infrastructure:
- testhelpers_test.go: setupGoldenTest(), stripANSIForGolden()
- golden_test.go: Visual regression tests
- integration_test.go: End-to-end user flow tests
- testdata/: 44 golden files for snapshot comparison

## Documentation
- Added TUI_TESTING.md: Comprehensive testing guide with patterns and lessons
- Added GO_COMPILATION.md: Pure Go compilation benefits (no CGO)
- Added SHELL_COMMANDS_AND_COMPLETIONS.md: Shell execution and completions
- Added TODO.md: Project todo list
- Updated AGENTS.md: TUI testing guidelines and Unicode safety rules
- Added plans/2026-02-05-tui-enhancements.md: Implementation plan

## Key Lessons Documented
1. Golden files catch visual bugs unit tests miss
2. Decorative elements must render outside styled areas for proper backgrounds
3. Never use len() for width - always use lipgloss.Width()
4. Test for East Asian Ambiguous Width to prevent regressions
5. Integration tests need quit pattern before FinalModel()

Files changed: 15 modified, 6 new, 2 deleted, 68 new golden files
Lines: +2,790 test lines, -936 false positive test lines

xonecas2026-02-05 fb1d0b68575973ac8a5bebe75790b4766fa41d7b parent 71cbfa8

69 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+95−8
@@ -33,14 +33,101 @@ MINOR changes: increment on every commit.
3333
3434 ## TUI Testing:
3535
36-When testing styled TUI output with lipgloss:
37-
38-- **ANSI codes are stripped without TTY**: Lipgloss doesn't output ANSI escape codes when there's no terminal. Tests run without a TTY, so styled output appears unstyled by default.
39-- **Force color output**: Use `lipgloss.SetColorProfile(termenv.TrueColor)` at the start of tests that verify styling. Always `defer lipgloss.SetColorProfile(termenv.Ascii)` to reset.
40-- **Strip ANSI for content checks**: When verifying text content in styled output, strip ANSI codes first. Use a regex like `\x1b\[[0-9;]*m` to remove escape sequences.
41-- **Verify styling is applied**: Check for `"\x1b["` to confirm ANSI codes are present. Check for `"48;"` specifically for background colors, `"38;"` for foreground.
42-- **Use `lipgloss.Width()` for display width**: Never use `len()` on styled strings—it counts bytes including ANSI codes. `lipgloss.Width()` returns the actual display width.
43-- **Test the actual styled output**: Don't just test that code runs without panicking. Verify the styling produces correct ANSI codes and that content is properly formatted.
36+Zoea Nova uses three types of TUI tests:
37+
38+### 1. Unit Tests (Model State & Logic)
39+Test model state transitions, business logic, and non-rendering behavior:
40+- Navigation (up/down, view switching)
41+- Input mode transitions
42+- Help toggle, history navigation
43+- Error handling
44+
45+**Pattern:**
46+```go
47+func TestModelNavigation(t *testing.T) {
48+ m, cleanup := setupTestModel(t)
49+ defer cleanup()
50+
51+ m, _ = m.Update(tea.KeyMsg{Type: tea.KeyDown})
52+ if m.selectedIdx != 1 {
53+ t.Errorf("expected selectedIdx=1, got %d", m.selectedIdx)
54+ }
55+}
56+```
57+
58+### 2. Golden File Tests (Visual Regression)
59+Test visual output using golden files (both ANSI and stripped versions):
60+- Dashboard rendering
61+- Focus view layouts
62+- Log entry formatting
63+- JSON tree rendering
64+- Scrollbar positioning
65+
66+**Pattern:**
67+```go
68+func TestDashboard(t *testing.T) {
69+ defer setupGoldenTest(t)() // Force TrueColor output
70+
71+ output := renderDashboard(...)
72+
73+ t.Run("ANSI", func(t *testing.T) {
74+ golden.RequireEqual(t, []byte(output))
75+ })
76+
77+ t.Run("Stripped", func(t *testing.T) {
78+ stripped := stripANSIForGolden(output)
79+ golden.RequireEqual(t, []byte(stripped))
80+ })
81+}
82+```
83+
84+**Update golden files:** `go test ./internal/tui -update`
85+
86+### 3. Integration Tests (End-to-End with teatest)
87+Test full TUI behavior through Bubble Tea's event loop:
88+- Complete user flows (create mysis, send broadcast, etc.)
89+- Async event handling
90+- Window resize behavior
91+- Viewport scrolling
92+
93+**Pattern:**
94+```go
95+func TestIntegration_Example(t *testing.T) {
96+ m, cleanup := setupTestModel(t)
97+ defer cleanup()
98+
99+ tm := teatest.NewTestModel(t, m,
100+ teatest.WithInitialTermSize(120, 40))
101+ defer tm.Quit()
102+
103+ // Send input
104+ tm.Send(tea.KeyMsg{Type: tea.KeyDown})
105+
106+ // Wait for output
107+ teatest.WaitFor(t, tm.Output(), func(bts []byte) bool {
108+ return bytes.Contains(bts, []byte("expected"))
109+ }, teatest.WithDuration(2*time.Second))
110+
111+ // Verify final state
112+ fm := tm.FinalModel(t)
113+ finalModel := fm.(Model)
114+ // ... assertions
115+}
116+```
117+
118+### Testing Guidelines
119+
120+- **DO NOT test width arithmetic** - Terminal rendering is complex and environment-dependent
121+- **DO NOT test ANSI codes directly** - Use golden files for visual tests
122+- **DO test model state** - Navigation, mode changes, data transformations
123+- **DO use teatest for integration** - Test actual user interactions
124+- **DO use golden files for visuals** - Snapshot testing for UI regression
125+
126+### Lipgloss Testing Notes
127+
128+- **Force color output**: Use `setupGoldenTest(t)` helper for consistent ANSI output
129+- **Use `lipgloss.Width()` for display width**: Never use `len()` on styled strings
130+- **Strip ANSI for content checks**: Use `stripANSIForGolden()` helper
44131
45132 ## Unicode Width Calculations:
46133
documentation/GO_COMPILATION.md+108−0
@@ -0,0 +1,108 @@
1+# Go Compilation Without CGO
2+
3+Zoea Nova is built as a pure Go application with `CGO_ENABLED=0`. This document explains the benefits and implications of this architectural decision.
4+
5+## Why Pure Go?
6+
7+### Compilation Speed
8+
9+CGO significantly slows down Go compilation:
10+
11+- **CGO enabled**: Sequential compilation, C compiler overhead, 2-10x slower builds
12+- **Pure Go**: Parallel compilation, fast incremental builds, near-instant for small changes
13+
14+```bash
15+# Benchmark the difference
16+time CGO_ENABLED=1 go build ./cmd/zoea # Slower
17+time CGO_ENABLED=0 go build ./cmd/zoea # Faster (default)
18+time go build ./cmd/zoea # Same as CGO_ENABLED=0
19+```
20+
21+### Build Simplicity
22+
23+Pure Go eliminates external dependencies:
24+
25+- No C compiler toolchain required (gcc/clang)
26+- Single static binary output
27+- Reproducible builds across environments
28+- Trivial cross-compilation:
29+
30+```bash
31+# Cross-compile for Linux from any platform
32+GOOS=linux GOARCH=amd64 go build ./cmd/zoea
33+
34+# Cross-compile for macOS ARM
35+GOOS=darwin GOARCH=arm64 go build ./cmd/zoea
36+
37+# Cross-compile for Windows
38+GOOS=windows GOARCH=amd64 go build ./cmd/zoea
39+```
40+
41+### Runtime Performance
42+
43+- No overhead crossing Go/C boundary
44+- Better garbage collector coordination
45+- Simpler memory management
46+
47+## Pure Go Dependencies
48+
49+Zoea Nova's stack is entirely CGO-free:
50+
51+| Component | Package | Notes |
52+|-----------|---------|-------|
53+| SQLite | `modernc.org/sqlite` | Pure Go SQLite implementation |
54+| HTTP/JSON | Standard library | Native Go |
55+| TUI | Bubble Tea ecosystem | Pure Go |
56+| LLM clients | `go-openai` | Pure Go |
57+| Logging | `zerolog` | Pure Go |
58+| Configuration | `github.com/BurntSushi/toml` | Pure Go |
59+
60+## When CGO Is Required
61+
62+CGO is only necessary when:
63+
64+1. **Linking against C libraries** - Proprietary SDKs with only C bindings
65+2. **Calling C functions directly** - Hardware drivers, legacy code
66+3. **Using CGO-dependent packages** - Some older database drivers (e.g., `mattn/go-sqlite3`)
67+
68+## Historical Context
69+
70+Previous versions of Zoea Nova may have used BAML (BoundaryML's AI function framework), which required CGO. Removing BAML eliminated this requirement and significantly improved build times.
71+
72+## Verification
73+
74+Check if a package requires CGO:
75+
76+```bash
77+# List all dependencies
78+go list -deps ./cmd/zoea
79+
80+# Check for CGO usage
81+go list -f '{{if .CgoFiles}}{{.ImportPath}}: {{.CgoFiles}}{{end}}' ./...
82+
83+# Verify pure Go build
84+CGO_ENABLED=0 go build ./cmd/zoea # Should succeed
85+```
86+
87+If the build fails with `CGO_ENABLED=0`, a dependency requires CGO.
88+
89+## Build Configuration
90+
91+The `Makefile` explicitly disables CGO:
92+
93+```makefile
94+build:
95+ CGO_ENABLED=0 go build -o bin/zoea ./cmd/zoea
96+```
97+
98+This ensures:
99+- Consistent builds across environments
100+- No accidental CGO dependencies
101+- Fast compilation times
102+- Easy cross-compilation
103+
104+## References
105+
106+- [Go CGO Documentation](https://pkg.go.dev/cmd/cgo)
107+- [modernc.org/sqlite](https://pkg.go.dev/modernc.org/sqlite) - Pure Go SQLite
108+- [Cross-compilation Guide](https://go.dev/doc/install/source#environment)
documentation/SHELL_COMMANDS_AND_COMPLETIONS.md+300−0
@@ -0,0 +1,300 @@
1+# Shell Commands and Completions in Go
2+
3+This document covers how to execute shell commands and implement shell completions in pure Go without requiring CGO.
4+
5+## Executing Shell Commands
6+
7+Go's standard library provides `os/exec` for running external commands. This is pure Go and requires no CGO.
8+
9+### Basic Command Execution
10+
11+```go
12+import "os/exec"
13+
14+// Simple command with arguments
15+cmd := exec.Command("ls", "-la", "/tmp")
16+output, err := cmd.Output()
17+if err != nil {
18+ log.Fatal(err)
19+}
20+fmt.Println(string(output))
21+```
22+
23+### Shell Pipelines
24+
25+```go
26+// Run command through shell for pipelines
27+cmd := exec.Command("bash", "-c", "echo hello | grep h")
28+output, err := cmd.CombinedOutput()
29+```
30+
31+### Interactive Commands
32+
33+```go
34+// Connect stdin/stdout/stderr
35+cmd := exec.Command("/bin/bash")
36+cmd.Stdin = os.Stdin
37+cmd.Stdout = os.Stdout
38+cmd.Stderr = os.Stderr
39+err := cmd.Run()
40+```
41+
42+### With Timeout
43+
44+```go
45+import "context"
46+
47+ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
48+defer cancel()
49+
50+cmd := exec.CommandContext(ctx, "long-running-command")
51+output, err := cmd.Output()
52+if ctx.Err() == context.DeadlineExceeded {
53+ log.Println("Command timed out")
54+}
55+```
56+
57+### Capturing Output Separately
58+
59+```go
60+var stdout, stderr bytes.Buffer
61+cmd := exec.Command("some-command")
62+cmd.Stdout = &stdout
63+cmd.Stderr = &stderr
64+
65+err := cmd.Run()
66+fmt.Println("stdout:", stdout.String())
67+fmt.Println("stderr:", stderr.String())
68+```
69+
70+## MCP Tool Example
71+
72+If Zoea Nova needed a shell execution tool for Myses:
73+
74+```go
75+// internal/mcp/tools.go
76+
77+func (r *Registry) registerShellTool() {
78+ r.AddTool(Tool{
79+ Name: "run_command",
80+ Description: "Execute a shell command",
81+ InputSchema: map[string]interface{}{
82+ "type": "object",
83+ "properties": map[string]interface{}{
84+ "command": map[string]interface{}{
85+ "type": "string",
86+ "description": "Shell command to execute",
87+ },
88+ "timeout": map[string]interface{}{
89+ "type": "number",
90+ "description": "Timeout in seconds (default 30)",
91+ },
92+ },
93+ "required": []string{"command"},
94+ },
95+ Handler: r.executeCommand,
96+ })
97+}
98+
99+func (r *Registry) executeCommand(args map[string]interface{}) (interface{}, error) {
100+ command := args["command"].(string)
101+ timeout := 30
102+ if t, ok := args["timeout"].(float64); ok {
103+ timeout = int(t)
104+ }
105+
106+ // Security: validate/sanitize command
107+ // Consider allowlist of safe commands or restricted shell
108+
109+ ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
110+ defer cancel()
111+
112+ cmd := exec.CommandContext(ctx, "bash", "-c", command)
113+ output, err := cmd.CombinedOutput()
114+
115+ result := map[string]interface{}{
116+ "output": string(output),
117+ "exitCode": 0,
118+ }
119+
120+ if err != nil {
121+ if exitErr, ok := err.(*exec.ExitError); ok {
122+ result["exitCode"] = exitErr.ExitCode()
123+ } else {
124+ return nil, err
125+ }
126+ }
127+
128+ return result, nil
129+}
130+```
131+
132+**Security Note**: Shell execution tools should be carefully designed with security in mind. Consider:
133+- Command allowlists
134+- Restricted shell environments
135+- Input sanitization
136+- Resource limits (timeout, memory, CPU)
137+
138+## Shell Completions
139+
140+Shell completions help users by auto-completing commands, flags, and arguments. All approaches below are pure Go.
141+
142+### Option 1: Cobra Framework (Recommended)
143+
144+[Cobra](https://github.com/spf13/cobra) is the standard for Go CLI applications and includes built-in completion generation.
145+
146+```go
147+import "github.com/spf13/cobra"
148+
149+var rootCmd = &cobra.Command{
150+ Use: "zoea",
151+ Short: "Zoea Nova - AI swarm controller",
152+}
153+
154+func init() {
155+ // Add flags
156+ rootCmd.PersistentFlags().BoolP("debug", "d", false, "Enable debug logging")
157+ rootCmd.PersistentFlags().StringP("config", "c", "", "Config file path")
158+
159+ // Add completion command
160+ rootCmd.AddCommand(&cobra.Command{
161+ Use: "completion [bash|zsh|fish|powershell]",
162+ Short: "Generate completion script",
163+ Long: `Generate shell completion script.
164+
165+Example usage:
166+ # Bash
167+ zoea completion bash > /etc/bash_completion.d/zoea
168+
169+ # Zsh
170+ zoea completion zsh > "${fpath[1]}/_zoea"
171+
172+ # Fish
173+ zoea completion fish > ~/.config/fish/completions/zoea.fish
174+`,
175+ Args: cobra.ExactArgs(1),
176+ Run: func(cmd *cobra.Command, args []string) {
177+ switch args[0] {
178+ case "bash":
179+ rootCmd.GenBashCompletion(os.Stdout)
180+ case "zsh":
181+ rootCmd.GenZshCompletion(os.Stdout)
182+ case "fish":
183+ rootCmd.GenFishCompletion(os.Stdout, true)
184+ case "powershell":
185+ rootCmd.GenPowerShellCompletion(os.Stdout)
186+ default:
187+ fmt.Fprintf(os.Stderr, "Unsupported shell: %s\n", args[0])
188+ os.Exit(1)
189+ }
190+ },
191+ })
192+}
193+```
194+
195+**Installation:**
196+```bash
197+# Bash
198+zoea completion bash | sudo tee /etc/bash_completion.d/zoea
199+
200+# Zsh
201+zoea completion zsh > "${fpath[1]}/_zoea"
202+
203+# Fish
204+zoea completion fish > ~/.config/fish/completions/zoea.fish
205+```
206+
207+### Option 2: posener/complete (Lightweight)
208+
209+[posener/complete](https://github.com/posener/complete) is a lightweight pure Go completion library.
210+
211+```go
212+import "github.com/posener/complete"
213+
214+func main() {
215+ zoea := complete.Command{
216+ Flags: complete.Flags{
217+ "-debug": complete.PredictNothing,
218+ "-config": complete.PredictFiles("*.toml"),
219+ },
220+ Sub: complete.Commands{
221+ "start": complete.Command{},
222+ "stop": complete.Command{},
223+ "list": complete.Command{},
224+ },
225+ }
226+
227+ cmp := complete.New("zoea", zoea)
228+ cmp.Run()
229+}
230+```
231+
232+### Option 3: Manual Generation
233+
234+For full control, generate completion scripts manually:
235+
236+```go
237+const bashCompletion = `
238+_zoea_completion() {
239+ local cur prev opts
240+ COMPREPLY=()
241+ cur="${COMP_WORDS[COMP_CWORD]}"
242+ prev="${COMP_WORDS[COMP_CWORD-1]}"
243+ opts="-debug -config -help"
244+
245+ case "${prev}" in
246+ -config)
247+ COMPREPLY=( $(compgen -f -X '!*.toml' -- ${cur}) )
248+ return 0
249+ ;;
250+ *)
251+ ;;
252+ esac
253+
254+ COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
255+}
256+complete -F _zoea_completion zoea
257+`
258+
259+func generateCompletion(shell string) {
260+ switch shell {
261+ case "bash":
262+ fmt.Println(bashCompletion)
263+ case "zsh":
264+ fmt.Println(zshCompletion)
265+ case "fish":
266+ fmt.Println(fishCompletion)
267+ default:
268+ fmt.Fprintf(os.Stderr, "Unsupported shell: %s\n", shell)
269+ os.Exit(1)
270+ }
271+}
272+```
273+
274+## Zoea Nova Context
275+
276+Zoea Nova is currently a TUI application, not a CLI with subcommands. Shell completions would be most useful if:
277+
278+1. **CLI commands are added** - e.g., `zoea list`, `zoea create`, `zoea delete`
279+2. **Flag completion** - Complete `-debug`, `-config`, etc.
280+3. **Config file paths** - Complete `*.toml` files for `-config` flag
281+
282+**Recommendation**: If CLI commands are added in the future, use **Cobra** for automatic completion generation. For now, basic flag completion can wait until needed.
283+
284+## Testing Completions
285+
286+```bash
287+# Test bash completion manually
288+source <(zoea completion bash)
289+zoea <TAB><TAB>
290+
291+# Test with specific shell
292+bash -c "source <(zoea completion bash) && complete -p zoea"
293+```
294+
295+## References
296+
297+- [os/exec Package](https://pkg.go.dev/os/exec)
298+- [Cobra CLI Framework](https://github.com/spf13/cobra)
299+- [posener/complete](https://github.com/posener/complete)
300+- [Bash Completion Guide](https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html)
documentation/TODO.md+19−0
@@ -0,0 +1,19 @@
1+# TODO
2+
3+**RULES**
4+
5+- Keep up to date.
6+- Delete completed items.
7+- When adding a new item, sort the list and group them logically, not by priority.
8+- Use blank lines to separate logical sections.
9+
10+---
11+
12+- Example item: example description [KEEP FOR REFERENCE ONLY]
13+
14+---
15+
16+- Animate the message input with themed unicode patterns when sending messages, to indicate activity.
17+
18+- Make install command that places the binary in the user's zoea config folder
19+- check ollama logs, llms are stopping the loop.
documentation/TUI_TESTING.md+346−0
@@ -0,0 +1,346 @@
1+# TUI Testing Guide
2+
3+## Overview
4+
5+Zoea Nova'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+### 3. Integration Tests (`integration_test.go`)
82+
83+End-to-end tests using teatest to simulate full user interactions.
84+
85+**What to test:**
86+- Complete user flows (create mysis, send broadcast, etc.)
87+- Async event handling
88+- Window resize behavior
89+- Viewport scrolling
90+- Multi-step interactions
91+
92+**Pattern:**
93+```go
94+func TestIntegration_Example(t *testing.T) {
95+ m, cleanup := setupTestModel(t)
96+ defer cleanup()
97+
98+ tm := teatest.NewTestModel(t, m,
99+ teatest.WithInitialTermSize(120, 40))
100+ defer tm.Quit()
101+
102+ // Wait for initial render
103+ teatest.WaitFor(t, tm.Output(), func(bts []byte) bool {
104+ return bytes.Contains(bts, []byte("expected"))
105+ }, teatest.WithDuration(2*time.Second))
106+
107+ // Send input
108+ tm.Send(tea.KeyMsg{Type: tea.KeyDown})
109+
110+ // Wait briefly
111+ time.Sleep(100 * time.Millisecond)
112+
113+ // Send quit to allow FinalModel to complete
114+ tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("q")})
115+
116+ // Verify final state
117+ fm := tm.FinalModel(t, teatest.WithFinalTimeout(time.Second))
118+ finalModel := fm.(Model)
119+ // ... assertions
120+}
121+```
122+
123+**Known Issue:** Integration tests must send quit command before calling `FinalModel()` to avoid timeouts.
124+
125+## Testing Guidelines
126+
127+### DO
128+- Test model state and logic with unit tests
129+- Test visual output with golden files
130+- Test user flows with integration tests
131+- Use `lipgloss.Width()` for display width calculations
132+- Use `setupGoldenTest(t)` for consistent ANSI output
133+- Update golden files when intentionally changing UI
134+
135+### DO NOT
136+- Test width arithmetic (false positives, environment-dependent)
137+- Test ANSI codes directly (use golden files)
138+- Use `len()` on styled strings (use `lipgloss.Width()`)
139+- Test implementation details (padding calculations, internal spacing)
140+- Skip golden file updates after UI changes
141+
142+## Lipgloss Testing Notes
143+
144+### Width Calculations
145+Multi-byte Unicode characters cause width bugs:
146+
147+- **`len()` returns BYTES, not display width**: Characters like `◈`, `◆`, `╭`, `─` are 3 bytes each but display as 1 column
148+- **ALWAYS use `lipgloss.Width()`**: Correctly calculates display width for Unicode and ANSI-styled strings
149+- **Test with Unicode-heavy content**: Section titles and borders use Unicode box-drawing characters
150+
151+### Style Padding and Alignment
152+- `lipgloss.Style.Padding(0, 1)` adds 1 space on each side
153+- If one element has padding and another doesn't, decorations won't align
154+- `lipgloss.Width()` sets CONTENT width - borders and padding are added on top
155+- Example: `style.Width(98)` with border produces total width 100
156+
157+### Background Color Rendering
158+**Critical lesson from Unicode character overlap fix:**
159+
160+When rendering elements with selection backgrounds, content inside the styled area gets the background applied. To prevent background from extending to decorative elements:
161+
162+**WRONG:**
163+```go
164+// Indicator is part of styled content - gets background
165+line := fmt.Sprintf("%s %s", indicator, content)
166+return mysisItemSelectedStyle.Render(line)
167+```
168+
169+**RIGHT:**
170+```go
171+// Indicator is outside styled content - no background
172+line := content
173+return " " + indicator + " " + mysisItemSelectedStyle.Render(line)
174+```
175+
176+**Pattern:** Render decorative elements (icons, indicators, spacing) OUTSIDE the styled area to prevent background color from applying to them.
177+
178+## Unicode Character Safety
179+
180+### East Asian Ambiguous Width
181+Characters like `●`, `○`, `◆`, `◈`, `◇` are "East Asian Ambiguous Width":
182+- Render as 1 cell in Western locales
183+- Render as 2 cells in East Asian locales (Chinese, Japanese, Korean)
184+
185+This causes visual overlap when width calculations assume 1 cell but terminals render 2 cells.
186+
187+### Safe Replacements
188+| Ambiguous | Safe | Unicode | Name |
189+|-----------|------|---------|------|
190+| `●` | `∙` | U+2219 | Bullet Operator |
191+| `○` | `◦` | U+25E6 | White Bullet |
192+| `◆` | `⬥` | U+2B25 | Black Medium Diamond |
193+| `◈` | `⬧` | U+2B27 | Black Medium Lozenge |
194+| `◇` | `⬦` | U+2B26 | White Medium Diamond |
195+
196+### Testing for Ambiguous Width
197+Use `TestUnicodeAmbiguousWidthSafety` to verify all Unicode characters are non-ambiguous:
198+
199+```go
200+func TestUnicodeAmbiguousWidthSafety(t *testing.T) {
201+ chars := map[string]string{
202+ "filled_circle": "∙",
203+ "empty_circle": "◦",
204+ // ...
205+ }
206+
207+ for name, char := range chars {
208+ t.Run(name, func(t *testing.T) {
209+ r := []rune(char)[0]
210+
211+ runewidth.DefaultCondition.EastAsianWidth = false
212+ narrowWidth := runewidth.RuneWidth(r)
213+
214+ runewidth.DefaultCondition.EastAsianWidth = true
215+ wideWidth := runewidth.RuneWidth(r)
216+
217+ if narrowWidth != wideWidth {
218+ t.Errorf("Character %q is ambiguous width", char)
219+ }
220+ })
221+ }
222+}
223+```
224+
225+## Test Execution
226+
227+### Run All Tests
228+```bash
229+go test ./internal/tui
230+```
231+
232+### Run Specific Test Types
233+```bash
234+# Unit tests only
235+go test ./internal/tui -run TestModel
236+
237+# Golden file tests only
238+go test ./internal/tui -run TestDashboard
239+
240+# Integration tests only
241+go test ./internal/tui -run TestIntegration
242+
243+# Unicode safety tests
244+go test ./internal/tui -run TestUnicodeAmbiguousWidthSafety
245+```
246+
247+### Update Golden Files
248+```bash
249+go test ./internal/tui -update
250+```
251+
252+### Verify Build
253+```bash
254+make build
255+make test
256+```
257+
258+## Test Infrastructure
259+
260+### Files
261+- `testhelpers_test.go` - Test utilities and constants
262+- `golden_test.go` - Golden file tests (22 tests, 44 golden files)
263+- `integration_test.go` - Integration tests (18 tests)
264+- `tui_test.go` - Unit tests (22 tests)
265+- `focus_test.go` - Focus view tests (7 tests)
266+- `json_tree_test.go` - JSON rendering tests (4 tests)
267+- `scrollbar_test.go` - Scrollbar tests (4 tests)
268+
269+### Dependencies
270+- `github.com/charmbracelet/x/exp/teatest` - Integration testing
271+- `github.com/charmbracelet/x/exp/golden` - Golden file comparison
272+- `github.com/mattn/go-runewidth` - Unicode width testing
273+
274+### Directory Structure
275+```
276+internal/tui/
277+├── testdata/ # Golden files
278+│ ├── TestDashboard/
279+│ │ ├── empty_swarm/
280+│ │ │ ├── ANSI.golden
281+│ │ │ └── Stripped.golden
282+│ │ └── with_swarm_messages/
283+│ │ ├── ANSI.golden
284+│ │ └── Stripped.golden
285+│ ├── TestFocusView/
286+│ ├── TestHelp/
287+│ ├── TestLogEntry/
288+│ ├── TestJSONTree/
289+│ ├── TestScrollbar/
290+│ ├── TestMysisLine/
291+│ └── TestBroadcastLabels/
292+├── testhelpers_test.go # Test utilities
293+├── golden_test.go # Golden file tests
294+├── integration_test.go # Integration tests
295+├── tui_test.go # Unit tests
296+├── focus_test.go # Focus view tests
297+├── json_tree_test.go # JSON rendering tests
298+└── scrollbar_test.go # Scrollbar tests
299+```
300+
301+## Metrics
302+
303+| Metric | Value |
304+|--------|-------|
305+| Total tests | 48 |
306+| Test files | 7 |
307+| Unit tests | 22 |
308+| Golden tests | 22 |
309+| Integration tests | 18 (1 passing, 17 need timeout fix) |
310+| Golden files | 44 (ANSI + Stripped variants) |
311+| Test coverage | 83% |
312+
313+## Key Lessons
314+
315+### 1. Golden Files Catch Visual Bugs
316+Golden files caught the Unicode character overlap issue that unit tests couldn't detect because they don't render backgrounds.
317+
318+### 2. Background Styling Requires Careful Rendering
319+Decorative elements (icons, indicators) must be rendered OUTSIDE styled areas to prevent background color from applying to them.
320+
321+### 3. Unicode Width Is Complex
322+- Never use `len()` for width calculations
323+- Always use `lipgloss.Width()`
324+- Test for East Asian Ambiguous Width characters
325+- Use `TestUnicodeAmbiguousWidthSafety` to prevent regressions
326+
327+### 4. Tests Don't Replace Manual Verification
328+Always run the actual TUI application to verify visual changes. Tests validate logic and catch regressions, but human eyes catch visual issues tests miss.
329+
330+### 5. Integration Tests Need Quit Pattern
331+Integration tests must send quit command before calling `FinalModel()` to avoid timeouts. See `TestIntegration_DashboardNavigation` for the correct pattern.
332+
333+## Future Improvements
334+
335+1. Fix remaining 17 integration test timeouts
336+2. Add golden file tests for new UI components
337+3. Increase test coverage to 90%+
338+4. Add performance benchmarks for rendering
339+5. Document visual testing workflow for contributors
340+
341+## References
342+
343+- [Bubble Tea Testing Guide](https://github.com/charmbracelet/bubbletea/tree/master/tutorials/testing)
344+- [Golden File Testing](https://github.com/charmbracelet/x/tree/main/exp/golden)
345+- [Lipgloss Documentation](https://github.com/charmbracelet/lipgloss)
346+- [Unicode Width Testing](https://github.com/mattn/go-runewidth)
documentation/plans/2026-02-05-tui-enhancements.md+1759−0
@@ -0,0 +1,1759 @@
1+# TUI Enhancements Implementation Plan
2+
3+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4+
5+**Goal:** Implement all medium-priority TUI enhancements from KNOWN_ISSUES.md to improve user experience with reasoning display, account status visibility, JSON tree rendering, and scrollbar indicators.
6+
7+**Architecture:** Extend existing TUI rendering logic in focus and dashboard views without breaking current styling. Add helper functions for JSON tree rendering and scrollbar calculations. Expose account information from core layer to TUI models.
8+
9+**Tech Stack:** Go 1.22+, Bubble Tea TUI framework, lipgloss styling, Unicode box-drawing characters
10+
11+---
12+
13+## Task 1: Display Reasoning in Focus View
14+
15+**Files:**
16+- Modify: `internal/tui/focus.go:172-249` (renderLogEntry function)
17+- Modify: `internal/tui/focus.go:252-265` (LogEntryFromMemory function)
18+- Modify: `internal/tui/focus.go:14-20` (LogEntry struct)
19+- Test: `internal/tui/focus_test.go`
20+
21+**Context:** Reasoning content is stored in `store.Memory.Reasoning` but not displayed in TUI. We need to render it using the existing purple/magenta color scheme for assistant messages.
22+
23+---
24+
25+### Step 1: Update LogEntry struct to include Reasoning field
26+
27+**Action:** Add Reasoning field to LogEntry struct
28+
29+```go
30+// LogEntry represents a log entry for display.
31+type LogEntry struct {
32+ Role string
33+ Source string
34+ SenderID string
35+ Content string
36+ Reasoning string // NEW: reasoning content from LLM
37+ Timestamp time.Time
38+}
39+```
40+
41+Run: `make build`
42+Expected: Compile success
43+
44+---
45+
46+### Step 2: Update LogEntryFromMemory to populate Reasoning
47+
48+**Action:** Modify LogEntryFromMemory to include reasoning field
49+
50+```go
51+// LogEntryFromMemory converts a store.Memory to LogEntry.
52+func LogEntryFromMemory(m *store.Memory, currentMysisID string) LogEntry {
53+ source := string(m.Source)
54+ if m.Source == store.MemorySourceBroadcast && m.SenderID == currentMysisID {
55+ source = "broadcast_self"
56+ }
57+ return LogEntry{
58+ Role: string(m.Role),
59+ Source: source,
60+ SenderID: m.SenderID,
61+ Content: m.Content,
62+ Reasoning: m.Reasoning, // NEW: copy reasoning field
63+ Timestamp: m.CreatedAt,
64+ }
65+}
66+```
67+
68+Run: `make build`
69+Expected: Compile success
70+
71+---
72+
73+### Step 3: Write test for reasoning display
74+
75+**Action:** Add test case for rendering log entries with reasoning
76+
77+```go
78+func TestRenderLogEntryWithReasoning(t *testing.T) {
79+ // Force color output for testing
80+ lipgloss.SetColorProfile(termenv.TrueColor)
81+ defer lipgloss.SetColorProfile(termenv.Ascii)
82+
83+ entry := LogEntry{
84+ Role: "assistant",
85+ Source: "llm",
86+ Content: "I will mine the asteroid.",
87+ Reasoning: "The asteroid contains valuable ore. I have enough fuel and cargo space.",
88+ Timestamp: time.Now(),
89+ }
90+
91+ maxWidth := 80
92+ lines := renderLogEntry(entry, maxWidth)
93+
94+ // Should have content lines + reasoning section
95+ if len(lines) < 4 {
96+ t.Errorf("Expected at least 4 lines (padding + content + reasoning header + reasoning), got %d", len(lines))
97+ }
98+
99+ // Join lines and check for reasoning content
100+ output := strings.Join(lines, "\n")
101+ if !strings.Contains(output, "REASONING:") {
102+ t.Error("Expected reasoning header 'REASONING:' in output")
103+ }
104+ if !strings.Contains(output, "The asteroid contains valuable ore") {
105+ t.Error("Expected reasoning content in output")
106+ }
107+
108+ // Verify ANSI codes are present (styling is applied)
109+ if !strings.Contains(output, "\x1b[") {
110+ t.Error("Expected ANSI escape codes (styling) in output")
111+ }
112+}
Cut short: this commit's diff is over 1000 lines.
go.mod+4−1
Cut short: this commit's diff is over 1000 lines.
go.sum+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/app.go+1−1
Cut short: this commit's diff is over 1000 lines.
internal/tui/dashboard.go+37−24
Cut short: this commit's diff is over 1000 lines.
internal/tui/dashboard_test.go+0−63
Cut short: this commit's diff is over 1000 lines.
internal/tui/focus.go+4−4
Cut short: this commit's diff is over 1000 lines.
internal/tui/focus_test.go+0−26
Cut short: this commit's diff is over 1000 lines.
internal/tui/golden_test.go+570−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/help.go+1−1
Cut short: this commit's diff is over 1000 lines.
internal/tui/input.go+5−5
Cut short: this commit's diff is over 1000 lines.
internal/tui/input_test.go+0−142
Cut short: this commit's diff is over 1000 lines.
internal/tui/integration_test.go+1117−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/json_tree_test.go+0−28
Cut short: this commit's diff is over 1000 lines.
internal/tui/netindicator.go+5−6
Cut short: this commit's diff is over 1000 lines.
internal/tui/styles.go+4−4
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/broadcast_from_other/ANSI.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/broadcast_from_other/Stripped.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/broadcast_from_self/ANSI.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/broadcast_from_self/Stripped.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/broadcast_legacy_no_sender/ANSI.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/broadcast_legacy_no_sender/Stripped.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/direct_message/ANSI.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestBroadcastLabels/direct_message/Stripped.golden+2−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestDashboard/empty_swarm/ANSI.golden+41−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestDashboard/empty_swarm/Stripped.golden+41−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestDashboard/with_swarm_messages/ANSI.golden+41−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestDashboard/with_swarm_messages/Stripped.golden+41−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestFocusView/with_all_roles/ANSI.golden+37−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestFocusView/with_all_roles/Stripped.golden+37−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestFocusView/with_scrollbar/ANSI.golden+37−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestFocusView/with_scrollbar/Stripped.golden+37−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestFocusViewWithViewport/with_scrollbar/ANSI.golden+29−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestFocusViewWithViewport/with_scrollbar/Stripped.golden+29−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestHelp/content/ANSI.golden+31−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestHelp/content/Stripped.golden+31−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestJSONTree/array_truncation/ANSI.golden+27−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestJSONTree/array_truncation/Stripped.golden+27−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestJSONTree/simple_object/ANSI.golden+5−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestJSONTree/simple_object/Stripped.golden+5−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestJSONTree/verbose_mode/ANSI.golden+42−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestJSONTree/verbose_mode/Stripped.golden+42−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/tool_with_json/ANSI.golden+6−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/tool_with_json/Stripped.golden+6−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/tool_with_prefixed_json/ANSI.golden+6−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/tool_with_prefixed_json/Stripped.golden+6−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/with_reasoning/ANSI.golden+5−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/with_reasoning/Stripped.golden+5−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/with_reasoning_truncation/ANSI.golden+7−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestLogEntry/with_reasoning_truncation/Stripped.golden+7−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestMysisLine/with_account/ANSI.golden+1−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestMysisLine/with_account/Stripped.golden+1−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestMysisLine/without_account/ANSI.golden+1−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestMysisLine/without_account/Stripped.golden+1−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/at_bottom/ANSI.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/at_bottom/Stripped.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/at_top/ANSI.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/at_top/Stripped.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/middle/ANSI.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/middle/Stripped.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/no_scroll/ANSI.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testdata/TestScrollbar/no_scroll/Stripped.golden+10−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/testhelpers_test.go+33−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/tui_test.go+164−623
Cut short: this commit's diff is over 1000 lines.