xonecas.io
62159
Sy

symb / commit 0ea1205

fix: maybe fix TUI lag on scroll?

xonecas2026-02-11 0ea12051673f0e72fba757b3730bfd9d4f5813ca parent 4ac8f62

4 files changed

docs/DESIGN.md+4−4
@@ -160,11 +160,9 @@ Confidence Level: High for a prototype. The ecosystem is ready.
160160
161161 # TODO:
162162
163-- file and filesystem combined search with fuzzy matching in the current directory tree.
164-- respects gitignore if it exists.
165-- will be used by both tool for llm (Grep()) and for user later. So make a internal/filesearch separate from the Grep tool definition. Keep it decoupled.
163+- TUI is extremly lagging, if I scroll or hold a key down. Cursor blocks scrolling, needs to follow it. ** MAJOR ISSUE **
166164
167-- Enter on editor area send empty message.
165+- Enter on editor area send empty message. Both text areas are Focused, should be mutually exclusive.
168166
169167 - Copy text selection to clipboard (shift + arrows) then (ctrl c)
170168
@@ -173,3 +171,5 @@ Confidence Level: High for a prototype. The ecosystem is ready.
173171 - sendUserEditor(content) tool to add a "buffer"
174172
175173 - streamed assistant response
174+
175+- Fun: Show icon in unicode and a highlight color clock centered in the right panel when there are no messages.
internal/tui/styles.go+1−0
@@ -6,6 +6,7 @@ var (
66 ColorMatrix = lipgloss.Color("#00AA00") // Matrix green
77 ColorDarkGray = lipgloss.Color("#2a2a2a") // Dark gray
88 ColorGray = lipgloss.Color("#3f3f3f")
9+ ColorError = lipgloss.Color("#932e2e")
910 ColorBorder = ColorDarkGray
1011 ColorDimText = ColorGray
1112 )
internal/tui/textarea/textarea.go+41−10
@@ -300,6 +300,9 @@ type Model struct {
300300 // Language for syntax highlighting (e.g., "go", "python", "javascript")
301301 // If empty, no syntax highlighting is applied.
302302 Language string
303+
304+ // highlightCache caches highlighted lines to avoid re-highlighting on every frame
305+ highlightCache map[string]string
303306 }
304307
305308 // New creates a new model with default settings.
@@ -323,6 +326,7 @@ func New() Model {
323326 ShowLineNumbers: true,
324327 Cursor: cur,
325328 KeyMap: DefaultKeyMap,
329+ highlightCache: make(map[string]string),
326330
327331 value: make([][]rune, minHeight, maxLines),
328332 focus: false,
@@ -383,6 +387,9 @@ func (m *Model) InsertRune(r rune) {
383387
384388 // insertRunesFromUserInput inserts runes at the current cursor position.
385389 func (m *Model) insertRunesFromUserInput(runes []rune) {
390+ // Clear highlight cache since text is being modified
391+ m.highlightCache = make(map[string]string)
392+
386393 // Clean up any special characters in the input provided by the
387394 // clipboard. This avoids bugs due to e.g. tab characters and
388395 // whatnot.
@@ -622,6 +629,8 @@ func (m *Model) Reset() {
622629 m.row = 0
623630 m.viewport.GotoTop()
624631 m.SetCursor(0)
632+ // Clear highlight cache on reset
633+ m.highlightCache = make(map[string]string)
625634 }
626635
627636 // san initializes or retrieves the rune sanitizer.
@@ -637,6 +646,7 @@ func (m *Model) san() runeutil.Sanitizer {
637646 // deleteBeforeCursor deletes all text before the cursor. Returns whether or
638647 // not the cursor blink should be reset.
639648 func (m *Model) deleteBeforeCursor() {
649+ m.highlightCache = make(map[string]string)
640650 m.value[m.row] = m.value[m.row][m.col:]
641651 m.SetCursor(0)
642652 }
@@ -645,6 +655,7 @@ func (m *Model) deleteBeforeCursor() {
645655 // the cursor blink should be reset. If input is masked delete everything after
646656 // the cursor so as not to reveal word breaks in the masked input.
647657 func (m *Model) deleteAfterCursor() {
658+ m.highlightCache = make(map[string]string)
648659 m.value[m.row] = m.value[m.row][:m.col]
649660 m.SetCursor(len(m.value[m.row]))
650661 }
@@ -672,6 +683,7 @@ func (m *Model) deleteWordLeft() {
672683 if m.col == 0 || len(m.value[m.row]) == 0 {
673684 return
674685 }
686+ m.highlightCache = make(map[string]string)
675687
676688 // Linter note: it's critical that we acquire the initial cursor position
677689 // here prior to altering it via SetCursor() below. As such, moving this
@@ -711,6 +723,7 @@ func (m *Model) deleteWordRight() {
711723 if m.col >= len(m.value[m.row]) || len(m.value[m.row]) == 0 {
712724 return
713725 }
726+ m.highlightCache = make(map[string]string)
714727
715728 oldCol := m.col
716729
@@ -1024,6 +1037,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
10241037 if m.ReadOnly {
10251038 break
10261039 }
1040+ m.highlightCache = make(map[string]string)
10271041 m.col = clamp(m.col, 0, len(m.value[m.row]))
10281042 if m.col <= 0 {
10291043 m.mergeLineAbove(m.row)
@@ -1039,6 +1053,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
10391053 if m.ReadOnly {
10401054 break
10411055 }
1056+ m.highlightCache = make(map[string]string)
10421057 if len(m.value[m.row]) > 0 && m.col < len(m.value[m.row]) {
10431058 m.value[m.row] = append(m.value[m.row][:m.col], m.value[m.row][m.col+1:]...)
10441059 }
@@ -1135,11 +1150,8 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
11351150 m.Err = msg
11361151 }
11371152
1138- vp, cmd := m.viewport.Update(msg)
1139- m.viewport = &vp
1140- cmds = append(cmds, cmd)
1141-
11421153 newRow, newCol := m.cursorLineNumber(), m.col
1154+ var cmd tea.Cmd
11431155 m.Cursor, cmd = m.Cursor.Update(msg)
11441156 if (newRow != oldRow || newCol != oldCol) && m.Cursor.Mode() == cursor.CursorBlink {
11451157 m.Cursor.Blink = false
@@ -1147,8 +1159,13 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
11471159 }
11481160 cmds = append(cmds, cmd)
11491161
1162+ // Reposition viewport BEFORE viewport.Update to avoid race condition
11501163 m.repositionView()
11511164
1165+ vp, cmd := m.viewport.Update(msg)
1166+ m.viewport = &vp
1167+ cmds = append(cmds, cmd)
1168+
11521169 return m, tea.Batch(cmds...)
11531170 }
11541171
@@ -1225,16 +1242,19 @@ func (m Model) View() string {
12251242 }
12261243 // Apply syntax highlighting if language is set
12271244 lineText := string(wrappedLine)
1228- if m.Language != "" {
1245+ isCursorLine := m.row == l && lineInfo.RowOffset == wl
1246+
1247+ if m.Language != "" && !isCursorLine {
1248+ // Only highlight non-cursor lines here
12291249 lineText = m.highlightLine(lineText)
12301250 }
12311251
1232- if m.row == l && lineInfo.RowOffset == wl {
1233- // For cursor line, we need to handle highlighting carefully
1234- // Split the line at cursor position
1252+ if isCursorLine {
1253+ // For cursor line, work with the original text and split it
12351254 beforeCursor := string(wrappedLine[:lineInfo.ColumnOffset])
12361255 afterCursor := string(wrappedLine[lineInfo.ColumnOffset+1:])
12371256
1257+ // Highlight the segments individually (still need 2 calls due to cursor split)
12381258 if m.Language != "" {
12391259 beforeCursor = m.highlightLine(beforeCursor)
12401260 afterCursor = m.highlightLine(afterCursor)
@@ -1552,11 +1572,17 @@ func clamp(v, low, high int) int {
15521572
15531573 // highlightLine applies Chroma syntax highlighting to a line of text.
15541574 // Returns the original text if highlighting fails or language is empty.
1555-func (m Model) highlightLine(text string) string {
1575+func (m *Model) highlightLine(text string) string {
15561576 if m.Language == "" || text == "" {
15571577 return text
15581578 }
15591579
1580+ // Check cache first
1581+ cacheKey := m.Language + ":" + text
1582+ if highlighted, ok := m.highlightCache[cacheKey]; ok {
1583+ return highlighted
1584+ }
1585+
15601586 // Get lexer for language
15611587 lexer := lexers.Get(m.Language)
15621588 if lexer == nil {
@@ -1590,5 +1616,10 @@ func (m Model) highlightLine(text string) string {
15901616 }
15911617
15921618 // Remove trailing newline if added by formatter
1593- return strings.TrimSuffix(buf.String(), "\n")
1619+ result := strings.TrimSuffix(buf.String(), "\n")
1620+
1621+ // Cache the result
1622+ m.highlightCache[cacheKey] = result
1623+
1624+ return result
15941625 }
internal/tui/tui.go+58−36
@@ -2,6 +2,7 @@ package tui
22
33 import (
44 "context"
5+ "fmt"
56 "strings"
67 "time"
78
@@ -48,6 +49,15 @@ type Model struct {
4849 // Pane resize state
4950 resizingPane bool // True when dragging divider
5051 customHalfWidth int // Custom half width (0 = use default calculated value)
52+
53+ // Wrap cache to avoid re-wrapping unchanged text
54+ wrapCache map[string][]string
55+ wrapCacheKey string // Key for current conversation state
56+
57+ // Pre-allocated styles to avoid repeated allocations
58+ borderStyle lipgloss.Style
59+ selectionStyle lipgloss.Style
60+ conversationWidth int // Track width for style invalidation
5161 }
5262
5363 // New creates a new TUI model
@@ -82,17 +92,20 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool) Model {
8292 ctx, cancel := context.WithCancel(context.Background())
8393
8494 return Model{
85- spinner: s,
86- editor: editor,
87- agentInput: agentInput,
88- provider: prov,
89- mcpProxy: proxy,
90- mcpTools: tools,
91- history: []provider.Message{},
92- conversation: []string{},
93- updateChan: updateChan,
94- ctx: ctx,
95- cancel: cancel,
95+ spinner: s,
96+ editor: editor,
97+ agentInput: agentInput,
98+ provider: prov,
99+ mcpProxy: proxy,
100+ mcpTools: tools,
101+ history: []provider.Message{},
102+ conversation: []string{},
103+ updateChan: updateChan,
104+ ctx: ctx,
105+ cancel: cancel,
106+ wrapCache: make(map[string][]string),
107+ borderStyle: lipgloss.NewStyle().Foreground(ColorBorder),
108+ selectionStyle: lipgloss.NewStyle().Background(ColorDarkGray),
96109 }
97110 }
98111
@@ -103,7 +116,7 @@ func (m Model) Init() tea.Cmd {
103116
104117 // wrapText wraps text to the conversation pane width, applying style after wrapping.
105118 // Returns lines that fit within the pane width.
106-func (m Model) wrapText(text string, style lipgloss.Style) []string {
119+func (m *Model) wrapText(text string, style lipgloss.Style) []string {
107120 if m.rightPaneWidth <= 0 {
108121 // Fallback if width not set yet
109122 lines := strings.Split(text, "\n")
@@ -114,6 +127,14 @@ func (m Model) wrapText(text string, style lipgloss.Style) []string {
114127 return result
115128 }
116129
130+ // Create cache key from text and width
131+ cacheKey := fmt.Sprintf("%d:%s", m.rightPaneWidth, text)
132+
133+ // Check cache
134+ if cached, ok := m.wrapCache[cacheKey]; ok {
135+ return cached
136+ }
137+
117138 // Word wrap first, then apply style to each line
118139 // ansi.Wordwrap preserves ANSI codes and handles wide characters
119140 wrapped := ansi.Wordwrap(text, m.rightPaneWidth, "")
@@ -124,6 +145,13 @@ func (m Model) wrapText(text string, style lipgloss.Style) []string {
124145 for i, line := range lines {
125146 result[i] = style.Render(line)
126147 }
148+
149+ // Cache result (limit cache size to prevent memory issues)
150+ if len(m.wrapCache) > 1000 {
151+ m.wrapCache = make(map[string][]string)
152+ }
153+ m.wrapCache[cacheKey] = result
154+
127155 return result
128156 }
129157
@@ -411,18 +439,18 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
411439 CreatedAt: now,
412440 })
413441 // Format and display user message first
414- grayStyle := lipgloss.NewStyle().Foreground(ColorGray)
442+ grayStyle := lipgloss.NewStyle().Foreground(lipgloss.NoColor{})
415443 wrappedLines := m.wrapText(msg.content, grayStyle)
416444 m.conversation = append(m.conversation, wrappedLines...)
417445 m.conversation = append(m.conversation, "")
418446 // Add timestamp separator after message
419- timestamp := now.Format("15:04")
447+ timestamp := now.Format("15:04:05")
420448 rightPaneWidth := m.width/2 - 1
421449 dashCount := rightPaneWidth - len("0s "+timestamp+" ")
422450 if dashCount < 0 {
423451 dashCount = 0
424452 }
425- separator := lipgloss.NewStyle().Foreground(ColorGray).Render(
453+ separator := lipgloss.NewStyle().Foreground(ColorDarkGray).Render(
426454 "0s " + timestamp + " " + strings.Repeat("─", dashCount),
427455 )
428456 m.conversation = append(m.conversation, separator)
@@ -473,7 +501,7 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
473501 case llmErrorMsg:
474502 // Display error message
475503 m.conversation = append(m.conversation, "")
476- errLine := lipgloss.NewStyle().Foreground(lipgloss.Color("#ff0000")).Render("Error: " + msg.err.Error())
504+ errLine := lipgloss.NewStyle().Foreground(ColorError).Render("Error: " + msg.err.Error())
477505 m.conversation = append(m.conversation, errLine)
478506 m.conversation = append(m.conversation, "")
479507 return m, nil // Done listening
@@ -483,11 +511,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
483511 m.conversation = append(m.conversation, "")
484512 durationStr := msg.duration.Round(time.Second).String()
485513 rightPaneWidth := m.width/2 - 1
486- dashCount := rightPaneWidth - len(durationStr+" "+msg.timestamp+" ")
514+ dashCount := rightPaneWidth - len(durationStr+" "+msg.timestamp+" ") // TODO: Using `leg` should be using lipgloss
487515 if dashCount < 0 {
488516 dashCount = 0
489517 }
490- separator := lipgloss.NewStyle().Foreground(ColorGray).Render(
518+ separator := lipgloss.NewStyle().Foreground(ColorDarkGray).Render(
491519 durationStr + " " + msg.timestamp + " " + strings.Repeat("─", dashCount),
492520 )
493521 m.conversation = append(m.conversation, separator)
@@ -568,7 +596,6 @@ func (m Model) View() string {
568596 contentHeight := m.height - 2
569597
570598 var b strings.Builder
571- borderStyle := lipgloss.NewStyle().Foreground(ColorBorder)
572599
573600 // Render editor in left pane
574601 editorView := m.editor.View()
@@ -578,6 +605,10 @@ func (m Model) View() string {
578605 agentInputView := m.agentInput.View()
579606 agentInputLines := strings.Split(agentInputView, "\n")
580607
608+ // Calculate row boundaries
609+ inputStartRow := contentHeight - 3 // 3 rows for input
610+ separatorRow := contentHeight - 4 // Separator before input
611+
581612 // Content rows - use the stored rightPaneWidth from model
582613 for i := 0; i < contentHeight; i++ {
583614 // Left pane: editor
@@ -593,17 +624,10 @@ func (m Model) View() string {
593624 } else {
594625 b.WriteString(strings.Repeat(" ", halfWidth))
595626 }
596-
597- // Middle divider (or T connection on separator row)
598- separatorRow := contentHeight - 4 // 1 row for separator
599- if i == separatorRow {
600- b.WriteString(borderStyle.Render("├"))
601- } else {
602- b.WriteString(borderStyle.Render("│"))
603- }
627+ // Divider
628+ b.WriteString(m.borderStyle.Render("│"))
604629
605630 // Right pane: conversation area (top), separator, input at bottom
606- inputStartRow := contentHeight - 3 // 3 rows for input
607631 if i < separatorRow {
608632 // Conversation area - show conversation log
609633 // Calculate which line to show (scroll based on offset)
@@ -637,8 +661,7 @@ func (m Model) View() string {
637661
638662 // Apply selection highlighting if selected
639663 if isSelected {
640- selStyle := lipgloss.NewStyle().Background(lipgloss.Color("#444444"))
641- line = selStyle.Render(line)
664+ line = m.selectionStyle.Render(line)
642665 }
643666
644667 lineWidth := lipgloss.Width(line)
@@ -647,8 +670,7 @@ func (m Model) View() string {
647670 if lineWidth < m.rightPaneWidth {
648671 padding := strings.Repeat(" ", m.rightPaneWidth-lineWidth)
649672 if isSelected {
650- selStyle := lipgloss.NewStyle().Background(lipgloss.Color("#444444"))
651- padding = selStyle.Render(padding)
673+ padding = m.selectionStyle.Render(padding)
652674 }
653675 b.WriteString(padding)
654676 }
@@ -657,7 +679,7 @@ func (m Model) View() string {
657679 }
658680 } else if i == separatorRow {
659681 // Separator line
660- b.WriteString(borderStyle.Render(strings.Repeat("─", m.rightPaneWidth)))
682+ b.WriteString(m.borderStyle.Render(strings.Repeat("─", m.rightPaneWidth)))
661683 } else {
662684 // Input area (last 3 rows)
663685 lineIdx := i - inputStartRow
@@ -679,9 +701,9 @@ func (m Model) View() string {
679701 }
680702
681703 // Status separator: ───...───┴───...───
682- b.WriteString(borderStyle.Render(strings.Repeat("─", halfWidth)))
683- b.WriteString(borderStyle.Render("┴"))
684- b.WriteString(borderStyle.Render(strings.Repeat("─", m.width-halfWidth-1)))
704+ b.WriteString(m.borderStyle.Render(strings.Repeat("─", halfWidth)))
705+ b.WriteString(m.borderStyle.Render("┴"))
706+ b.WriteString(m.borderStyle.Render(strings.Repeat("─", m.width-halfWidth-1)))
685707 b.WriteString("\n")
686708
687709 // Status bar: master* │<spaces>spinner