1package modes
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "sync"
8
9 "github.com/patriceckhart/zot/packages/core"
10 "github.com/patriceckhart/zot/packages/provider"
11 "github.com/patriceckhart/zot/packages/tui"
12)
13
14// btwTurn is one user/assistant pair within a side chat. Kept
15// separate from the main transcript so closing the dialog leaves
16// the main session untouched.
17type btwTurn struct {
18 User string
19 Assistant string
20 Tools []tui.ToolCallView
21 Err string
22}
23
24// btwDialog is the side-chat overlay opened by /btw. It shows the
25// user's question, runs an isolated agent turn against the live
26// snapshot of the main session plus any prior side-chat turns,
27// renders the assistant reply through the markdown pipeline, and
28// keeps the main transcript completely untouched.
29//
30// Cancellation: esc cancels an in-flight call when one is running,
31// otherwise closes the dialog.
32type btwDialog struct {
33 mu sync.Mutex
34 active bool
35 turns []btwTurn
36 editor *tui.Editor
37 loading bool
38 compactMode bool
39 lineInput bool
40 cancel context.CancelFunc
41
42 // spin drives the same braille animation + rotating funny-line
43 // shown in the main status bar. Owned by the dialog so its clock
44 // is independent of the main spinner (so re-opening the dialog
45 // always starts fresh and the message doesn't carry over from a
46 // completed main turn).
47 spin *spinner
48
49 // sideAgent owns an isolated transcript seeded from the main
50 // conversation. It uses the same tools and runtime hooks as the
51 // main agent, but has no persistence callbacks.
52 sideAgent *core.Agent
53
54 // Theme and toolView are cached so render() uses the same tool-call
55 // presentation and collapse behavior as the main transcript.
56 theme tui.Theme
57 toolView *tui.View
58
59 // cwd is the working directory used to resolve relative paths
60 // when the user presses Tab on a path-like token in the side-
61 // chat editor. Set by Open() from the host's cwd so the same
62 // path-completion that works in the main editor also works
63 // here.
64 cwd string
65}
66
67func newBtwDialog() *btwDialog {
68 return &btwDialog{}
69}
70
71// Active reports whether the dialog is visible and consuming keys.
72func (d *btwDialog) Active() bool {
73 if d == nil {
74 return false
75 }
76 d.mu.Lock()
77 defer d.mu.Unlock()
78 return d.active
79}
80
81// Loading reports whether the dialog is currently awaiting a
82// model response (and therefore rendering an animated spinner).
83// Used by the host to decide whether a periodic redraw is worth
84// triggering; when false and the user is just typing, we can
85// skip the tick and let the terminal drive the cursor blink.
86func (d *btwDialog) Loading() bool {
87 if d == nil {
88 return false
89 }
90 d.mu.Lock()
91 defer d.mu.Unlock()
92 return d.active && d.loading
93}
94
95// SetToolPreview attaches the side-effect-free confirmation preview to the
96// matching side-chat tool box before execution begins.
97func (d *btwDialog) SetToolPreview(id, summary, content string) {
98 if d == nil || id == "" {
99 return
100 }
101 d.mu.Lock()
102 defer d.mu.Unlock()
103 for turnIdx := range d.turns {
104 if tool := findBtwTool(&d.turns[turnIdx], id); tool != nil {
105 tool.Args = summary
106 tool.Preview = content
107 return
108 }
109 }
110}
111
112// ToggleToolExpansion expands or collapses long tool results in the side chat.
113func (d *btwDialog) ToggleToolExpansion() {
114 if d == nil {
115 return
116 }
117 d.mu.Lock()
118 defer d.mu.Unlock()
119 if d.toolView != nil {
120 d.toolView.ExpandAll = !d.toolView.ExpandAll
121 }
122}
123
124// Open enters the side chat. agent supplies the live transcript and
125// system prompt, plus the underlying provider client to use for the
126// one-off completion. seed is an optional first question that gets
127// auto-submitted (so /btw <text> starts a conversation right away).
128// invalidate, if non-nil, is called after each state change so the
129// host redraw loop can pick up the update without polling.
130func (d *btwDialog) Open(th tui.Theme, agent *core.Agent, system, model, cwd, seed string, compactMode, flatTools bool, lineInput bool, invalidate func()) {
131 d.mu.Lock()
132 d.active = true
133 d.theme = th
134 d.compactMode = compactMode
135 d.lineInput = lineInput
136 d.toolView = &tui.View{Theme: th, CompactMode: compactMode, FlatTools: flatTools}
137 d.turns = nil
138 d.loading = false
139 d.cancel = nil
140 prompt := th.AccentBar(th.Accent)
141 if lineInput {
142 prompt = ""
143 }
144 d.editor = tui.NewEditor(prompt)
145 d.sideAgent = newBtwAgent(agent, system, model)
146 d.cwd = cwd
147 d.mu.Unlock()
148
149 if seed = strings.TrimSpace(seed); seed != "" {
150 d.editor.SetValue(seed)
151 d.submit(invalidate)
152 }
153}
154
155// Close hides the dialog. Cancels any in-flight request.
156func (d *btwDialog) Close() {
157 d.mu.Lock()
158 d.active = false
159 d.turns = nil
160 d.editor = nil
161 d.loading = false
162 cancel := d.cancel
163 d.cancel = nil
164 d.sideAgent = nil
165 d.toolView = nil
166 d.mu.Unlock()
167 if cancel != nil {
168 cancel()
169 }
170}
171
172// HandleKey routes a keypress to the dialog. Returns true if the
173// dialog wants the event consumed (always true while active, except
174// for the special closing case where the caller may want to signal
175// the parent).
176func (d *btwDialog) HandleKey(k tui.Key, invalidate func()) (closed bool) {
177 if !d.Active() {
178 return false
179 }
180 switch k.Kind {
181 case tui.KeyEsc:
182 // First esc: cancel an in-flight call. Subsequent esc closes.
183 d.mu.Lock()
184 busy := d.loading
185 cancel := d.cancel
186 d.mu.Unlock()
187 if busy && cancel != nil {
188 cancel()
189 return false
190 }
191 d.Close()
192 invalidate()
193 return true
194 }
195
196 d.mu.Lock()
197 editor := d.editor
198 loading := d.loading
199 cwd := d.cwd
200 d.mu.Unlock()
201 if editor == nil {
202 return false
203 }
204 // Tab-complete a path-like token before the editor sees the key,
205 // matching the main editor's behaviour.
206 if k.Kind == tui.KeyTab {
207 if tryPathTabCompleteEditor(editor, cwd) {
208 invalidate()
209 return false
210 }
211 }
212 // Don't accept new submissions while a call is in flight; arrow
213 // keys / scrolling still flow through to the editor for caret
214 // movement and history.
215 submitted := editor.HandleKey(k)
216 invalidate()
217 if submitted && !loading {
218 d.submit(invalidate)
219 }
220 return false
221}
222
223// submit fires the LLM call for the current input and, on success,
224// appends a new turn to d.turns. invalidate is called every time
225// the turn's visible state changes (text delta, error, complete)
226// so the host redraw loop picks up the update without relying on
227// a periodic tick.
228func (d *btwDialog) submit(invalidate func()) {
229 d.mu.Lock()
230 if d.editor == nil || d.loading {
231 d.mu.Unlock()
232 return
233 }
234 question := strings.TrimSpace(d.editor.Value())
235 if question == "" {
236 d.mu.Unlock()
237 return
238 }
239 d.editor.Clear()
240 d.loading = true
241 if d.spin == nil {
242 d.spin = newSpinner(d.theme)
243 } else {
244 d.spin.Configure(d.theme)
245 }
246 d.spin.Start()
247 d.turns = append(d.turns, btwTurn{User: question})
248 turnIdx := len(d.turns) - 1
249
250 ctx, cancel := context.WithCancel(context.Background())
251 d.cancel = cancel
252 agent := d.sideAgent
253 d.mu.Unlock()
254
255 go func() {
256 err := agent.Prompt(ctx, question, nil, func(ev core.AgentEvent) {
257 d.handleAgentEvent(turnIdx, ev)
258 if invalidate != nil {
259 invalidate()
260 }
261 })
262 errMsg := ""
263 if err != nil && ctx.Err() == nil {
264 errMsg = err.Error()
265 }
266 d.completeTurn(turnIdx, errMsg)
267 if invalidate != nil {
268 invalidate()
269 }
270 }()
271}
272
273func newBtwAgent(main *core.Agent, system, model string) *core.Agent {
274 agent := core.NewAgent(main.Client, model, system, main.Tools)
275 agent.MaxSteps = main.MaxSteps
276 agent.Reasoning = main.Reasoning
277 agent.Temperature = main.Temperature
278 agent.MaxTokens = main.MaxTokens
279 agent.BeforeToolExecute = main.BeforeToolExecute
280 agent.BeforeTurn = main.BeforeTurn
281 agent.BeforeAssistantMessage = main.BeforeAssistantMessage
282 agent.MaxRetries = main.MaxRetries
283 agent.RetryBaseDelay = main.RetryBaseDelay
284 agent.OnEvent = main.OnEvent
285 agent.SetMessages(main.Messages())
286 return agent
287}
288
289func (d *btwDialog) handleAgentEvent(turnIdx int, ev core.AgentEvent) {
290 d.mu.Lock()
291 defer d.mu.Unlock()
292 if turnIdx < 0 || turnIdx >= len(d.turns) {
293 return
294 }
295 turn := &d.turns[turnIdx]
296 switch e := ev.(type) {
297 case core.EvTextDelta:
298 turn.Assistant += e.Delta
299 case core.EvToolUseStart:
300 turn.Tools = append(turn.Tools, tui.ToolCallView{ID: e.ID, Name: e.Name, Streaming: true})
301 case core.EvToolUseArgs:
302 if tool := findBtwTool(turn, e.ID); tool != nil {
303 tool.RawJSONBuf += e.Delta
304 if path, ok, _ := tui.ExtractPartialStringField(tool.RawJSONBuf, "path"); ok {
305 tool.LivePath = path
306 } else if path, ok, _ := tui.ExtractPartialStringField(tool.RawJSONBuf, "file_path"); ok {
307 tool.LivePath = path
308 }
309 }
310 case core.EvToolUseEnd:
311 if tool := findBtwTool(turn, e.ID); tool != nil {
312 tool.Streaming = false
313 }
314 case core.EvToolCall:
315 tool := findBtwTool(turn, e.ID)
316 if tool == nil {
317 turn.Tools = append(turn.Tools, tui.ToolCallView{ID: e.ID, Name: e.Name})
318 tool = &turn.Tools[len(turn.Tools)-1]
319 }
320 tool.Name = e.Name
321 tool.Args = tui.ShortArgs(e.Name, e.Args)
322 if tool.RawJSONBuf == "" {
323 tool.RawJSONBuf = string(e.Args)
324 }
325 tool.Streaming = false
326 case core.EvToolResult:
327 if tool := findBtwTool(turn, e.ID); tool != nil {
328 tool.Done = true
329 tool.Error = e.Result.IsError
330 var text strings.Builder
331 for _, content := range e.Result.Content {
332 if block, ok := content.(provider.TextBlock); ok {
333 if text.Len() > 0 {
334 text.WriteString("\n")
335 }
336 text.WriteString(block.Text)
337 }
338 }
339 tool.Result = text.String()
340 }
341 }
342}
343
344func findBtwTool(turn *btwTurn, id string) *tui.ToolCallView {
345 for j := range turn.Tools {
346 if turn.Tools[j].ID == id {
347 return &turn.Tools[j]
348 }
349 }
350 return nil
351}
352
353// completeTurn records an error, if any, and clears the loading state.
354func (d *btwDialog) completeTurn(idx int, errMsg string) {
355 d.mu.Lock()
356 defer d.mu.Unlock()
357 if idx < 0 || idx >= len(d.turns) {
358 return
359 }
360 d.turns[idx].Err = errMsg
361 d.loading = false
362 d.cancel = nil
363}
364
365func renderBtwConfirmation(th tui.Theme, width int, btw *btwDialog, confirm *confirmDialog) []string {
366 rows := padDialogFrame(btw.Render(th, width))
367 rows = append(rows, "")
368 return append(rows, padDialogFrame(confirm.Render(th, width))...)
369}
370
371// Render returns the side-chat panel lines. Called every frame
372// while active.
373func (d *btwDialog) Render(th tui.Theme, width int) []string {
374 d.mu.Lock()
375 defer d.mu.Unlock()
376 if !d.active {
377 return nil
378 }
379
380 var out []string
381 out = append(out, frameHeaderColor(th, "btw - side chat (esc closes; nothing is added to the main thread)", width, th.Accent))
382
383 if len(d.turns) == 0 && !d.loading {
384 out = append(out, " "+th.FG256(th.Muted, "ask anything; replies stay private to this side chat."))
385 }
386
387 for _, t := range d.turns {
388 out = append(out, "")
389 out = append(out, btwUserBubbleRows(th, t.User, width-2, d.compactMode)...)
390 if len(t.Tools) > 0 {
391 // Match the main transcript's inter-message separator between
392 // the user bubble and the first tool box.
393 out = append(out, "")
394 }
395 for _, tool := range t.Tools {
396 out = append(out, d.toolView.RenderToolCall(tool, width)...)
397 }
398 if t.Assistant != "" {
399 out = append(out, "")
400 out = append(out, renderDialogMarkdownRows(t.Assistant, th, width)...)
401 }
402 if t.Err != "" {
403 out = append(out, wrapDialogTextRows(th.FG256(th.Error, "✖ "+t.Err), width)...)
404 }
405 }
406
407 if d.loading && d.spin != nil {
408 out = append(out, "")
409 // Match the main chat busy prefix shape: spinner glyph,
410 // rotating funny-line, elapsed seconds, then a muted hint
411 // that esc cancels.
412 prefix := fmt.Sprintf("%s %s - %s",
413 th.FG256(th.Assistant, d.spin.Frame()),
414 th.FG256(th.Assistant, d.spin.Message()),
415 th.FG256(th.Muted, d.spin.Elapsed().String()),
416 )
417 out = append(out, " "+prefix+" "+th.FG256(th.Muted, "(esc cancels)"))
418 }
419
420 out = append(out, "")
421 if d.editor != nil {
422 // Render at width-2 to match the two-cell left indent applied
423 // below. CursorPos uses the same width so the reported cursor
424 // column matches the wrapped layout shown on screen.
425 d.editor.Prompt = th.AccentBar(th.Accent)
426 if d.lineInput {
427 d.editor.Prompt = ""
428 }
429 edLines, _, _ := d.editor.Render(width - 2)
430 for _, l := range edLines {
431 // Indent the editor body so it lines up with the side-chat
432 // content column. Editor's prompt already includes a left
433 // marker, so just two cells of pad.
434 out = append(out, " "+l)
435 }
436 out = append(out, "") // breathing room between editor and frame rule
437 }
438 out = append(out, frameRuleColor(th, width, th.Accent))
439 return out
440}
441
442// CursorRow / CursorCol report where the dialog wants the terminal
443// cursor placed within its render output, so the parent can position
444// the actual terminal cursor on the editor input. Returns (-1, -1)
445// when the dialog isn't active or has no editor.
446func (d *btwDialog) CursorPos(width int) (row, col int) {
447 d.mu.Lock()
448 defer d.mu.Unlock()
449 if !d.active || d.editor == nil {
450 return -1, -1
451 }
452 // Reproduce render's structure to find where the editor sits.
453 // Note: the parent (interactive.go) wraps every dialog with
454 // padDialogFrame. It only injects a blank row after the frame
455 // header when Render did not already put one there. With existing
456 // turns or a loading spinner, Render's first body row is already
457 // blank, so counting an extra pad row would place the cursor one
458 // row too low.
459 editorOffset := 1 // header
460 if len(d.turns) == 0 && !d.loading {
461 editorOffset++ // padDialogFrame's post-header blank
462 editorOffset++ // muted "ask anything..." line
463 }
464 for _, t := range d.turns {
465 editorOffset++ // blank
466 editorOffset += len(btwUserBubbleRows(d.theme, t.User, width-2, d.compactMode))
467 if len(t.Tools) > 0 {
468 editorOffset++ // main transcript's user-to-tool separator
469 }
470 for _, tool := range t.Tools {
471 editorOffset += len(d.toolView.RenderToolCall(tool, width))
472 }
473 if t.Assistant != "" {
474 editorOffset++ // blank
475 editorOffset += len(renderDialogMarkdownRows(t.Assistant, d.theme, width))
476 }
477 if t.Err != "" {
478 editorOffset += len(wrapDialogTextRows(d.theme.FG256(d.theme.Error, "✖ "+t.Err), width))
479 }
480 }
481 if d.loading {
482 editorOffset++ // blank
483 editorOffset++ // spinner line
484 }
485 editorOffset++ // pre-editor blank
486 d.editor.Prompt = d.theme.AccentBar(d.theme.Accent)
487 if d.lineInput {
488 d.editor.Prompt = ""
489 }
490 _, eRow, eCol := d.editor.Render(width - 2)
491 return editorOffset + eRow, eCol + 2 /* matches render indent */
492}
493
494// btwUserBubbleRows renders a user message inside the /btw dialog
495// using the same bubble layout the main chat uses (full-width tinted
496// panel, left-edge ▌ bar, padding rows above and below). The frame
497// padding is the caller's job; bubbleWidth is the available row
498// width inside the frame.
499func btwUserBubbleRows(th tui.Theme, text string, bubbleWidth int, compactMode bool) []string {
500 const leftGutter = 0
501 const rightGutter = 2
502 innerWidth := bubbleWidth - 2 - leftGutter - rightGutter // 2 = bar's two cells
503 if innerWidth < 1 {
504 innerWidth = 1
505 }
506 bar := th.BG(th.UserBubbleBG, th.FG256(th.Accent, "▌ "))
507 row := func(content string) string {
508 inner := strings.Repeat(" ", leftGutter) + content
509 return " " + bar + th.UserBubble(inner, bubbleWidth-2)
510 }
511 if compactMode {
512 innerWidth = bubbleWidth - 2
513 if innerWidth < 1 {
514 innerWidth = 1
515 }
516 row = func(content string) string {
517 return " " + th.FG256(th.Accent, "▌ ") + th.FG256(th.Muted, content)
518 }
519 }
520 var bubble []string
521 for _, l := range strings.Split(text, "\n") {
522 for _, w := range tui.WrapANSILine(l, innerWidth) {
523 bubble = append(bubble, row(w))
524 }
525 }
526 if len(bubble) == 0 {
527 return nil
528 }
529 if compactMode {
530 return bubble
531 }
532 out := make([]string, 0, len(bubble)+2)
533 out = append(out, row(""))
534 out = append(out, bubble...)
535 out = append(out, row(""))
536 return out
537}
538
539// errMessage is a tiny helper for the future when we want to surface
540// retryable failures in a styled way.
541func errMessage(err error) string {
542 if err == nil {
543 return ""
544 }
545 return fmt.Sprintf("error: %s", err.Error())
546}