xonecas.io
62159
Sy

symb / commit 6786174

fix: TUI lag

xonecas2026-02-14 678617469f706821636210bc757205cb5a290274 parent be2659b

4 files changed

internal/tui/conv.go+26−2
@@ -49,7 +49,7 @@ func (m *Model) appendText(lines ...string) bool {
4949
5050 // rebuildStreamEntries replaces any existing streaming entries with fresh
5151 // styled entries from the current streamingReasoning and streamingContent.
52-// Called on each delta to reflect incremental updates.
52+// Only re-wraps the streaming portion — the stable prefix is preserved.
5353 func (m *Model) rebuildStreamEntries() {
5454 // Remove old streaming entries
5555 if m.streamEntryStart >= 0 && m.streamEntryStart <= len(m.convEntries) {
@@ -62,7 +62,31 @@ func (m *Model) rebuildStreamEntries() {
6262 if m.streamingContent != "" {
6363 m.convEntries = append(m.convEntries, textEntries(styledLines(m.streamingContent, m.styles.Text)...)...)
6464 }
65- m.convLines = nil // invalidate cache
65+
66+ // Incrementally re-wrap only the streaming entries.
67+ w := m.convWidth()
68+ if m.convLines != nil && m.convCachedW == w && m.streamWrapStart <= len(m.convLines) {
69+ // Truncate cached lines/source to the stable prefix.
70+ m.convLines = m.convLines[:m.streamWrapStart]
71+ m.convLineSource = m.convLineSource[:m.streamWrapStart]
72+ // Wrap only new streaming entries and append.
73+ for i := m.streamEntryStart; i < len(m.convEntries); i++ {
74+ entry := m.convEntries[i]
75+ if entry.display == "" {
76+ m.convLines = append(m.convLines, "")
77+ m.convLineSource = append(m.convLineSource, i)
78+ } else {
79+ wrapped := wrapANSI(entry.display, w)
80+ for range wrapped {
81+ m.convLineSource = append(m.convLineSource, i)
82+ }
83+ m.convLines = append(m.convLines, wrapped...)
84+ }
85+ }
86+ } else {
87+ // Cache invalid or width changed — full rebuild.
88+ m.convLines = nil
89+ }
6690 }
6791
6892 // wrappedConvLines returns the conversation wrapped to the current convWidth.
internal/tui/messages.go+18−1
@@ -38,6 +38,9 @@ type llmErrorMsg struct{ err error }
3838 type llmContentDeltaMsg struct{ content string }
3939 type llmReasoningDeltaMsg struct{ content string }
4040
41+// llmBatchMsg carries multiple messages drained from updateChan in one go.
42+type llmBatchMsg []tea.Msg
43+
4144 // UpdateToolsMsg is exported so main.go can send it via program.Send.
4245 type UpdateToolsMsg struct{ Tools []mcp.Tool }
4346
@@ -56,7 +59,21 @@ func (m Model) sendToLLM(userInput string) tea.Cmd {
5659 }
5760
5861 func (m Model) waitForLLMUpdate() tea.Cmd {
59- return func() tea.Msg { return <-m.updateChan }
62+ ch := m.updateChan
63+ return func() tea.Msg {
64+ // Block until at least one message arrives.
65+ first := <-ch
66+ batch := llmBatchMsg{first}
67+ // Drain all pending messages without blocking.
68+ for {
69+ select {
70+ case msg := <-ch:
71+ batch = append(batch, msg)
72+ default:
73+ return batch
74+ }
75+ }
76+ }
6077 }
6178
6279 func (m Model) processLLM() tea.Cmd {
internal/tui/tui.go+1−0
@@ -187,6 +187,7 @@ type Model struct {
187187 streamingContent string // In-progress content text
188188 streaming bool // Whether we're currently streaming
189189 streamEntryStart int // Index in convEntries where streaming entries begin (-1 = none)
190+ streamWrapStart int // Number of cached wrapped lines before streaming entries
190191
191192 // Editor state
192193 editorFilePath string // absolute path of the file currently shown in the editor
internal/tui/update.go+159−0
@@ -100,6 +100,10 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
100100 }
101101 }
102102
103+ // -- LLM batch (multiple messages drained from updateChan) ---------------
104+ case llmBatchMsg:
105+ return m.handleLLMBatch(msg)
106+
103107 // -- LLM messages --------------------------------------------------------
104108 case llmUserMsg:
105109 now := time.Now()
@@ -120,6 +124,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
120124 if !m.streaming {
121125 m.streaming = true
122126 m.streamEntryStart = len(m.convEntries)
127+ m.streamWrapStart = len(m.wrappedConvLines())
123128 m.streamingReasoning = ""
124129 m.streamingContent = ""
125130 }
@@ -134,6 +139,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
134139 if !m.streaming {
135140 m.streaming = true
136141 m.streamEntryStart = len(m.convEntries)
142+ m.streamWrapStart = len(m.wrappedConvLines())
137143 m.streamingReasoning = ""
138144 m.streamingContent = ""
139145 }
@@ -277,6 +283,159 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
277283 return m, tea.Batch(cmds...)
278284 }
279285
286+// handleLLMBatch processes a batch of messages drained from updateChan.
287+// Delta messages are accumulated first, with a single rebuildStreamEntries
288+// at the end, avoiding per-token re-wraps.
289+func (m Model) handleLLMBatch(batch llmBatchMsg) (tea.Model, tea.Cmd) {
290+ needRebuild := false
291+ var finalCmd tea.Cmd
292+
293+ for _, raw := range batch {
294+ switch msg := raw.(type) {
295+ case llmReasoningDeltaMsg:
296+ if !m.streaming {
297+ m.streaming = true
298+ m.streamEntryStart = len(m.convEntries)
299+ m.streamWrapStart = len(m.wrappedConvLines())
300+ m.streamingReasoning = ""
301+ m.streamingContent = ""
302+ }
303+ m.streamingReasoning += msg.content
304+ needRebuild = true
305+
306+ case llmContentDeltaMsg:
307+ if !m.streaming {
308+ m.streaming = true
309+ m.streamEntryStart = len(m.convEntries)
310+ m.streamWrapStart = len(m.wrappedConvLines())
311+ m.streamingReasoning = ""
312+ m.streamingContent = ""
313+ }
314+ m.streamingContent += msg.content
315+ needRebuild = true
316+
317+ case llmHistoryMsg:
318+ m.history = append(m.history, msg.msg)
319+
320+ case llmAssistantMsg:
321+ // Flush any pending streaming rebuild before finalizing.
322+ if needRebuild {
323+ m.rebuildStreamEntries()
324+ needRebuild = false
325+ }
326+ m.applyAssistantMsg(msg)
327+
328+ case llmToolResultMsg:
329+ if needRebuild {
330+ m.rebuildStreamEntries()
331+ needRebuild = false
332+ }
333+ m.applyToolResultMsg(msg)
334+
335+ case llmErrorMsg:
336+ if needRebuild {
337+ m.rebuildStreamEntries()
338+ }
339+ m.appendText("", m.styles.Error.Render("Error: "+msg.err.Error()), "")
340+ return m, nil
341+
342+ case llmDoneMsg:
343+ if needRebuild {
344+ m.rebuildStreamEntries()
345+ }
346+ m.appendText("")
347+ sep := m.makeSeparator(msg.duration.Round(time.Second).String(), msg.timestamp)
348+ m.appendText(sep)
349+ return m, nil
350+ }
351+ }
352+
353+ // Apply one rebuild for all accumulated deltas.
354+ if needRebuild {
355+ m.rebuildStreamEntries()
356+ }
357+
358+ // Keep scroll pinned to bottom during streaming.
359+ if m.scrollOffset == 0 {
360+ m.scrollOffset = 0
361+ }
362+
363+ // More messages may follow — keep listening.
364+ finalCmd = m.waitForLLMUpdate()
365+ return m, finalCmd
366+}
367+
368+// applyAssistantMsg finalizes streaming state and appends the assistant's
369+// response entries. Extracted so handleLLMBatch can reuse the logic.
370+func (m *Model) applyAssistantMsg(msg llmAssistantMsg) {
371+ if m.streaming {
372+ m.streaming = false
373+ if m.streamEntryStart >= 0 && m.streamEntryStart <= len(m.convEntries) {
374+ m.convEntries = m.convEntries[:m.streamEntryStart]
375+ }
376+ m.streamEntryStart = -1
377+ m.streamingReasoning = ""
378+ m.streamingContent = ""
379+ m.convLines = nil
380+ }
381+ if msg.reasoning != "" {
382+ wasBottom := m.appendText(styledLines(msg.reasoning, m.styles.Muted)...)
383+ m.appendText("")
384+ if wasBottom {
385+ m.scrollOffset = 0
386+ }
387+ }
388+ if msg.content != "" {
389+ wasBottom := m.appendText(styledLines(msg.content, m.styles.Text)...)
390+ m.appendText("")
391+ if wasBottom {
392+ m.scrollOffset = 0
393+ }
394+ }
395+ for _, tc := range msg.toolCalls {
396+ entry := m.styles.ToolArrow.Render("→") + " " + m.styles.ToolCall.Render(tc.Name+"(...)")
397+ wasBottom := m.appendText(entry)
398+ if wasBottom {
399+ m.scrollOffset = 0
400+ }
401+ }
402+}
403+
404+// applyToolResultMsg appends tool result display entries.
405+func (m *Model) applyToolResultMsg(msg llmToolResultMsg) {
406+ var filePath string
407+ if sm := toolResultFileRe.FindStringSubmatch(msg.content); sm != nil {
408+ filePath = sm[1]
409+ }
410+
411+ lines := strings.Split(msg.content, "\n")
412+ preview := lines
413+ truncated := false
414+ if len(lines) > maxPreviewLines {
415+ preview = lines[:maxPreviewLines]
416+ truncated = true
417+ }
418+
419+ arrow := m.styles.ToolArrow.Render("←") + " "
420+ var wasBottom bool
421+ for i, line := range preview {
422+ display := m.styles.Dim.Render(line)
423+ if i == 0 {
424+ display = arrow + display
425+ wasBottom = m.appendConv(convEntry{display: display, kind: entryToolResult, filePath: filePath, full: msg.content})
426+ } else {
427+ m.appendConv(convEntry{display: display, kind: entryToolResult, filePath: filePath, full: msg.content})
428+ }
429+ }
430+ if truncated {
431+ hint := fmt.Sprintf(" ... %d more lines (click to view)", len(lines)-maxPreviewLines)
432+ m.appendConv(convEntry{display: m.styles.Muted.Render(hint), kind: entryToolResult, filePath: filePath, full: msg.content})
433+ }
434+ if wasBottom {
435+ m.scrollOffset = 0
436+ }
437+}
438+
280439 // updateComponentSizes pushes layout dimensions to sub-models.
281440 func (m *Model) updateComponentSizes() {
282441 m.editor.SetWidth(m.layout.editor.Dx())