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