xonecas.io
62159
Sy

symb / commit 6043083

feat: click on tool responses for full view in editor

xonecas2026-02-13 6043083a1c24219a271e8f4a3fd976126c0a2276 parent 00ff610

5 files changed

docs/DESIGN.md+7−16
@@ -32,9 +32,10 @@ viewer. Input pane uses same component with `ReadOnly=false`.
3232
3333 ### LLM Loop (`internal/llm`)
3434
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.
35+Streaming multi-turn. Up to 20 tool rounds per turn. Calls
36+`Provider.ChatStream()` — returns `<-chan StreamEvent`. Forwards deltas via
37+`OnDelta` callback for incremental TUI rendering, emits complete messages via
38+`OnMessage` callback.
3839
3940 Prompt system: model-specific base prompts (Claude, Gemini, Qwen, GPT).
4041 `AGENTS.md` support: walks directory tree upward collecting all AGENTS.md files,
@@ -45,8 +46,8 @@ prepends to system prompt. Checks `~/.config/symb/AGENTS.md` too.
4546 - **Ollama** — local, OpenAI-compatible `/v1` endpoint. Extracts reasoning from
4647 `reasoning`/`reasoning_content` fields.
4748 - **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.
49+- Both use SSE streaming with retry on initial connection (3 retries, 429/5xx).
50+- Single `ChatStream()` interface method replaces `Chat`/`ChatWithTools`/`Stream`.
5051
5152 ### MCP (`internal/mcp`)
5253
@@ -74,18 +75,8 @@ Retry-After parsing.
7475 matching, binary detection, 10MB size limit.
7576 - `internal/config` — TOML config, JSON credentials, env overrides.
7677
77-### Dead Code
78-
79-- `internal/tui/textarea/` — 1636-line bubbles/textarea fork. Imported by nothing.
80-
8178 ## Considered Features
8279
83-### Streaming Responses
84-
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.
88-
8980 ### Basic keybind to toggle cursor from agent input <> editor
9081
9182 Choose a convenient keybind to toggle the active cursor.
@@ -102,7 +93,6 @@ opens the file in the editor pane at the referenced line.
10293
10394 - Needs design work
10495
105-
10696 ### Web/Search Tools
10797
10898 HTTP fetch cleans the html for less wasted tokens, preserving content.
@@ -161,6 +151,7 @@ Separate OpenForUser into Read and Show. Read sends the output to the llm, Show
161151
162152 - 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.
163153 - Show, new tool: Open and send to the editor.
154+- All tools: don't auto update the editor (Show excluded).
164155
165156 ### Human-in-the-Middle Tool Approval
166157
internal/mcp_tools/edit.go+2−2
@@ -246,7 +246,7 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
246246 }
247247
248248 // Show updated file in TUI editor
249- language := detectLanguage(args.File)
249+ language := DetectLanguage(args.File)
250250 if h.program != nil {
251251 h.program.Send(OpenForUserMsg{
252252 Content: result,
@@ -281,7 +281,7 @@ func (h *EditHandler) handleCreate(absPath, displayPath string, op *CreateOp) (*
281281 }
282282
283283 // Show in TUI
284- language := detectLanguage(displayPath)
284+ language := DetectLanguage(displayPath)
285285 if h.program != nil {
286286 h.program.Send(OpenForUserMsg{
287287 Content: op.Content,
internal/mcp_tools/open.go+3−3
@@ -170,7 +170,7 @@ func (h *OpenForUserHandler) Handle(ctx context.Context, arguments json.RawMessa
170170 }
171171
172172 // Detect language from file extension
173- language := detectLanguage(args.File)
173+ language := DetectLanguage(args.File)
174174
175175 // Send message to TUI to update editor
176176 if h.program != nil {
@@ -205,8 +205,8 @@ func (h *OpenForUserHandler) Handle(ctx context.Context, arguments json.RawMessa
205205 }, nil
206206 }
207207
208-// detectLanguage returns the Chroma language identifier based on file extension.
209-func detectLanguage(path string) string {
208+// DetectLanguage returns the Chroma language identifier based on file extension.
209+func DetectLanguage(path string) string {
210210 // Map common extensions to Chroma language identifiers
211211 languageMap := map[string]string{
212212 ".go": "go",
internal/tui/editor/editor.go+15−0
@@ -216,6 +216,21 @@ func (m *Model) Reset() {
216216 m.scroll = 0
217217 }
218218
219+// GotoLine moves the cursor to the given 1-indexed line number and scrolls
220+// it into view.
221+func (m *Model) GotoLine(line int) {
222+ line-- // convert to 0-indexed
223+ if line < 0 {
224+ line = 0
225+ }
226+ if line >= len(m.lines) {
227+ line = len(m.lines) - 1
228+ }
229+ m.row = line
230+ m.col = 0
231+ m.clampScroll()
232+}
233+
219234 // Blink returns the initial cursor blink message. Call from Init().
220235 func Blink() tea.Msg { return cursor.Blink() }
221236
internal/tui/tui.go+205−30
@@ -2,7 +2,12 @@ package tui
22
33 import (
44 "context"
5+ "fmt"
56 "image"
7+ "os"
8+ "path/filepath"
9+ "regexp"
10+ "strconv"
611 "strings"
712 "time"
813
@@ -34,11 +39,35 @@ type layout struct {
3439 }
3540
3641 const (
37- inputRows = 3 // Agent input height
38- statusRows = 2 // Status separator + status bar
39- minPaneWidth = 20
42+ inputRows = 3 // Agent input height
43+ statusRows = 2 // Status separator + status bar
44+ minPaneWidth = 20
45+ maxPreviewLines = 5 // Max lines shown for tool results before truncation
4046 )
4147
48+// entryKind distinguishes conversation entry types for click handling.
49+type entryKind int
50+
51+const (
52+ entryText entryKind = iota // Plain text (user, assistant, separator)
53+ entryToolResult // Tool result — clickable to view full content in editor
54+)
55+
56+// convEntry is a single logical entry in the conversation pane.
57+type convEntry struct {
58+ display string // Styled text for rendering (may be truncated for tool results)
59+ kind entryKind // Entry type
60+ filePath string // Source file path (for tool results that reference a file)
61+ full string // Fallback raw content (when no file path, e.g. Grep results)
62+}
63+
64+// toolResultFileRe extracts the file path from "Opened path ..." / "Edited path ..." / "Created path ..." headers.
65+var toolResultFileRe = regexp.MustCompile(`^(?:Opened|Edited|Created)\s+(\S+)`)
66+
67+// filePathRe matches file references like "path/to/file.go:123" or just "path/to/file.go".
68+// Requires a '/' to avoid matching version numbers like "v1.0".
69+var filePathRe = regexp.MustCompile(`(?:^|[\s(])([a-zA-Z0-9_./-]*[/][a-zA-Z0-9_.-]+\.[a-zA-Z]\w*)(?::(\d+))?`)
70+
4271 // generateLayout computes all regions from terminal size and divider position.
4372 func generateLayout(width, height, divX int) layout {
4473 contentH := height - statusRows
@@ -245,10 +274,11 @@ type Model struct {
245274 cancel context.CancelFunc
246275
247276 // Conversation
248- convEntries []string // Raw styled lines (not wrapped)
249- convLines []string // Wrapped visual lines (cache, rebuilt on width change)
250- convCachedW int // Width used for current convLines cache
251- scrollOffset int // Lines from bottom (0 = pinned)
277+ convEntries []convEntry // Conversation entries (not wrapped)
278+ convLines []string // Wrapped visual lines (cache, rebuilt on width change)
279+ convLineSource []int // Maps each wrapped line -> index in convEntries
280+ convCachedW int // Width used for current convLines cache
281+ scrollOffset int // Lines from bottom (0 = pinned)
252282
253283 // Streaming state: raw text accumulated during streaming, styled at render time
254284 streamingReasoning string // In-progress reasoning text
@@ -304,7 +334,7 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
304334 mcpProxy: proxy,
305335 mcpTools: tools,
306336 history: []provider.Message{{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}},
307- convEntries: []string{},
337+ convEntries: []convEntry{},
308338 updateChan: ch,
309339 ctx: ctx,
310340 cancel: cancel,
@@ -336,15 +366,29 @@ func styledLines(text string, style lipgloss.Style) []string {
336366 return out
337367 }
338368
339-// appendConv appends raw styled entries and returns whether we were at bottom
369+// textEntries converts styled display strings into plain convEntry values.
370+func textEntries(lines ...string) []convEntry {
371+ out := make([]convEntry, len(lines))
372+ for i, l := range lines {
373+ out[i] = convEntry{display: l, kind: entryText}
374+ }
375+ return out
376+}
377+
378+// appendConv appends entries and returns whether we were at bottom
340379 // (for sticky scroll). Invalidates the wrapped-lines cache.
341-func (m *Model) appendConv(entries ...string) bool {
380+func (m *Model) appendConv(entries ...convEntry) bool {
342381 atBottom := m.scrollOffset == 0
343382 m.convEntries = append(m.convEntries, entries...)
344383 m.convLines = nil // invalidate cache
345384 return atBottom
346385 }
347386
387+// appendText is a convenience to append plain text entries.
388+func (m *Model) appendText(lines ...string) bool {
389+ return m.appendConv(textEntries(lines...)...)
390+}
391+
348392 // rebuildStreamEntries replaces any existing streaming entries with fresh
349393 // styled entries from the current streamingReasoning and streamingContent.
350394 // Called on each delta to reflect incremental updates.
@@ -355,10 +399,10 @@ func (m *Model) rebuildStreamEntries() {
355399 }
356400
357401 if m.streamingReasoning != "" {
358- m.convEntries = append(m.convEntries, styledLines(m.streamingReasoning, m.styles.Muted)...)
402+ m.convEntries = append(m.convEntries, textEntries(styledLines(m.streamingReasoning, m.styles.Muted)...)...)
359403 }
360404 if m.streamingContent != "" {
361- m.convEntries = append(m.convEntries, styledLines(m.streamingContent, m.styles.Text)...)
405+ m.convEntries = append(m.convEntries, textEntries(styledLines(m.streamingContent, m.styles.Text)...)...)
362406 }
363407 m.convLines = nil // invalidate cache
364408 }
@@ -372,14 +416,21 @@ func (m *Model) wrappedConvLines() []string {
372416 }
373417 m.convCachedW = w
374418 lines := make([]string, 0, len(m.convEntries))
375- for _, entry := range m.convEntries {
376- if entry == "" {
419+ source := make([]int, 0, len(m.convEntries))
420+ for i, entry := range m.convEntries {
421+ if entry.display == "" {
377422 lines = append(lines, "")
423+ source = append(source, i)
378424 } else {
379- lines = append(lines, wrapANSI(entry, w)...)
425+ wrapped := wrapANSI(entry.display, w)
426+ for range wrapped {
427+ source = append(source, i)
428+ }
429+ lines = append(lines, wrapped...)
380430 }
381431 }
382432 m.convLines = lines
433+ m.convLineSource = source
383434 return m.convLines
384435 }
385436
@@ -454,11 +505,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
454505 m.history = append(m.history, provider.Message{
455506 Role: "user", Content: msg.content, CreatedAt: now,
456507 })
457- m.appendConv(styledLines(msg.content, m.styles.Text)...)
458- m.appendConv("")
508+ m.appendText(styledLines(msg.content, m.styles.Text)...)
509+ m.appendText("")
459510 sep := m.makeSeparator("0s", now.Format("15:04:05"))
460- wasBottom := m.appendConv(sep)
461- m.appendConv("")
511+ wasBottom := m.appendText(sep)
512+ m.appendText("")
462513 if wasBottom {
463514 m.scrollOffset = 0
464515 }
@@ -511,22 +562,22 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
511562 }
512563
513564 if msg.reasoning != "" {
514- wasBottom := m.appendConv(styledLines(msg.reasoning, m.styles.Muted)...)
515- m.appendConv("")
565+ wasBottom := m.appendText(styledLines(msg.reasoning, m.styles.Muted)...)
566+ m.appendText("")
516567 if wasBottom {
517568 m.scrollOffset = 0
518569 }
519570 }
520571 if msg.content != "" {
521- wasBottom := m.appendConv(styledLines(msg.content, m.styles.Text)...)
522- m.appendConv("")
572+ wasBottom := m.appendText(styledLines(msg.content, m.styles.Text)...)
573+ m.appendText("")
523574 if wasBottom {
524575 m.scrollOffset = 0
525576 }
526577 }
527578 for _, tc := range msg.toolCalls {
528579 entry := m.styles.ToolArrow.Render("→") + " " + m.styles.ToolCall.Render(tc.Name+"(...)")
529- wasBottom := m.appendConv(entry)
580+ wasBottom := m.appendText(entry)
530581 if wasBottom {
531582 m.scrollOffset = 0
532583 }
@@ -534,21 +585,48 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
534585 return m, m.waitForLLMUpdate()
535586
536587 case llmToolResultMsg:
537- entry := m.styles.ToolArrow.Render("←") + " " + m.styles.Dim.Render(msg.content)
538- wasBottom := m.appendConv(entry)
588+ // Extract file path from tool result header (Opened/Edited/Created)
589+ var filePath string
590+ if sm := toolResultFileRe.FindStringSubmatch(msg.content); sm != nil {
591+ filePath = sm[1]
592+ }
593+
594+ lines := strings.Split(msg.content, "\n")
595+ preview := lines
596+ truncated := false
597+ if len(lines) > maxPreviewLines {
598+ preview = lines[:maxPreviewLines]
599+ truncated = true
600+ }
601+
602+ arrow := m.styles.ToolArrow.Render("←") + " "
603+ var wasBottom bool
604+ for i, line := range preview {
605+ display := m.styles.Dim.Render(line)
606+ if i == 0 {
607+ display = arrow + display
608+ wasBottom = m.appendConv(convEntry{display: display, kind: entryToolResult, filePath: filePath, full: msg.content})
609+ } else {
610+ m.appendConv(convEntry{display: display, kind: entryToolResult, filePath: filePath, full: msg.content})
611+ }
612+ }
613+ if truncated {
614+ hint := fmt.Sprintf(" ... %d more lines (click to view)", len(lines)-maxPreviewLines)
615+ m.appendConv(convEntry{display: m.styles.Muted.Render(hint), kind: entryToolResult, filePath: filePath, full: msg.content})
616+ }
539617 if wasBottom {
540618 m.scrollOffset = 0
541619 }
542620 return m, m.waitForLLMUpdate()
543621
544622 case llmErrorMsg:
545- m.appendConv("", m.styles.Error.Render("Error: "+msg.err.Error()), "")
623+ m.appendText("", m.styles.Error.Render("Error: "+msg.err.Error()), "")
546624 return m, nil
547625
548626 case llmDoneMsg:
549- m.appendConv("")
627+ m.appendText("")
550628 sep := m.makeSeparator(msg.duration.Round(time.Second).String(), msg.timestamp)
551- m.appendConv(sep)
629+ m.appendText(sep)
552630 return m, nil
553631
554632 case mcp_tools.OpenForUserMsg:
@@ -671,7 +749,12 @@ func (m Model) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
671749 }
672750 case tea.MouseActionRelease:
673751 m.selecting = false
674- if m.selectStart != m.selectEnd {
752+ if m.selectStart == m.selectEnd {
753+ // Single click — try to handle as interactive click
754+ if cmd := m.handleConvClick(clickedLine); cmd != nil {
755+ cmds = append(cmds, cmd)
756+ }
757+ } else {
675758 start, end := m.selectStart, m.selectEnd
676759 if start > end {
677760 start, end = end, start
@@ -721,6 +804,98 @@ func (m *Model) visibleStartLine() int {
721804 return start
722805 }
723806
807+// handleConvClick resolves a click on a wrapped conversation line.
808+// If the line belongs to a tool result entry, the full content is opened in
809+// the editor. Otherwise, if the line contains a file path reference
810+// (path/to/file.go:123), that file is opened in the editor.
811+func (m *Model) handleConvClick(wrappedLine int) tea.Cmd {
812+ m.wrappedConvLines() // ensure convLineSource is fresh
813+ src := m.convLineSource
814+ if wrappedLine < 0 || wrappedLine >= len(src) {
815+ return nil
816+ }
817+ entryIdx := src[wrappedLine]
818+ if entryIdx < 0 || entryIdx >= len(m.convEntries) {
819+ return nil
820+ }
821+ entry := m.convEntries[entryIdx]
822+
823+ // Tool result: open the source file or fall back to raw content
824+ if entry.kind == entryToolResult {
825+ if entry.filePath != "" {
826+ if content, err := os.ReadFile(entry.filePath); err == nil {
827+ m.editor.SetValue(string(content))
828+ m.editor.Language = mcp_tools.DetectLanguage(entry.filePath)
829+ m.focus = focusEditor
830+ m.agentInput.Blur()
831+ m.editor.Focus()
832+ return nil
833+ }
834+ }
835+ // Fallback: show raw tool result text
836+ if entry.full != "" {
837+ m.editor.SetValue(entry.full)
838+ m.editor.Language = "text"
839+ m.focus = focusEditor
840+ m.agentInput.Blur()
841+ m.editor.Focus()
842+ return nil
843+ }
844+ }
845+
846+ // Try to extract a file path from the clicked line's plain text
847+ lines := m.wrappedConvLines()
848+ if wrappedLine >= len(lines) {
849+ return nil
850+ }
851+ plain := ansi.Strip(lines[wrappedLine])
852+ return m.tryOpenFilePath(plain)
853+}
854+
855+// tryOpenFilePath looks for a file:line reference in text and opens it in the editor.
856+func (m *Model) tryOpenFilePath(text string) tea.Cmd {
857+ matches := filePathRe.FindStringSubmatch(text)
858+ if matches == nil {
859+ return nil
860+ }
861+ path := matches[1]
862+ lineNum := 0
863+ if matches[2] != "" {
864+ lineNum, _ = strconv.Atoi(matches[2])
865+ }
866+
867+ absPath, err := filepath.Abs(path)
868+ if err != nil {
869+ return nil
870+ }
871+
872+ // Restrict to files within the working directory
873+ wd, err := os.Getwd()
874+ if err != nil {
875+ return nil
876+ }
877+ rel, err := filepath.Rel(wd, absPath)
878+ if err != nil || strings.HasPrefix(rel, "..") {
879+ return nil
880+ }
881+
882+ content, err := os.ReadFile(absPath)
883+ if err != nil {
884+ return nil
885+ }
886+
887+ language := mcp_tools.DetectLanguage(path)
888+ m.editor.SetValue(string(content))
889+ m.editor.Language = language
890+ if lineNum > 0 {
891+ m.editor.GotoLine(lineNum)
892+ }
893+ m.focus = focusEditor
894+ m.agentInput.Blur()
895+ m.editor.Focus()
896+ return nil
897+}
898+
724899 // ---------------------------------------------------------------------------
725900 // View
726901 // ---------------------------------------------------------------------------