xonecas.io
62159
Sy

symb / commit 2455182

feat: cleanup and prep for next features

xonecas2026-02-13 2455182af63260db474a51b09859c5393f626fb1 parent 6cd2ada

3 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.

docs/DESIGN.md+130−205
@@ -1,266 +1,191 @@
11 # Symb (pronounced "sim")
22
3-A code/pair programming tool for developers who use agents in their main workflows. Symbiotic pairing between developer and LLM. The developer has an agentic UI that provides the interface to the LLM, and a set of tools the LLM can use to cooperate in coding/development with the user.
3+Symbiotic pairing between developer and LLM. TUI with an agentic conversation
4+on one side, code editor on the other. Fast, low memory, not a distraction.
45
5-## Vision
6+## What It Is Now
67
7-Simple UI. Being a TUI, the goal is to be fast, have low memory usage, and avoid being a distraction to the code/content. Simple unicode border around the window. Agentic conversation on one side, code editor on the other. Matrix green for color (used rarely, only when a color is absolutely needed).
8+### TUI (BubbleTea, ELM architecture)
89
9-A TUI from the future. We want feature parity with a GUI editor: mouse selection, clicking, etc.
10+Split-pane layout: editor left, conversation + input right. Draggable divider.
11+Click-to-focus between panes. Alt-screen, mouse cell-motion mode with 15ms
12+throttle on wheel/motion events.
1013
11-## Minimum Viable Product
12-
13-### Agentic UI
14-
15-- Support for clicking file references/diffs/snippets to open in Editor side.
16-- Optional Human-in-the-middle LLM tool call loop (with configurable permissions in global config)
17-- Auto Context, LLM is aware of file/project in question probably via tree-sitter?
18-- AGENTS.md support
19-
20-### Code/Diff Viewer (currently editor in read-only) UI
21-
22-- Line numbers, syntax highlighting
23-- LSP support
24-- Git integration (show file git status)
25-- Simple editting support, no advanced usages or keybinds. ** DONE BUT UNUSED FOR NOW, KEEP!! **
26-- Code browsing mouse features: click to go to definition/references. Search for word under cursor.
27-
28-### LLM Tools
29-
30-- Run in sandboxed version of the working directory to allow multiple agents working on the same file. Use git to merge sandboxed changes to real repo.
31-- Grep, Read, Write: optimized for code changes (LSP and linting checks after each edit). These appear in agentic UI as a diff message (not actual diff). Clicking on it takes us to that edit in the editor tab.
32-- Undo: Either perform an intelligent step back or use git to reset.
33-- Subagent tool: Performs a single task based on prompt.
34-- Mutation tools create a new branch worktress for the sandboxed environment. Perform the mutation. Once the user approves the mutation or tells the agent to merge, a git merge happens.
35-
36-### Features
37-
38-#### File Search: `<CTRL> + <f>`
39-
40-Search files by filename or content (fuzzy matches, fast)
41-
42-- Opens a modal/overlay with a search box and a dynamic list of matches.
43-- Searching filters the list.
44-- Up/Down arrows select item in the list.
45-- Enter opens the currently matched/selected file.
46-- Includes the currently "opened" buffers in search at the top of the matches.
47-- We should find a library that does this for us, before trying to code our own fuzzy
48-
49-#### Git Diff: `<CTRL> + <g>`
50-
51-Open git diff in the editor.
52-
53-#### LLM Interaction
54-
55-- Selected text + `<CTRL> + <k>`: Send selected text to the LLM input.
56-- `<CTRL> + <k>`: Prompt at cursor, focus the input with information for the LLM about the user's cursor.
57-
58-### Theme
59-
60-Clean, straight corners, _suit and tie_-like. Use dark grayscale for almost everything on a clean black background. Matrix green used lightly (animated activity spinner). Single clean unicode lines (like in the drawing bellow)
61-
62-## Mockup
63-
64-```text
65-╭─────────────────────────────────────┬────────────────────────────────────╮
66-│ 102 │ ● Symb │ // Flexible height.
67-│ 103 pub fn wake_up(neo: &User) { │ │ // Panes split 50% each
68-│ 104 // TODO: Implement signal │ ┌─ Assistant ────────────────────┐ │
69-│ 105 let signal = Signal::new();│ │ I see you're working on the │ │ // Assistant message
70-│ 106 │ │ wake_up function. │ │ // - Messages have their embedded code highlighter for code blocks, diffs etc.
71-│ 107 if neo.is_ready() { │ │ │ │ // - Shows short reasoning (toggleable in the options)
72-│ 108 neo.disconnect(); │ │ Would you like me to generate │ │ // - Shows tool calls/tool response is stylized human readable format.
73-│ 109 } else { │ │ the Signal implementation? │ │
74-│ 110 neo.sleep(); │ │ │ │ // Conversation log takes a lot of inspiration from Opencode.
75-│ 111 } │ │ [Generate] [Diff] [Ignore] │ │
76-│ 112 } │ └────────────────────────────────┘ │
77-│ 113 │ │
78-│ 114 │ ┌─ Input ────────────────────────┐ │
79-│ 115 │ │ /bash cargo check │ │ // Input box, user can cycle history with arrows *up/down*
80-│ 116 │ └────────────────────────────────┘ │ // - Input supports commands /Read /Grep /Write (call the same tools as the LLM sees)
81-├─────────────────────────────────────┴────────────────────────────────────┤
82-│ master* │ src/matrix/core.rs[+] ⣽ │ // Git branch, current file if any. ending with an
83-╰──────────────────────────────────────────────────────────────────────────╯ // animated icon: fast animation when LLM is thinking, slow when idle.
84-```
85-
86-### Agent message:
87-
88-```text
89-
90-[reasoning ...]
91-
92-→ Read(file, args)
93-← Write(file, args)
94-
95-[agent reply...]
96-
97-XXs 00:00 ───────────────────────── // DarkGray color, timestamp and duration of the LLM response: 10s 19:57
9814 ```
99-
100-### User Message
101-
15+╭──────────────────────┬───────────────────────╮
16+│ editor (read-only) │ conversation log │
17+│ - chroma highlighting│ - reasoning (muted) │
18+│ - line numbers │ - → tool calls │
19+│ - soft line wrap │ - ← tool results │
20+│ - mouse scroll/select│ - content │
21+│ - click, drag, copy │ - scroll, select, copy│
22+│ ├───────────────────────┤
23+│ │ input (editable) │
24+├──────────────────────┴───────────────────────┤
25+│ status bar with spinner │
26+╰──────────────────────────────────────────────╯
10227 ```
103-[User message ...]
10428
105-XXs 00:00 ───────────────────────── // DarkGray color
29+Editor component (`internal/tui/editor`): full editing capability (insert,
30+delete, paste, tab indent) gated behind `ReadOnly` flag. Left pane is read-only
31+viewer. Input pane uses same component with `ReadOnly=false`.
10632
107-```
33+### LLM Loop (`internal/llm`)
10834
109-### Post-MVP
35+Synchronous multi-turn. Up to 20 tool rounds per turn. Calls
36+`Provider.ChatWithTools()` — request/response, not streaming. Emits messages
37+via `OnMessage` callback to TUI.
11038
111-- Send input text to editor and send editor text to input/llm via keybinds
112-- Send cursor position/filename to llm via keybind
113-- Send selected text to llm via keybind
39+Prompt system: model-specific base prompts (Claude, Gemini, Qwen, GPT).
40+`AGENTS.md` support: walks directory tree upward collecting all AGENTS.md files,
41+prepends to system prompt. Checks `~/.config/symb/AGENTS.md` too.
11442
115-## Technology Stack
43+### Providers (`internal/provider`)
11644
117-### Architecture
45+- **Ollama** — local, OpenAI-compatible `/v1` endpoint. Extracts reasoning from
46+ `reasoning`/`reasoning_content` fields.
47+- **OpenCode** — remote, API key auth. Model-specific endpoint routing.
48+- Both have retry logic (3 retries, 429/5xx handling).
49+- `Stream()` method exists on both but is needed for streaming responses feature.
11850
119-- True ELM architecture (no exceptions ever).
120- - Strict project structure with separation of concern by internal modules.
121-- Go (see https://github.com/tj/go-tea) For ELM architecture in TUI app (documentation).
51+### MCP (`internal/mcp`)
12252
123-### Core Libraries
53+Proxy merges local tool handlers with optional upstream MCP server (HTTP
54+Streamable-HTTP transport, SSE support, session tracking). Retry with
55+Retry-After parsing.
12456
125-- **BubbleTea**:
126- - Base library for TUI, use their bubbles, and all of the ecosystem.
127- - Golden files based testing for the TUI.
128- - https://github.com/charmbracelet/bubbletea Root BubbleTea.
129-- **LLM Providers**: Ollama local + Opencode Zen.
130-- **Config driven**: `./config.toml`.
57+### Tools (`internal/mcp_tools`)
13158
132-### Dependencies
59+3 tools registered:
13360
134-#### LSP Client
61+- **Open** — reads file, returns hashline-tagged content (`linenum:hash|content`),
62+ sends to TUI editor. Path traversal prevention.
63+- **Edit** — hash-anchored file editing (replace, insert, delete, create).
64+ Validates hashes before modifying. Returns fresh hashes after edit. Enforces
65+ read-before-edit via `FileReadTracker`.
66+- **Grep** — file/content search. Regex, gitignore-aware, case sensitivity,
67+ max results.
13568
136-- Candidate: `github.com/sourcegraph/go-lsp` (Battle-tested by Sourcegraph).
137-- Alternative: `go.lsp.dev/protocol` (Modern, modular).
69+### Supporting Packages
13870
139-#### Mouse Support
71+- `internal/hashline` — SHA-256 truncated to 2 hex chars per line. Anchor
72+ validation, range validation. 7 tests, 96.7% coverage.
73+- `internal/filesearch` — directory walker with `.gitignore` support, regex
74+ matching, binary detection, 10MB size limit.
75+- `internal/config` — TOML config, JSON credentials, env overrides.
14076
141-- Candidate: `github.com/lrstanley/bubblezone` (Wrapper for easier hit-testing/zoning).
77+### Dead Code
14278
143-#### Editor
79+- `internal/tui/textarea/` — 1636-line bubbles/textarea fork. Imported by nothing.
14480
145-- Official: `github.com/charmbracelet/bubbles/textarea` (Basic text input).
146-- Vim-like: `github.com/mieubrisse/vim-bubble` (Vim buffer emulation).
81+## Considered Features
14782
148-#### Syntax Highlighting
83+### Streaming Responses
14984
150-- Candidate: `github.com/alecthomas/chroma` (Standard Go syntax highlighter).
85+Stream LLM output token-by-token to the conversation pane. `Stream()` already
86+exists on providers. Needs: wire into LLM loop, incremental conversation
87+rendering, handle tool calls mid-stream.
15188
152-### References
89+### Basic keybind to toggle cursor from agent input <> editor
15390
154-- ZOEA NOVA `~/src/zoea-nova`: A past project with a lot of overlap, also focused on LLM agentic loop.
155-- Mysis `~/src/mysis`: Also a past project: raw CLI agentic tool for a dedicated agent (lots of overlap).
156-- Cursor IDE (Cursor has this UX, but it's slow, leaks memory and it's more distracting than most other editors).
157-- Opencode (TUI in `ink` does the same without the text editor, 75% feature overlap).
91+Choose a convenient keybind to toggle the active cursor.
92+Goes back and forth
93+Use vim's `CTRL+w` keybind for easy muscle memory?
15894
159-## Implementation Roadmap
95+### Clickable File References
16096
161-### MVP Phases
97+File paths in conversation (tool calls, content) become clickable. Clicking
98+opens the file in the editor pane at the referenced line.
99+- Don't show tool response bodies in conversation pane once the user can click to see. Show a max 5 line preview for the user to click to see more. User clicks, the content of the tool response is sent to the editor.
162100
163-#### Phase 1: Basic TUI with editor + agent pane (no LSP, no git sandbox)
101+### Web/Search Tools
164102
165-- File viewer with syntax highlighting
166-- Agent conversation with tool calls (Read/Write/Grep)
103+HTTP fetch cleans the html for less wasted tokens, preserving content.
104+Search APIs from Exa.ai. Give the agent access to documentation and external resources.
105+ - Re-use the existing `credentials.json` file for exa api key
106+ - Encourage LLMs to search before assuming in prompts
167107
168-#### Phase 2: Git integration
108+### File Search in agent input box
169109
170-- Show git status in editor
171-- Ctrl+g for diffs
172-- Simple diff preview before applying
173-- Agent commits to real repo (no sandbox yet)
110+Typing `@` shows a file search modal. Substiture `@` in the input with the selected pathname
111+File search modal:
112+ - Centered in the UI, 80% of legth and width of the main app window, resizable with the rest of the app.
113+ - Top row is the input for the file search query
114+ - Rest of the modal is the list of matches.
115+ - Results update after the user stops typing for a few hundred miliseconds.
116+ - Up/down arrow select from the search results. If focus is on input and user presses down arrow, it focus the list. If focus is on first result and user presses up arrow focus the input.
117+ - `Enter` on input selects the first match
118+ - `Enter` on result list row selected the selected row.
174119
175-#### Phase 3: LSP integration
120+### Copy/Selection Improvements
176121
177-- Start with diagnostics only
178-- Add go-to-definition later
122+Keyboard-driven selection (Shift+arrows). `Ctrl+Shift+C` to copy.
123+Currently mouse-only, and has bugs. Complete refactor of selection with the mouse to work in tandem with keyboard selection.
179124
180-#### Phase 4: Advanced features
125+### Editor-LLM link:
181126
182-- Sandboxed worktrees
183-- Sub-agents
184-- Context optimization with tree-sitter
127+LLM input (in the spirit of the app, symbiotic):
128+ - User types in agent input
129+ - with `@cursor` or `@selected` -- Works with `@` filesearh modal.
130+ - creates a reference with hashes of where the user's cursor or selection is in the filesystem/file
185131
186-### The Main Challenge: State Management
132+### LSP Integration
187133
188-You have three asynchronous "gods" to serve:
134+- Start with diagnostics (show errors/warnings in editor gutter).
135+- Go-to-definition on click. -- Needs more design before work starts
136+- Find references on click. -- Needs more design before work starts
137+- Candidates: `go.lsp.dev/protocol` or `github.com/sourcegraph/go-lsp`.
189138
190-1. User Input (Keyboard/Mouse) -> Instant.
191-2. LSP Server (Diagnostics/Completions) -> Fast (ms).
192-3. LLM Agent (Thinking/Tools) -> Slow (seconds).
139+### Tree-Sitter Context
193140
194-BubbleTea's ELM architecture (Update() loop) is perfect for this if you keep the heavy lifting (LLM/LSP) in separate Go routines that send messages back to the main thread. If you block the main thread, the UI will freeze.
141+Parse project with tree-sitter for structural awareness. Feed relevant
142+symbols/scope to LLM as auto-context instead of whole files.
195143
196-Confidence Level: High for a prototype. The ecosystem is ready.
144+### Git Integration
197145
198-## TODO
146+- Show current branch + dirty status in status bar.
147+- git **read** tools for the LLM: diff, status
148+- Editor displays diffs with syntax hl
149+- git markers in the number column for editted files in the editor
150+- sandboxed git worktrees for agents edits.
151+- git **write** tools. (only after worktrees are functional)
199152
200-### Bug Fixes
153+### Tool improvements:
201154
202-- Grep is not matching pathname:
155+Separate OpenForUser into Read and Show. Read sends the output to the llm, Show sends it to the editor after read.
203156
204- ```
205- The Grep tool was called with the following arguments:
157+- Open (or as it's called internally open for user): Change to Read, shows the read output to the llm. User can click to see if he wants, no automatic loading it to the editor.
158+- Show, new tool: Open and send to the editor.
206159
207- - `pattern`: `"mcp_tools.go"`
208- - `content_search`: `false` (filename search, not content grep)
209- - `case_sensitive`: `false` (default, case-insensitive)
210- - `max_results`: `100` (default)
160+### Human-in-the-Middle Tool Approval
211161
212- This means the tool was searching for files named
213- `mcp_tools.go` (or similar, due to fuzzy matching) in the
214- current directory and tracked paths (while respecting
215- `.gitignore`). Let me know if you'd like to tweak these
216- parameters!
217- ```
162+Pause before executing tool calls. Show tool name + args in a dialog. User
163+approves/rejects. Configurable per-tool permissions in `config.toml` (allow,
164+ask, deny). Some tools (Read/Grep) default allow, mutations (Edit) default ask.
218165
219-### UI Enhancements
166+### Shell Execution Tool
220167
221-- Show tool call arguments expanded:
222- ```
223- Grep(pattern="...", ...)
224- ```
225-- truncate tool reposnses. (time for verbose?)
226-- Make file references clickable in coversation (including tool calls output.)
227-- Copy text selection to clipboard (shift + arrows) then (ctrl + shift + c)
228-- streamed assistant response
229-- Fun: Show icon in unicode and a highlight color clock centered in the right panel when there are no messages.
168+Run commands in sandbox (container isolation or restricted shell). Command
169+whitelisting. Output streaming to conversation.
230170
231-### Features
232171
233-- websearch tool (exa tools?)
234-- file searching and opening, buffer switching. do I even want this, just make llm tools and ask it.
172+### Sub-Agent Tool
235173
236-## Future Enhancements
174+Spawn a child LLM turn scoped to a single task. Useful for parallel work
175+or decomposing complex operations.
237176
238-### Planned Features
177+### Parallel Tool Execution
239178
240-1. **Write Tools**: File modification with user approval
241- - `Edit` - Apply diffs to files
242- - `Create` - Create new files
243- - `Delete` - Remove files (with confirmation)
179+Execute multiple independent tool calls concurrently within a single LLM
180+turn. Needs careful coordination with FileReadTracker and TUI updates.
244181
245-2. **Shell Execution Tool**: Run commands with sandboxing
246- - Container isolation (Docker/Podman)
247- - Command whitelisting
248- - Output streaming
182+### UI Polish
249183
250-3. **Web Tools**: HTTP requests and web scraping
251- - `Fetch` - HTTP GET/POST
252- - `Scrape` - Extract data from HTML
184+- Show tool call arguments expanded: `Grep(pattern="...", ...)`, for all tools.
185+- Empty-state decoration in conversation pane.
253186
254-4. **LSP Integration**: Language server protocol
255- - `GoToDefinition` - Jump to symbol definition
256- - `FindReferences` - Find all references
257- - `Rename` - Refactor symbol names
187+### Tests
258188
259-### Research Areas
189+29 tests, all passing. Coverage: hashline 96.7%, filesearch 76%,
190+mcp_tools 43.2%, tui/editor 42.1%, tui 41.9%.
260191
261-- **Parallel tool execution**: LLM calls multiple tools simultaneously
262-- **Tool chaining**: Compose tools into workflows
263-- **Streaming results**: Show tool output in real-time
264-- **Permission system**: User approvals for sensitive operations
265-- **Audit logging**: Track all tool executions
266-- **Tool marketplace**: Discover and install community tools
docs/TUI_TESTING.md+0−853
@@ -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.
internal/tui/textarea/textarea.go+0−1635
Cut short: this commit's diff is over 1000 lines.