xonecas.io
62159
Sy

symb / commit 1044169

chore: code health and cleanup

xonecas2026-02-17 1044169694d321450e0484a4174d79d42d3397d0 parent 3fa05c2

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

TODO.md+5−58
@@ -1,68 +1,15 @@
1-- [ ] Encourage more subagent usage:
1+- [ ] Slow? or is it just some models? need numbers to compare. Turn times are ridiculous longest one was 27minutes with zen codex.
22
3-Update the prompts so the main agent is more of an orchestrator and the subagents do code searching/editting/commands etc.
4-This makes the most of subagents for context control.
5-Teach conflict free workflows for subagents
6-Trim subagent system prompt, align it with the new encouragement, perform the task from the main agent.
7-
8-After the changes above and some testing:
9-speciallize subagent_prompt.md into separate internal agent types: Grepper, Editor, Reviewer, Tasker, Webfinder.
10-update subagent to support an optional type that uses these specialized subagent prompts, defaults to Tasker for non-specific tasks.
11-
12-- [ ] LLM needs to improve todo usage!
3+- [ ] Investigate reasoning messages missing from opencode provider but working with ollama. (Check if any opencode model shows reasoning).
134
145 - [ ] Investigate empty messages with some models
156
16-- [ ] Refactor provider layer:
17-
18-Refactor opencode provider:
19- - cover all model options: https://opencode.ai/docs/zen). Fix current issues and misleading comments.
20- - ensure streaming + reasoning + tool call support is solid accross provider different formats.
21- - Add functionality to list available models and variants (xtra/medium/low/etc)
22-
23-Ollama changes:
24-
25- - ensure streaming + reasoning + tool call support is solid for ollama models.
26- - Add functionality to list available models and variants
27-
28-Update config usage:
29-
30-- Config only has upstream providers: ollama or opencode zen.
31-- Config set's api key to use from `credentials.json`:
32-
33-```
34-[provider.zen]
35-endpoint: [url]
36-api_key: [name] # optional
37-
38-[provider.ollama]
39-endpoint: [url]
40-```
41-
42-Add new modal, list available models, grouped by configured providers. When a model is selected it
43-becomes the active model, statusbar updates correctly, future messages go to new model.
44-
45-Benefits: User can now switch between providers/models freely. Multiple providers connected.
46-
47-Tackle in 3 phases:
48-
49-# Phase 1
50-1. Refactor opencode provider
51-2. Update config format
52-3. Modal implementation and model switching
53-
54-# Phase 2
55-Manual testing with user
56-
57-# Phase 3
58-Refactor ollama
7+- [ ] Conversation pane, no scroll to the bottom when the user is not at bottom.
598
609 - [ ] Cleanup codebase:
6110
6211 Aggregate common helpers in packages
6312 Breakdown visual tui components into their own tui files.
64-Separate modals into their own files (filesearch, keybinds, and base modal)
65-Find files larger than 750 lines write report for analysis
13+Audit for ELM compliance and fix outliers
6614
67-
68-- [ ] Investigate reasoning messages missing from opencode provider but working with ollama. (Check if any opencode model shows reasoning).
15+Finish with: Find files larger than 750 lines write report for analysis
docs/DESIGN.md+8−6
@@ -119,6 +119,7 @@ Needs an undo.
119119 <time elapsed> <timestamp> <toekns in current count>/<tokens out current count> (<total tokens in context at current count).
120120 <undo if most recent agent message>
121121 ```
122+
122123 **DONE**
123124
124125 - Read tool caps output at 500 lines / 20k chars; tells LLM to use line ranges for larger files.
@@ -180,9 +181,9 @@ Make a generic modal with inputbox + list combo for re-use. The use that to make
180181
181182 - Enable the same editting abilities as the agent input box.
182183 - <ctrl + s> Saves the file:
183- - File has changes -> send to llm to apply diff
184- - Need to consider if this makes sense, or if the LLM should also be aware of user changes,
185- and we should always send the diff for the LLM to apply?
184+- File has changes -> send to llm to apply diff
185+- Need to consider if this makes sense, or if the LLM should also be aware of user changes,
186+ and we should always send the diff for the LLM to apply?
186187
187188 ### Sub-Agent Tool
188189
@@ -194,6 +195,8 @@ or decomposing complex operations.
194195 - TODO: Custom agents from community configs
195196 - TODO: Worktress so they don't colide (needs to be an option, not all users use or like gitworktrees)
196197
198+Testing, cleaning up.
199+
197200 ## Features waiting implementation for current version:
198201
199202 ### Community configs support:
@@ -204,7 +207,7 @@ or decomposing complex operations.
204207
205208 ### Agent input interactivity:
206209
207-Use a special key `@` to spawn an autocomplete. This can match files, skills, commands or subagents.
210+Use a special key `@` to spawn an autocomplete. This can match files, skills, commands or subagents.
208211 When the user selects a match with `Enter` it replaces the @ with the selected item once the message is sent to the
209212 LLM
210213
@@ -212,8 +215,6 @@ LLM
212215
213216 Like git hooks, but after a specific tool call (lint after edit, or format when Y, etc).
214217
215-Testing current feature set
216-
217218 # TODO (after features)
218219
219220 2. Investigate if turn latency has improved
@@ -231,6 +232,7 @@ Testing current feature set
231232 Pause before executing tool calls. Show tool name + args in a dialog. User
232233 approves/rejects. Configurable per-tool permissions in `config.toml` (allow,
233234 ask, deny). Some tools (Read/Grep) default allow, mutations (Edit) default ask.
235+
234236 ### Parallel Tool Execution
235237
236238 Execute multiple independent tool calls concurrently within a single LLM
internal/mcptools/edit.go+11−1
@@ -69,6 +69,7 @@ type EditHandler struct {
6969 lspManager *lsp.Manager
7070 tsIndex *treesitter.Index
7171 deltaTracker *delta.Tracker
72+ rootDir string
7273 }
7374
7475 // NewEditHandler creates a handler for the Edit tool.
@@ -79,6 +80,9 @@ func NewEditHandler(tracker *FileReadTracker, lspManager *lsp.Manager, dt *delta
7980 // SetTSIndex sets the tree-sitter index for incremental updates on edit.
8081 func (h *EditHandler) SetTSIndex(idx *treesitter.Index) { h.tsIndex = idx }
8182
83+// SetRootDir overrides the base directory for path validation.
84+func (h *EditHandler) SetRootDir(root string) { h.rootDir = root }
85+
8286 // Handle implements the mcp.ToolHandler interface.
8387 func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
8488 var args EditArgs
@@ -92,7 +96,13 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
9296 return toolError("operation is required (replace, insert, delete, or create)"), nil
9397 }
9498
95- absPath, err := validatePath(args.File)
99+ var absPath string
100+ var err error
101+ if h.rootDir != "" {
102+ absPath, err = validatePathWithRoot(args.File, h.rootDir)
103+ } else {
104+ absPath, err = validatePath(args.File)
105+ }
96106 if err != nil {
97107 return toolError("%v", err), nil
98108 }
internal/mcptools/edit_test.go+1−5
@@ -27,12 +27,8 @@ func setupTestFile(t *testing.T) (string, string) {
2727 func newTrackedHandler(t *testing.T, dir string) *EditHandler {
2828 t.Helper()
2929 tracker := NewFileReadTracker()
30- oldDir, _ := os.Getwd()
31- if err := os.Chdir(dir); err != nil {
32- t.Fatal(err)
33- }
34- t.Cleanup(func() { os.Chdir(oldDir) })
3530 h := NewEditHandler(tracker, nil, nil)
31+ h.SetRootDir(dir)
3632 return h
3733 }
3834
internal/mcptools/helpers.go+57−0
@@ -0,0 +1,57 @@
1+package mcptools
2+
3+import (
4+ "fmt"
5+ "os"
6+ "path/filepath"
7+ "strings"
8+
9+ "github.com/xonecas/symb/internal/mcp"
10+)
11+
12+// validatePath resolves a file path, ensuring it's within the working directory.
13+func validatePath(file string) (string, error) {
14+ workingDir, err := os.Getwd()
15+ if err != nil {
16+ return "", fmt.Errorf("failed to get working directory: %w", err)
17+ }
18+ return validatePathWithRoot(file, workingDir)
19+}
20+
21+func validatePathWithRoot(file, root string) (string, error) {
22+ rootAbs, err := filepath.Abs(root)
23+ if err != nil {
24+ return "", fmt.Errorf("invalid root path: %w", err)
25+ }
26+ var absPath string
27+ if filepath.IsAbs(file) {
28+ absPath = file
29+ } else {
30+ absPath = filepath.Join(rootAbs, file)
31+ }
32+ absPath, err = filepath.Abs(absPath)
33+ if err != nil {
34+ return "", fmt.Errorf("invalid file path: %w", err)
35+ }
36+ relPath, err := filepath.Rel(rootAbs, absPath)
37+ if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
38+ return "", fmt.Errorf("access denied: path outside working directory")
39+ }
40+ return absPath, nil
41+}
42+
43+// toolError returns an error ToolResult.
44+func toolError(format string, args ...interface{}) *mcp.ToolResult {
45+ return &mcp.ToolResult{
46+ Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf(format, args...)}},
47+ IsError: true,
48+ }
49+}
50+
51+// toolText returns a text ToolResult.
52+func toolText(text string) *mcp.ToolResult {
53+ return &mcp.ToolResult{
54+ Content: []mcp.ContentBlock{{Type: "text", Text: text}},
55+ IsError: false,
56+ }
57+}
internal/mcptools/open.go+0−18
@@ -5,7 +5,6 @@ import (
55 "encoding/json"
66 "fmt"
77 "os"
8- "path/filepath"
98 "strings"
109
1110 "github.com/xonecas/symb/internal/hashline"
@@ -131,23 +130,6 @@ func (h *ReadHandler) Handle(_ context.Context, arguments json.RawMessage) (*mcp
131130 }, nil
132131 }
133132
134-// validatePath resolves a file path, ensuring it's within the working directory.
135-func validatePath(file string) (string, error) {
136- absPath, err := filepath.Abs(file)
137- if err != nil {
138- return "", fmt.Errorf("invalid file path: %w", err)
139- }
140- workingDir, err := os.Getwd()
141- if err != nil {
142- return "", fmt.Errorf("failed to get working directory: %w", err)
143- }
144- relPath, err := filepath.Rel(workingDir, absPath)
145- if err != nil || strings.HasPrefix(relPath, "..") || filepath.IsAbs(relPath) {
146- return "", fmt.Errorf("access denied: path outside working directory")
147- }
148- return absPath, nil
149-}
150-
151133 // extractRange returns the selected content and start line number for a line range.
152134 func extractRange(lines []string, full string, start, end int) (string, int, error) {
153135 if start <= 0 && end <= 0 {
internal/mcptools/web.go+0−16
@@ -358,19 +358,3 @@ func truncate(s string, maxChars int) string {
358358 }
359359 return string(runes[:maxChars]) + "\n\n[Truncated]"
360360 }
361-
362-// toolError returns an error ToolResult.
363-func toolError(format string, args ...interface{}) *mcp.ToolResult {
364- return &mcp.ToolResult{
365- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf(format, args...)}},
366- IsError: true,
367- }
368-}
369-
370-// toolText returns a text ToolResult.
371-func toolText(text string) *mcp.ToolResult {
372- return &mcp.ToolResult{
373- Content: []mcp.ContentBlock{{Type: "text", Text: text}},
374- IsError: false,
375- }
376-}
internal/treesitter/index_test.go+0−33
@@ -1,33 +0,0 @@
1-package treesitter
2-
3-import (
4- "os"
5- "testing"
6-)
7-
8-func TestIndexBuild(t *testing.T) {
9- cwd, err := os.Getwd()
10- if err != nil {
11- t.Fatal(err)
12- }
13- // Walk up to project root (internal/treesitter -> project root)
14- root := cwd + "/../.."
15-
16- idx := NewIndex(root)
17- if err := idx.Build(); err != nil {
18- t.Fatalf("Build: %v", err)
19- }
20-
21- files := idx.Files()
22- if len(files) == 0 {
23- t.Fatal("no files indexed")
24- }
25- t.Logf("Indexed %d files", len(files))
26-
27- snap := idx.Snapshot()
28- outline := FormatOutline(snap)
29- if outline == "" {
30- t.Fatal("empty outline")
31- }
32- t.Logf("Outline (%d bytes):\n%s", len(outline), outline)
33-}
internal/tui/editor/editor_test.go+0−3
@@ -1,7 +1,6 @@
11 package editor
22
33 import (
4- "fmt"
54 "strings"
65 "testing"
76
@@ -32,7 +31,6 @@ func TestLineWidthWithTabs(t *testing.T) {
3231 if w != 50 {
3332 t.Errorf("line %d: width=%d (want 50)", i, w)
3433 }
35- fmt.Printf("line %d: width=%d\n", i, w)
3634 }
3735 }
3836
@@ -126,6 +124,5 @@ func TestExpandTabs(t *testing.T) {
126124 if w != tc.want {
127125 t.Errorf("expandTabs(%q) width=%d, want %d (got %q)", tc.in, w, tc.want, got)
128126 }
129- fmt.Printf("expandTabs(%q) -> %q (width %d)\n", tc.in, got, w)
130127 }
131128 }
internal/tui/gitdiff_test.go+0−188
@@ -1,188 +0,0 @@
1-package tui
2-
3-import (
4- "context"
5- "os"
6- "os/exec"
7- "path/filepath"
8- "testing"
9-
10- "github.com/xonecas/symb/internal/tui/editor"
11-)
12-
13-// setupGitRepo creates a temp dir with an initialised git repo and returns
14-// the path along with a cleanup func that restores the original working dir.
15-func setupGitRepo(t *testing.T) (string, func()) {
16- t.Helper()
17-
18- dir := t.TempDir()
19- origDir, _ := os.Getwd()
20-
21- if err := os.Chdir(dir); err != nil {
22- t.Fatalf("chdir: %v", err)
23- }
24-
25- // Initialise a git repo with a first commit so HEAD exists.
26- for _, cmd := range [][]string{
27- {"git", "init"},
28- {"git", "config", "user.email", "test@test.com"},
29- {"git", "config", "user.name", "Test"},
30- } {
31- c := exec.Command(cmd[0], cmd[1:]...)
32- c.Dir = dir
33- if out, err := c.CombinedOutput(); err != nil {
34- t.Fatalf("setup %v: %s – %v", cmd, out, err)
35- }
36- }
37-
38- // Create an initial commit so we have HEAD.
39- initial := filepath.Join(dir, "init.txt")
40- if err := os.WriteFile(initial, []byte("init\n"), 0644); err != nil {
41- t.Fatal(err)
42- }
43- for _, cmd := range [][]string{
44- {"git", "add", "."},
45- {"git", "commit", "-m", "initial"},
46- } {
47- c := exec.Command(cmd[0], cmd[1:]...)
48- c.Dir = dir
49- if out, err := c.CombinedOutput(); err != nil {
50- t.Fatalf("setup %v: %s – %v", cmd, out, err)
51- }
52- }
53-
54- return dir, func() {
55- if err := os.Chdir(origDir); err != nil {
56- t.Errorf("restore chdir: %v", err)
57- }
58- }
59-}
60-
61-// ---------------------------------------------------------------------------
62-// ParseDiffMarkers tests
63-// ---------------------------------------------------------------------------
64-
65-func TestParseDiffMarkersEmpty(t *testing.T) {
66- m := ParseDiffMarkers("")
67- if m != nil {
68- t.Errorf("expected nil for empty diff, got %v", m)
69- }
70-}
71-
72-func TestParseDiffMarkersAdd(t *testing.T) {
73- // Pure addition: 3 new lines starting at line 5.
74- diff := `diff --git a/file.go b/file.go
75---- a/file.go
76-+++ b/file.go
77-@@ -4,0 +5,3 @@ func foo() {
78-+line1
79-+line2
80-+line3
81-`
82- m := ParseDiffMarkers(diff)
83- if len(m) != 3 {
84- t.Fatalf("expected 3 markers, got %d: %v", len(m), m)
85- }
86- for _, row := range []int{4, 5, 6} { // 0-indexed
87- if m[row] != editor.GutterAdd {
88- t.Errorf("row %d: expected GutterAdd, got %v", row, m[row])
89- }
90- }
91-}
92-
93-func TestParseDiffMarkersDelete(t *testing.T) {
94- // Pure deletion: 2 old lines removed, new file continues at line 10.
95- diff := `diff --git a/file.go b/file.go
96---- a/file.go
97-+++ b/file.go
98-@@ -8,2 +10,0 @@ func bar() {
99--old1
100--old2
101-`
102- m := ParseDiffMarkers(diff)
103- if len(m) != 1 {
104- t.Fatalf("expected 1 marker, got %d: %v", len(m), m)
105- }
106- // newStart=10, newCount=0 → mark row 10-1=9 (0-indexed)
107- if m[9] != editor.GutterDelete {
108- t.Errorf("row 9: expected GutterDelete, got %v", m[9])
109- }
110-}
111-
112-func TestParseDiffMarkersChange(t *testing.T) {
113- // Modification: 2 old lines replaced by 3 new lines starting at line 7.
114- diff := `diff --git a/file.go b/file.go
115---- a/file.go
116-+++ b/file.go
117-@@ -7,2 +7,3 @@ func baz() {
118--old
119--old2
120-+new1
121-+new2
122-+new3
123-`
124- m := ParseDiffMarkers(diff)
125- if len(m) != 3 {
126- t.Fatalf("expected 3 markers, got %d: %v", len(m), m)
127- }
128- for _, row := range []int{6, 7, 8} { // 0-indexed
129- if m[row] != editor.GutterChange {
130- t.Errorf("row %d: expected GutterChange, got %v", row, m[row])
131- }
132- }
133-}
134-
135-func TestParseDiffMarkersMultipleHunks(t *testing.T) {
136- diff := `diff --git a/file.go b/file.go
137---- a/file.go
138-+++ b/file.go
139-@@ -1,0 +2,1 @@
140-+added
141-@@ -10,1 +12,1 @@
142--old
143-+changed
144-`
145- m := ParseDiffMarkers(diff)
146- if len(m) != 2 {
147- t.Fatalf("expected 2 markers, got %d: %v", len(m), m)
148- }
149- if m[1] != editor.GutterAdd { // line 2, 0-indexed = 1
150- t.Errorf("row 1: expected GutterAdd, got %v", m[1])
151- }
152- if m[11] != editor.GutterChange { // line 12, 0-indexed = 11
153- t.Errorf("row 11: expected GutterChange, got %v", m[11])
154- }
155-}
156-
157-func TestParseDiffMarkersSingleLineNoComma(t *testing.T) {
158- // When count is 1, git omits the comma: @@ -5 +5 @@
159- diff := `@@ -5 +5 @@
160--old
161-+new
162-`
163- m := ParseDiffMarkers(diff)
164- if len(m) != 1 {
165- t.Fatalf("expected 1 marker, got %d: %v", len(m), m)
166- }
167- if m[4] != editor.GutterChange { // line 5, 0-indexed = 4
168- t.Errorf("row 4: expected GutterChange, got %v", m[4])
169- }
170-}
171-
172-func TestGitFileMarkersIntegration(t *testing.T) {
173- dir, cleanup := setupGitRepo(t)
174- defer cleanup()
175-
176- // Modify the tracked file.
177- if err := os.WriteFile(filepath.Join(dir, "init.txt"), []byte("changed\n"), 0644); err != nil {
178- t.Fatal(err)
179- }
180-
181- m := GitFileMarkers(context.Background(), "init.txt")
182- if m == nil {
183- t.Fatal("expected markers for modified file, got nil")
184- }
185- if _, ok := m[0]; !ok {
186- t.Errorf("expected marker on row 0, got %v", m)
187- }
188-}
internal/tui/messages.go+196−117
@@ -1,6 +1,7 @@
11 package tui
22
33 import (
4+ "context"
45 "encoding/json"
56 "fmt"
67 "os"
@@ -58,6 +59,15 @@ type storeBatch struct {
5859 type llmHistoryMsg struct{ msg provider.Message }
5960 type llmErrorMsg struct{ err error }
6061
62+type userMsgSavedMsg struct {
63+ convIdx int
64+ dbMsgID int64
65+ userMsg provider.Message
66+ err error
67+}
68+
69+type undoResultMsg struct{ err error }
70+
6171 // Streaming delta messages
6272 type llmContentDeltaMsg struct{ content string }
6373 type llmReasoningDeltaMsg struct{ content string }
@@ -179,102 +189,168 @@ func (m Model) waitForLLMUpdate() tea.Cmd {
179189 }
180190 }
181191
182-func (m Model) processLLM() tea.Cmd {
183- prov := m.provider
184- proxy := m.mcpProxy
192+func (m Model) processLLMWithExtra(extra []provider.Message) tea.Cmd {
193+ deps := m.llmTurnDeps()
194+ return func() tea.Msg {
195+ go m.runLLMTurn(deps, extra)
196+ return nil
197+ }
198+}
199+
200+type llmTurnDeps struct {
201+ provider provider.Provider
202+ proxy *mcp.Proxy
203+ tools []mcp.Tool
204+ store *store.Cache
205+ sessionID string
206+ ch chan tea.Msg
207+ ctx context.Context
208+ dt *delta.Tracker
209+ pad llm.ScratchpadReader
210+ systemMsg *provider.Message
211+}
212+
213+type usageTracker struct {
214+ turnIn int
215+ turnOut int
216+ contextIn int
217+}
218+
219+func (m Model) llmTurnDeps() llmTurnDeps {
185220 tools := make([]mcp.Tool, len(m.mcpTools))
186221 copy(tools, m.mcpTools)
187- db := m.store
188- sid := m.sessionID
189- ch := m.updateChan
190- ctx := m.turnCtx
191- dt := m.deltaTracker
192- pad := m.scratchpad
222+ return llmTurnDeps{
223+ provider: m.provider,
224+ proxy: m.mcpProxy,
225+ tools: tools,
226+ store: m.store,
227+ sessionID: m.sessionID,
228+ ch: m.updateChan,
229+ ctx: m.turnCtx,
230+ dt: m.deltaTracker,
231+ pad: m.scratchpad,
232+ systemMsg: m.initialSystemMsg,
233+ }
234+}
193235
194- return func() tea.Msg {
195- go func() {
196- // Load history from DB — the single source of truth.
197- var history []provider.Message
198- if db != nil {
199- stored, err := db.LoadMessages(sid)
200- if err != nil {
201- ch <- llmErrorMsg{err: fmt.Errorf("load history: %w", err)}
202- return
203- }
204- history = store.ToProviderMessages(stored)
205- }
206- // Snapshot the project directory before the turn for undo.
207- // Capture cwd once so both pre/post snapshots use the same root.
208- var preSnap map[string]delta.FileSnapshot
209- var snapRoot string
210- if dt != nil && dt.TurnID() > 0 {
211- if cwd, err := os.Getwd(); err == nil {
212- snapRoot = cwd
213- preSnap = delta.SnapshotDir(snapRoot)
214- }
215- }
236+func (m Model) runLLMTurn(deps llmTurnDeps, extra []provider.Message) {
237+ history, err := loadHistory(deps.store, deps.sessionID)
238+ if err != nil {
239+ deps.ch <- llmErrorMsg{err: fmt.Errorf("load history: %w", err)}
240+ return
241+ }
242+ history = ensureSystemMessage(history, deps.systemMsg)
243+ if len(extra) > 0 {
244+ history = append(history, extra...)
245+ }
216246
217- start := time.Now()
218- var turnIn, turnOut, contextIn int
219- err := llm.ProcessTurn(ctx, llm.ProcessTurnOptions{
220- Provider: prov,
221- Proxy: proxy,
222- Tools: tools,
223- History: history,
224- Scratchpad: pad,
225- // Uses the default from ProcessTurn.
226- OnDelta: func(evt provider.StreamEvent) {
227- switch evt.Type {
228- case provider.EventContentDelta:
229- ch <- llmContentDeltaMsg{content: evt.Content}
230- case provider.EventReasoningDelta:
231- ch <- llmReasoningDeltaMsg{content: evt.Content}
232- }
233- },
234- OnUsage: func(inputTokens, outputTokens int) {
235- turnIn += inputTokens
236- turnOut += outputTokens
237- contextIn = inputTokens
238- ch <- llmUsageMsg{inputTokens: inputTokens, outputTokens: outputTokens}
239- },
240- OnMessage: func(msg provider.Message) {
241- ch <- llmHistoryMsg{msg: msg}
242- switch msg.Role {
243- case roleAssistant:
244- ch <- llmAssistantMsg{
245- reasoning: msg.Reasoning,
246- content: msg.Content,
247- toolCalls: msg.ToolCalls,
248- }
249- case "tool":
250- ch <- llmToolResultMsg{
251- toolCallID: msg.ToolCallID,
252- content: msg.Content,
253- }
254- }
255- },
256- })
257-
258- // Post-turn snapshot: diff against pre to record deltas for undo.
259- // Skip on cancellation — partial work has no turnBoundary.
260- if preSnap != nil && err == nil {
261- postSnap := delta.SnapshotDir(snapRoot)
262- delta.RecordDeltas(dt, snapRoot, preSnap, postSnap)
263- }
247+ preSnap, snapRoot := snapshotBeforeTurn(deps.dt)
248+
249+ start := time.Now()
250+ usage := &usageTracker{}
251+ err = llm.ProcessTurn(deps.ctx, llm.ProcessTurnOptions{
252+ Provider: deps.provider,
253+ Proxy: deps.proxy,
254+ Tools: deps.tools,
255+ History: history,
256+ Scratchpad: deps.pad,
257+ OnDelta: func(evt provider.StreamEvent) {
258+ dispatchStreamEvent(deps.ch, evt)
259+ },
260+ OnUsage: usage.onUsage(deps.ch),
261+ OnMessage: func(msg provider.Message) {
262+ dispatchHistoryMessage(deps.ch, msg)
263+ },
264+ })
264265
265- if err != nil {
266- ch <- llmErrorMsg{err: err}
267- return
268- }
269- ch <- llmDoneMsg{
270- duration: time.Since(start),
271- timestamp: start.Format("15:04"),
272- inputTokens: turnIn,
273- outputTokens: turnOut,
274- contextTokens: contextIn,
275- }
276- }()
277- return nil
266+ recordTurnDeltas(deps.dt, snapRoot, preSnap, err)
267+ if err != nil {
268+ deps.ch <- llmErrorMsg{err: err}
269+ return
270+ }
271+ deps.ch <- llmDoneMsg{
272+ duration: time.Since(start),
273+ timestamp: start.Format("15:04"),
274+ inputTokens: usage.turnIn,
275+ outputTokens: usage.turnOut,
276+ contextTokens: usage.contextIn,
277+ }
278+}
279+
280+func loadHistory(db *store.Cache, sessionID string) ([]provider.Message, error) {
281+ if db == nil {
282+ return nil, nil
283+ }
284+ stored, err := db.LoadMessages(sessionID)
285+ if err != nil {
286+ return nil, err
287+ }
288+ return store.ToProviderMessages(stored), nil
289+}
290+
291+func ensureSystemMessage(history []provider.Message, systemMsg *provider.Message) []provider.Message {
292+ if systemMsg == nil {
293+ return history
294+ }
295+ for _, msg := range history {
296+ if msg.Role == "system" {
297+ return history
298+ }
299+ }
300+ return append([]provider.Message{*systemMsg}, history...)
301+}
302+
303+func snapshotBeforeTurn(dt *delta.Tracker) (map[string]delta.FileSnapshot, string) {
304+ if dt == nil || dt.TurnID() == 0 {
305+ return nil, ""
306+ }
307+ cwd, err := os.Getwd()
308+ if err != nil {
309+ return nil, ""
310+ }
311+ return delta.SnapshotDir(cwd), cwd
312+}
313+
314+func recordTurnDeltas(dt *delta.Tracker, snapRoot string, preSnap map[string]delta.FileSnapshot, err error) {
315+ if preSnap == nil || err != nil {
316+ return
317+ }
318+ postSnap := delta.SnapshotDir(snapRoot)
319+ delta.RecordDeltas(dt, snapRoot, preSnap, postSnap)
320+}
321+
322+func dispatchStreamEvent(ch chan tea.Msg, evt provider.StreamEvent) {
323+ switch evt.Type {
324+ case provider.EventContentDelta:
325+ ch <- llmContentDeltaMsg{content: evt.Content}
326+ case provider.EventReasoningDelta:
327+ ch <- llmReasoningDeltaMsg{content: evt.Content}
328+ }
329+}
330+
331+func dispatchHistoryMessage(ch chan tea.Msg, msg provider.Message) {
332+ ch <- llmHistoryMsg{msg: msg}
333+ switch msg.Role {
334+ case roleAssistant:
335+ ch <- llmAssistantMsg{
336+ reasoning: msg.Reasoning,
337+ content: msg.Content,
338+ toolCalls: msg.ToolCalls,
339+ }
340+ case "tool":
341+ ch <- llmToolResultMsg{
342+ toolCallID: msg.ToolCallID,
343+ content: msg.Content,
344+ }
345+ }
346+}
347+
348+func (u *usageTracker) onUsage(ch chan tea.Msg) func(int, int) {
349+ return func(inputTokens, outputTokens int) {
350+ u.turnIn += inputTokens
351+ u.turnOut += outputTokens
352+ u.contextIn = inputTokens
353+ ch <- llmUsageMsg{inputTokens: inputTokens, outputTokens: outputTokens}
278354 }
279355 }
280356
@@ -301,44 +377,47 @@ func messageToStore(msg provider.Message) store.SessionMessage {
301377 }
302378 }
303379
304-// saveMessage persists a message to the session store (no-op if store is nil).
305-func (m *Model) saveMessage(msg provider.Message) {
306- if m.store == nil {
380+func (m *Model) saveMessages(msgs []provider.Message) {
381+ if m.store == nil || len(msgs) == 0 {
307382 return
308383 }
309- stored := []store.SessionMessage{messageToStore(msg)}
310- if m.storeQueue != nil {
311- select {
312- case m.storeQueue <- storeBatch{sessionID: m.sessionID, msgs: stored}:
313- return
314- default:
315- log.Warn().Msg("store queue full; falling back to sync save")
316- }
384+ stored := make([]store.SessionMessage, 0, len(msgs))
385+ for _, msg := range msgs {
386+ stored = append(stored, messageToStore(msg))
387+ }
388+ if enqueueStoreBatch(m.storeQueue, storeBatch{sessionID: m.sessionID, msgs: stored}) {
389+ return
317390 }
318391 if err := m.store.SaveMessages(m.sessionID, stored); err != nil {
319392 log.Warn().Err(err).Msg("failed to save message batch")
320393 }
321394 }
322395
323-func (m *Model) saveMessages(msgs []provider.Message) {
396+func (m Model) saveMessagesCmd(msgs []provider.Message) tea.Cmd {
324397 if m.store == nil || len(msgs) == 0 {
325- return
398+ return nil
326399 }
327- stored := make([]store.SessionMessage, 0, len(msgs))
328- for _, msg := range msgs {
329- stored = append(stored, messageToStore(msg))
400+ return func() tea.Msg {
401+ m.saveMessages(msgs)
402+ return nil
330403 }
331- if m.storeQueue != nil {
332- select {
333- case m.storeQueue <- storeBatch{sessionID: m.sessionID, msgs: stored}:
334- return
335- default:
336- log.Warn().Msg("store queue full; dropping message batch")
337- return
338- }
404+}
405+
406+func enqueueStoreBatch(queue chan storeBatch, batch storeBatch) (ok bool) {
407+ if queue == nil {
408+ return false
339409 }
340- if err := m.store.SaveMessages(m.sessionID, stored); err != nil {
341- log.Warn().Err(err).Msg("failed to save message batch")
410+ defer func() {
411+ if recover() != nil {
412+ ok = false
413+ }
414+ }()
415+ select {
416+ case queue <- batch:
417+ return true
418+ default:
419+ log.Warn().Msg("store queue full; dropping message batch")
420+ return false
342421 }
343422 }
344423
internal/tui/modal/modal.go+21−1
@@ -46,6 +46,11 @@ const (
4646 // debounceMsg is sent after the debounce timer fires.
4747 type debounceMsg struct{ seq int }
4848
49+type searchResultsMsg struct {
50+ seq int
51+ items []Item
52+}
53+
4954 // Model is a generic input+list modal.
5055 type Model struct {
5156 input []rune
@@ -94,7 +99,12 @@ func (m *Model) HandleMsg(msg tea.Msg) (Action, tea.Cmd) {
9499 return m.handleKey(msg)
95100 case debounceMsg:
96101 if msg.seq == m.seq {
97- m.items = m.searchFn(string(m.input))
102+ return nil, m.searchCmd(string(m.input), msg.seq)
103+ }
104+ return nil, nil
105+ case searchResultsMsg:
106+ if msg.seq == m.seq {
107+ m.items = msg.items
98108 m.selected = 0
99109 m.inList = false
100110 }
@@ -132,6 +142,16 @@ func (m *Model) handleKey(msg tea.KeyPressMsg) (Action, tea.Cmd) {
132142 return nil, nil
133143 }
134144
145+func (m *Model) searchCmd(query string, seq int) tea.Cmd {
146+ if m.searchFn == nil {
147+ return nil
148+ }
149+ return func() tea.Msg {
150+ items := m.searchFn(query)
151+ return searchResultsMsg{seq: seq, items: items}
152+ }
153+}
154+
135155 func (m *Model) handleEnter() (Action, tea.Cmd) {
136156 if len(m.items) == 0 {
137157 return nil, nil
internal/tui/tui.go+21−21
@@ -8,7 +8,6 @@ import (
88
99 tea "charm.land/bubbletea/v2"
1010 "charm.land/lipgloss/v2"
11- "github.com/rs/zerolog/log"
1211 "github.com/xonecas/symb/internal/constants"
1312 "github.com/xonecas/symb/internal/delta"
1413 "github.com/xonecas/symb/internal/filesearch"
@@ -208,10 +207,11 @@ type Model struct {
208207 turnCancel context.CancelFunc // cancels current LLM turn only (nil when idle)
209208
210209 // Session persistence
211- store *store.Cache
212- storeQueue chan storeBatch
213- storeQueueDone <-chan struct{}
214- sessionID string
210+ store *store.Cache
211+ storeQueue chan storeBatch
212+ storeQueueDone <-chan struct{}
213+ sessionID string
214+ initialSystemMsg *provider.Message
215215
216216 // Conversation
217217 convEntries []convEntry // Conversation entries (not wrapped)
@@ -259,8 +259,10 @@ type Model struct {
259259 convDragging bool
260260
261261 // Frame loop
262- streamDirty bool // New streaming content arrived since last rebuild
263- frameLines []string // Per-frame cache of wrapped conv lines (cleared each Update)
262+ streamDirty bool // New streaming content arrived since last rebuild
263+ frameLines []string // Per-frame cache of wrapped conv lines (cleared each Update)
264+ turnPending bool // True while awaiting user message persistence
265+ undoInFlight bool // True while undo side-effects are running
264266
265267 // Statusbar state
266268 providerConfigName string // TOML config key (e.g. "zen-pickle")
@@ -321,20 +323,13 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
321323 ctx, cancel := context.WithCancel(context.Background())
322324
323325 var entries []convEntry
326+ var initialSystemMsg *provider.Message
324327 if resumeHistory != nil {
325328 entries = historyConvEntries(resumeHistory, sty)
326329 } else {
327330 systemPrompt := llm.BuildSystemPrompt(modelID, idx)
328331 systemMsg := provider.Message{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}
329- if db != nil {
330- if storeQueue != nil {
331- storeQueue <- storeBatch{sessionID: sessionID, msgs: []store.SessionMessage{messageToStore(systemMsg)}}
332- } else {
333- if err := db.SaveMessages(sessionID, []store.SessionMessage{messageToStore(systemMsg)}); err != nil {
334- log.Warn().Err(err).Msg("failed to save system message")
335- }
336- }
337- }
332+ initialSystemMsg = &systemMsg
338333 }
339334
340335 return Model{
@@ -351,10 +346,11 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
351346 ctx: ctx,
352347 cancel: cancel,
353348
354- store: db,
355- storeQueue: storeQueue,
Cut short: this commit's diff is over 1000 lines.
internal/tui/update.go+59−873
Cut short: this commit's diff is over 1000 lines.
internal/tui/update_keypress.go+111−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/update_llm.go+501−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/update_modals.go+136−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/update_resize.go+29−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/update_status.go+32−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/update_undo.go+125−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/view.go+0−159
Cut short: this commit's diff is over 1000 lines.
internal/tui/view_editor.go+26−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/view_rightpane.go+71−0
Cut short: this commit's diff is over 1000 lines.
internal/tui/view_status.go+83−0
Cut short: this commit's diff is over 1000 lines.