xonecas.io
62159
Sy

symb / files

symb / internal / tui / tui.go

11.2 KB
1package tui
2
3import (
4	"context"
5	"image"
6	"regexp"
7	"sync/atomic"
8	"time"
9
10	tea "charm.land/bubbletea/v2"
11	"charm.land/lipgloss/v2"
12	"github.com/xonecas/symb/internal/delta"
13	"github.com/xonecas/symb/internal/filesearch"
14	"github.com/xonecas/symb/internal/llm"
15	"github.com/xonecas/symb/internal/mcp"
16	"github.com/xonecas/symb/internal/provider"
17	"github.com/xonecas/symb/internal/store"
18	"github.com/xonecas/symb/internal/treesitter"
19	"github.com/xonecas/symb/internal/tui/editor"
20	"github.com/xonecas/symb/internal/tui/modal"
21)
22
23// ---------------------------------------------------------------------------
24// Layout
25// ---------------------------------------------------------------------------
26
27// layout holds computed rectangles for every TUI region.
28// Recomputed from terminal dimensions on every resize.
29type layout struct {
30	conv  image.Rectangle // Conversation log
31	sep   image.Rectangle // Separator between conv and input
32	input image.Rectangle // Agent input
33}
34
35const (
36	inputRows       = 3 // Agent input height
37	statusRows      = 2 // Status separator + status bar
38	maxDisplayTurns = 5 // Max conversation turns kept in memory; older turns live in DB
39
40	roleAssistant = "assistant"
41)
42
43// generateLayout computes all regions from terminal size.
44func generateLayout(width, height int) layout {
45	contentH := height - statusRows
46	if contentH < 1 {
47		contentH = 1
48	}
49
50	sepY := contentH - inputRows - 1
51	if sepY < 0 {
52		sepY = 0
53	}
54	inputY := contentH - inputRows
55	if inputY < 0 {
56		inputY = 0
57	}
58
59	return layout{
60		conv:  image.Rect(0, 0, width, sepY),
61		sep:   image.Rect(0, sepY, width, sepY+1),
62		input: image.Rect(0, inputY, width, inputY+inputRows),
63	}
64}
65
66// inRect returns true if screen point (x,y) is inside r.
67func inRect(x, y int, r image.Rectangle) bool {
68	return image.Pt(x, y).In(r)
69}
70
71// ---------------------------------------------------------------------------
72// Conversation types
73// ---------------------------------------------------------------------------
74
75// entryKind distinguishes conversation entry types for click handling.
76type entryKind int
77
78const (
79	entryText       entryKind = iota // Plain text (user, assistant, reasoning)
80	entryToolCall                    // Tool call arrow line (→ ToolName(...))
81	entryToolResult                  // Tool result summary (← summary [view])
82	entryToolDiag                    // Tool diagnostics — non-clickable
83	entryUndo                        // Undo button — small clickable label
84	entrySeparator                   // Turn-end separator (timestamp + tokens)
85)
86
87// convEntry is a single logical entry in the conversation pane.
88type convEntry struct {
89	display  string    // Styled text for rendering (may be truncated for tool results)
90	kind     entryKind // Entry type
91	filePath string    // Source file path (for tool results that reference a file)
92	full     string    // Full raw content (for editor viewing or undo separator restore)
93	line     int       // Target line (1-indexed) for cursor positioning on click (0 = none)
94	toolName string    // Tool name for view button context (Read, Edit, Shell, etc.)
95}
96
97// toolResultFileRe extracts the file path from "Read path ..." / "Edited path ..." / "Created path ..." headers.
98var toolResultFileRe = regexp.MustCompile(`^(?:Read|Edited|Created)\s+(\S+)`)
99
100// toolResultLineRe extracts the start line from "(lines N-M)" in tool result headers.
101var toolResultLineRe = regexp.MustCompile(`\(lines\s+(\d+)-\d+\)`)
102
103// toolResultRangeRe extracts both start and end lines from "(lines N-M)".
104var toolResultRangeRe = regexp.MustCompile(`\(lines\s+(\d+)-(\d+)\)`)
105
106// ---------------------------------------------------------------------------
107// Conversation selection (character-level)
108// ---------------------------------------------------------------------------
109
110type convPos struct{ line, col int }
111
112// convSelection tracks a character-level selection in the conversation pane.
113type convSelection struct {
114	anchor convPos // Where the selection started
115	active convPos // Current selection endpoint
116}
117
118func (s convSelection) ordered() (start, end convPos) {
119	if s.anchor.line > s.active.line ||
120		(s.anchor.line == s.active.line && s.anchor.col > s.active.col) {
121		return s.active, s.anchor
122	}
123	return s.anchor, s.active
124}
125
126func (s convSelection) empty() bool { return s.anchor == s.active }
127
128// FileReadResetter allows clearing the file read tracker on undo.
129type FileReadResetter interface {
130	Reset()
131}
132
133// ---------------------------------------------------------------------------
134// Turn tracking (for undo)
135// ---------------------------------------------------------------------------
136
137// turnBoundary marks the start of a user turn in convEntries.
138type turnBoundary struct {
139	convIdx      int   // index in m.convEntries where this turn's display starts
140	dbMsgID      int64 // messages.id of the user message (for DB cleanup)
141	inputTokens  int   // total input tokens at start of this turn
142	outputTokens int   // total output tokens at start of this turn
143}
144
145// ---------------------------------------------------------------------------
146// Model
147// ---------------------------------------------------------------------------
148
149// Model is the top-level TUI model.
150type Model struct {
151	// Terminal dimensions
152	width, height int
153
154	// Sub-models
155	agentInput editor.Model
156
157	// Layout
158	layout layout
159	styles Styles
160
161	// LLM
162	provider   provider.Provider
163	mcpProxy   *mcp.Proxy
164	mcpTools   []mcp.Tool
165	updateChan chan tea.Msg
166	ctx        context.Context
167	cancel     context.CancelFunc
168	turnCtx    context.Context    // per-turn child context (nil when idle)
169	turnCancel context.CancelFunc // cancels current LLM turn only (nil when idle)
170
171	// Session persistence
172	store            *store.Cache
173	storeQueue       chan storeBatch
174	storeQueueDone   <-chan struct{}
175	sessionID        string
176	initialSystemMsg *provider.Message
177
178	// Conversation
179	convEntries    []convEntry // Conversation entries (not wrapped)
180	convLineSource []int       // Maps each wrapped line -> index in convEntries (recomputed each frame)
181	scrollOffset   int         // Lines from bottom (0 = pinned)
182
183	// Streaming state: raw text accumulated during streaming, styled at render time
184	streamingReasoning string // In-progress reasoning text
185	streamingContent   string // In-progress content text
186	streaming          bool   // Whether we're currently streaming
187	streamEntryStart   int    // Index in convEntries where streaming entries begin (-1 = none)
188
189	// Token usage tracking
190	turnInputTokens   int // accumulated input tokens for current turn
191	turnOutputTokens  int // accumulated output tokens for current turn
192	turnContextTokens int // context size (last API call's input tokens)
193	totalInputTokens  int // session-wide total input tokens
194	totalOutputTokens int // session-wide total output tokens
195
196	// Context recitation
197	scratchpad llm.ScratchpadReader // agent plan injected at context tail
198
199	// Undo
200	deltaTracker   *delta.Tracker
201	turnBoundaries []turnBoundary
202	fileTracker    FileReadResetter // for clearing read-tracking on undo
203	tsIndex        *treesitter.Index
204
205	// File finder modal
206	fileModal *modal.Model
207	atOffset  int // rune offset where @ was typed (for file modal replacement)
208	// Keybinds modal
209	keybindsModal *modal.Model
210	// Models modal
211	modelsModal *modal.Model
212	// Tool viewer modal
213	toolViewModal *modal.ToolView
214	searcher      *filesearch.Searcher
215
216	// Provider switching
217	registry         *provider.Registry
218	providerOpts     provider.Options
219	currentModelName string
220	cachedModels     []provider.TaggedModel // cached across all providers
221	sharedProvider   *atomic.Pointer[provider.Provider]
222	// Pending tool calls: maps tool call ID → arguments for line extraction
223	pendingToolCalls map[string]provider.ToolCall
224
225	// Conversation selection
226	convSel      *convSelection
227	convDragging bool
228
229	// Frame loop
230	streamDirty  bool     // New streaming content arrived since last rebuild
231	frameLines   []string // Per-frame cache of wrapped conv lines (cleared each Update)
232	turnPending  bool     // True while awaiting user message persistence
233	undoInFlight bool     // True while undo side-effects are running
234
235	// Statusbar state
236	providerConfigName string // TOML config key (e.g. "zen-pickle")
237	gitBranch          string // Current git branch name
238	gitDirty           bool   // Working tree has uncommitted changes
239	gitAdded           int
240	gitModified        int
241	gitRemoved         int
242
243	lastNetError string // Last LLM network error (truncated for display)
244	llmInFlight  bool   // True while an LLM turn is in progress
245
246	// Statusbar animation
247	spinFrame   int       // Current braille spinner frame index
248	spinFrameAt time.Time // When the current frame was set
249}
250
251// New creates a new TUI model.
252// If resumeHistory is non-nil, the session is being resumed and messages are
253// loaded from the database instead of creating a fresh system prompt.
254func New(prov provider.Provider, sharedProvider *atomic.Pointer[provider.Provider], proxy *mcp.Proxy, tools []mcp.Tool, modelID string, db *store.Cache, sessionID string, idx *treesitter.Index, dt *delta.Tracker, ft FileReadResetter, providerConfigName string, pad llm.ScratchpadReader, resumeHistory []provider.Message, registry *provider.Registry, providerOpts provider.Options, syntaxTheme string) Model {
255	initTheme(syntaxTheme)
256	sty := DefaultStyles()
257	cursorStyle := lipgloss.NewStyle().Foreground(ColorHighlight)
258
259	selStyle := sty.Selection
260
261	ai := editor.New()
262	ai.Placeholder = "Ask anything... (CTRL+h for keybinds)"
263	ai.SubmitOnEnter = true
264	ai.Language = "markdown"
265	ai.SyntaxTheme = syntaxTheme
266	ai.CursorStyle = cursorStyle
267	ai.SelectionStyle = selStyle
268	ai.PlaceholderSty = lipgloss.NewStyle().Foreground(ColorDim).Background(ColorBg)
269	ai.BgColor = ColorBg
270	ai.Focus()
271
272	ch := make(chan tea.Msg, 500)
273	var storeQueue chan storeBatch
274	var storeQueueDone <-chan struct{}
275	if db != nil {
276		storeQueue = make(chan storeBatch, 256)
277		storeQueueDone = startStoreWorker(db, storeQueue)
278	}
279	ctx, cancel := context.WithCancel(context.Background())
280
281	var entries []convEntry
282	var initialSystemMsg *provider.Message
283	if resumeHistory != nil {
284		entries = historyConvEntries(resumeHistory, sty)
285	} else {
286		systemPrompt := llm.BuildSystemPrompt(modelID, idx)
287		systemMsg := provider.Message{Role: "system", Content: systemPrompt, CreatedAt: time.Now()}
288		initialSystemMsg = &systemMsg
289	}
290
291	return Model{
292		agentInput: ai,
293		styles:     sty,
294
295		provider:    prov,
296		mcpProxy:    proxy,
297		mcpTools:    tools,
298		convEntries: entries,
299		updateChan:  ch,
300		ctx:         ctx,
301		cancel:      cancel,
302
303		store:            db,
304		storeQueue:       storeQueue,
305		storeQueueDone:   storeQueueDone,
306		sessionID:        sessionID,
307		initialSystemMsg: initialSystemMsg,
308
309		scratchpad:   pad,
310		deltaTracker: dt,
311		fileTracker:  ft,
312		tsIndex:      idx,
313
314		searcher:         newSearcherOrNil("."),
315		registry:         registry,
316		providerOpts:     providerOpts,
317		currentModelName: modelID,
318		sharedProvider:   sharedProvider,
319
320		streamEntryStart: -1,
321
322		providerConfigName: providerConfigName,
323	}
324}
325
326func newSearcherOrNil(root string) *filesearch.Searcher {
327	s, err := filesearch.NewSearcher(root)
328	if err != nil {
329		return nil
330	}
331	return s
332}
333
334// Init starts the 60fps frame loop and periodic git branch polling.
335func (m Model) Init() tea.Cmd {
336	cmds := []tea.Cmd{frameTick(), gitBranchCmd()}
337	if m.initialSystemMsg != nil {
338		cmds = append(cmds, m.saveMessagesCmd([]provider.Message{*m.initialSystemMsg}))
339	}
340	return tea.Batch(cmds...)
341}