1package modes
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "strings"
8 "sync"
9 "time"
10
11 "github.com/patriceckhart/zot/internal/agent/tools"
12 "github.com/patriceckhart/zot/internal/auth"
13 "github.com/patriceckhart/zot/internal/core"
14 "github.com/patriceckhart/zot/internal/provider"
15 "github.com/patriceckhart/zot/internal/tui"
16)
17
18// InteractiveConfig configures the interactive loop.
19type InteractiveConfig struct {
20 Terminal tui.Terminal
21 Theme tui.Theme
22 Model string
23 Provider string
24 AuthMethod string // "apikey" | "oauth" — used to tag cost as (sub) in status bar
25 BaseURL string
26 Reasoning string
27 SystemPrompt string
28 Tools core.Registry
29 MaxSteps int
30 CWD string
31
32 // Agent is optional. If nil, zot opens without credentials; the
33 // user must /login before they can prompt.
34 Agent *core.Agent
35
36 InitialInput string
37
38 // Auth is required. When the user runs /login, Interactive talks to
39 // AuthManager to open a browser and wait for the callback.
40 AuthManager *auth.Manager
41 // BuildAgent is called after a successful login to (re)construct the
42 // agent with the fresh credential. It returns the new agent and
43 // the concrete provider/model in use.
44 BuildAgent func() (*core.Agent, string, string, error)
45
46 // BuildAgentFor rebuilds the agent with an explicit provider/model
47 // override (used by the /model picker when switching providers).
48 // If providerOverride is empty, the current provider is kept.
49 BuildAgentFor func(providerOverride, modelOverride string) (*core.Agent, string, string, error)
50
51 // ZotHome is the root directory for sessions/, used by /sessions.
52 ZotHome string
53
54 // Sandbox is the shared sandbox pointer. Toggled by /lock and /unlock.
55 Sandbox *tools.Sandbox
56
57 // LoadSession swaps the current session for the one at path. The
58 // callback returns the new agent message slice so the TUI can invalidate.
59 LoadSession func(path string) error
60
61 // PersistModel is called whenever the user switches model or provider.
62 // It should update config.json and (if there's an active session)
63 // write a new meta row so resume picks up the same model.
64 PersistModel func(providerName, model string)
65
66 OnAssistant func(m provider.Message)
67 OnToolResult func(id string, r core.ToolResult)
68}
69
70// Interactive is the TUI chat loop.
71type Interactive struct {
72 cfg InteractiveConfig
73 view *tui.View
74 ed *tui.Editor
75 rend *tui.Renderer
76
77 mu sync.Mutex
78 agent *core.Agent
79 streaming strings.Builder
80 streamOn bool
81 toolCalls map[string]*tui.ToolCallView
82 toolOrder []string
83 statusErr string
84 statusOK string
85 helpBlock []string // rendered above the chat when /help was typed
86 cumUsage provider.Usage
87 lastCtxInput int // input_tokens of the most recent turn — approximates current context size
88 busy bool
89 dirty chan struct{}
90 cancelTurn context.CancelFunc
91 scrollOffset int // rows from the bottom; 0 = pinned to latest
92
93 // Messages typed while a turn is in flight. Each is delivered as
94 // its own follow-up turn once the current one finishes. Rendered
95 // above the status bar as "sliding in: ..." chips.
96 queued []string
97
98 // runCtx is the top-level context passed to Run(). Follow-up turns
99 // drained from `queued` are started against this context so they
100 // survive past the ctx of the key event that enqueued them.
101 runCtx context.Context
102
103 // autoCompacting is true while a model-triggered compaction is in
104 // flight. Surfaced in the status bar so the user can tell a
105 // condense pass from a regular assistant turn.
106 autoCompacting bool
107
108 dialog *loginDialog
109 modelDialog *modelDialog
110 sessionDialog *sessionDialog
111 suggest *slashSuggester
112 spin *spinner
113}
114
115// NewInteractive constructs an Interactive from cfg.
116func NewInteractive(cfg InteractiveConfig) *Interactive {
117 i := &Interactive{
118 cfg: cfg,
119 view: &tui.View{
120 Theme: cfg.Theme,
121 ImageProto: tui.DetectImageProtocol(),
122 },
123 ed: tui.NewEditor(cfg.Theme.FG256(cfg.Theme.Accent, "▌ ")),
124 rend: tui.NewRenderer(cfg.Terminal),
125 toolCalls: map[string]*tui.ToolCallView{},
126 dirty: make(chan struct{}, 8),
127 dialog: newLoginDialog(),
128 modelDialog: newModelDialog(),
129 sessionDialog: newSessionDialog(),
130 suggest: newSlashSuggester(),
131 spin: newSpinner(),
132 }
133 if cfg.Agent != nil {
134 i.agent = cfg.Agent
135 i.view.Messages = cfg.Agent.Messages()
136 }
137 return i
138}
139
140// Run blocks until the user quits.
141func (i *Interactive) Run(ctx context.Context) error {
142 i.runCtx = ctx
143 term := i.cfg.Terminal
144 restore, err := term.EnterRaw()
145 if err != nil {
146 return err
147 }
148 defer restore()
149
150 _, _ = term.Write([]byte(tui.SeqBracketedPasteOn))
151 _, _ = term.Write([]byte(tui.SeqAltScreenOn))
152 defer term.Write([]byte(tui.SeqAltScreenOff + tui.SeqBracketedPasteOff + tui.SeqShowCursor))
153
154 cols, rows := term.Size()
155 i.rend.Resize(cols, rows)
156 term.OnResize(func() {
157 c, r := term.Size()
158 i.rend.Resize(c, r)
159 i.invalidate()
160 })
161
162 if i.cfg.InitialInput != "" {
163 i.ed.SetValue(i.cfg.InitialInput)
164 }
165
166 // No credential at startup? Auto-open the login dialog, and mark
167 // the status line. The user can Esc out of the dialog if they
168 // want to dismiss it (e.g. to check /help or /exit first).
169 if i.agent == nil {
170 i.statusErr = "not logged in. pick a login method below or press esc to dismiss."
171 i.dialog.Open()
172 }
173
174 // Input goroutine.
175 keys := make(chan tui.Key, 8)
176 go func() {
177 reader := tui.NewReaderWithPeek(term.ReadByte, term.PeekByteTimeout)
178 for {
179 k, err := reader.Read()
180 if err != nil {
181 return
182 }
183 keys <- k
184 }
185 }()
186
187 // Subscribe to auth events.
188 var authEvents <-chan auth.Event
189 if i.cfg.AuthManager != nil {
190 authEvents = i.cfg.AuthManager.Events()
191 }
192
193 // Animation ticker: drives spinner and dialog-related redraws when
194 // nothing else changed. 120ms is slow enough that highlighting a huge
195 // transcript doesn't spin the cpu.
196 tick := time.NewTicker(120 * time.Millisecond)
197 defer tick.Stop()
198
199 // Redraw throttle: coalesce bursts of invalidate() calls so we paint
200 // at most once every redrawMinInterval. Huge tool-result dumps can
201 // fire hundreds of invalidations while the user is typing; without
202 // this, the input goroutine never gets CPU and keystrokes lag.
203 const redrawMinInterval = 16 * time.Millisecond
204 var lastRedraw time.Time
205 var pendingRedraw bool
206 var pendingTimer *time.Timer
207
208 drainPending := func() {
209 if pendingTimer != nil {
210 pendingTimer.Stop()
211 pendingTimer = nil
212 }
213 if pendingRedraw {
214 pendingRedraw = false
215 lastRedraw = time.Now()
216 i.redraw()
217 }
218 }
219
220 requestRedraw := func() {
221 since := time.Since(lastRedraw)
222 if since >= redrawMinInterval {
223 lastRedraw = time.Now()
224 i.redraw()
225 return
226 }
227 if pendingRedraw {
228 return // already scheduled
229 }
230 pendingRedraw = true
231 wait := redrawMinInterval - since
232 if pendingTimer == nil {
233 pendingTimer = time.AfterFunc(wait, func() {
234 // Poke the dirty channel; the main loop will call drainPending().
235 i.invalidate()
236 })
237 } else {
238 pendingTimer.Reset(wait)
239 }
240 }
241
242 i.invalidate()
243
244 for {
245 select {
246 case <-ctx.Done():
247 return ctx.Err()
248 case k := <-keys:
249 if done := i.handleKey(ctx, k); done {
250 return nil
251 }
252 i.invalidate()
253 case ev := <-authEvents:
254 i.handleAuthEvent(ev)
255 i.invalidate()
256 case <-i.dirty:
257 requestRedraw()
258 case <-tick.C:
259 if i.busy || i.dialog.Active() || i.modelDialog.Active() || i.sessionDialog.Active() {
260 drainPending()
261 requestRedraw()
262 }
263 }
264 }
265}
266
267func (i *Interactive) invalidate() {
268 select {
269 case i.dirty <- struct{}{}:
270 default:
271 }
272}
273
274// lastCols returns the current terminal width in columns.
275func (i *Interactive) lastCols() int {
276 cols, _ := i.cfg.Terminal.Size()
277 return cols
278}
279
280// chatPage returns the number of chat rows currently visible, used
281// as the page size for PageUp/PageDown.
282func (i *Interactive) chatPage() int {
283 _, rows := i.cfg.Terminal.Size()
284 p := rows - 6 // rough reservation for status + editor + a dialog line
285 if p < 4 {
286 p = 4
287 }
288 return p
289}
290
291// scrollBy adjusts the scroll offset. Positive = up (into history).
292func (i *Interactive) scrollBy(delta int) {
293 i.mu.Lock()
294 i.scrollOffset += delta
295 if i.scrollOffset < 0 {
296 i.scrollOffset = 0
297 }
298 i.mu.Unlock()
299 i.invalidate()
300}
301
302// scrollToBottom pins the view to the latest content.
303func (i *Interactive) scrollToBottom() {
304 i.mu.Lock()
305 i.scrollOffset = 0
306 i.mu.Unlock()
307 i.invalidate()
308}
309
310func (i *Interactive) redraw() {
311 i.mu.Lock()
312 defer i.mu.Unlock()
313
314 cols, _ := i.cfg.Terminal.Size()
315 if i.agent != nil {
316 i.view.Messages = i.agent.Messages()
317 } else {
318 i.view.Messages = nil
319 }
320 i.view.Streaming = i.streaming.String()
321 i.view.StreamingActive = i.streamOn
322 // Belt and suspenders: if the transcript's last message is already an
323 // assistant message, the streaming view is stale (EvAssistantMessage may
324 // not have fired yet) — suppress it to avoid double-rendering the reply.
325 if n := len(i.view.Messages); n > 0 && i.view.Messages[n-1].Role == provider.RoleAssistant {
326 i.view.StreamingActive = false
327 }
328 // Live tool-call view: only shown while a turn is in flight. Once
329 // the agent is idle, every tool call has already been folded into
330 // the transcript (as assistant.ToolCallBlock + a tool-role message),
331 // so showing v.ToolCalls a second time would duplicate them below
332 // the final assistant text — which looks like the summary came
333 // "before" the tools.
334 i.view.ToolCalls = i.view.ToolCalls[:0]
335 if i.busy {
336 for _, id := range i.toolOrder {
337 if tc, ok := i.toolCalls[id]; ok {
338 i.view.ToolCalls = append(i.view.ToolCalls, *tc)
339 }
340 }
341 }
342 i.view.Err = i.statusErr
343
344 chat := i.view.Build(cols)
345
346 // Welcome banner: shown at the top of the chat area when there is
347 // no transcript yet. Disappears after the first message is sent.
348 if len(i.view.Messages) == 0 && !i.streamOn && len(i.toolOrder) == 0 {
349 chat = append(welcomeBanner(i.cfg.Theme), chat...)
350 }
351
352 // /help block: rendered above the welcome / transcript when active.
353 if len(i.helpBlock) > 0 {
354 chat = append(append([]string(nil), i.helpBlock...), chat...)
355 }
356
357 if i.statusOK != "" {
358 chat = append(chat, i.cfg.Theme.FG256(i.cfg.Theme.Tool, "✓ "+i.statusOK), "")
359 }
360
361 // Dialogs (login or model picker) render between chat and the editor.
362 var dialog []string
363 switch {
364 case i.dialog.Active():
365 dialog = i.dialog.Render(i.cfg.Theme, cols)
366 case i.modelDialog.Active():
367 dialog = i.modelDialog.Render(i.cfg.Theme, cols)
368 case i.sessionDialog.Active():
369 dialog = i.sessionDialog.Render(i.cfg.Theme, cols)
370 }
371
372 // Slash-command autocomplete: popup above the status line, only
373 // when the editor starts with "/" and no dialog is already open.
374 var suggest []string
375 currentInput := i.ed.Value()
376 if len(dialog) == 0 && i.suggest.Active(currentInput) && !i.busy {
377 suggest = i.suggest.Render(currentInput, i.cfg.Theme, cols)
378 }
379
380 // Busy prefix shown at the far left of the status bar.
381 var busyPrefix string
382 if i.busy {
383 busyPrefix = fmt.Sprintf("%s %s · %s",
384 i.cfg.Theme.FG256(i.cfg.Theme.Spinner, i.spin.Frame()),
385 i.cfg.Theme.FG256(i.cfg.Theme.Spinner, i.spin.Message()),
386 i.cfg.Theme.FG256(i.cfg.Theme.Muted, i.spin.Elapsed().String()),
387 )
388 }
389
390 ctxMax := 0
391 if m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model); err == nil {
392 ctxMax = m.ContextWindow
393 }
394 status := tui.StatusBar(tui.StatusBarParams{
395 Theme: i.cfg.Theme,
396 Provider: i.cfg.Provider,
397 Model: i.cfg.Model,
398 Busy: i.busy,
399 BusyPrefix: busyPrefix,
400 CWD: i.cfg.CWD,
401 Locked: i.cfg.Sandbox.Locked(),
402 Usage: i.cumUsage,
403 Subscription: i.cfg.AuthMethod == "oauth",
404 ContextUsed: i.lastCtxInput,
405 ContextMax: ctxMax,
406 AutoCompacting: i.autoCompacting,
407 Cols: cols,
408 })
409 edLines, curR, curC := i.ed.Render(cols)
410
411 // "Sliding in" chips for messages the user typed while a turn is
412 // in flight. Shown directly above the status bar so they're close
413 // to the editor but don't push the chat around.
414 var queue []string
415 if len(i.queued) > 0 {
416 for _, q := range i.queued {
417 label := i.cfg.Theme.FG256(i.cfg.Theme.Accent, "▸ sliding in: ")
418 text := truncateLine(q, cols-15)
419 queue = append(queue, label+i.cfg.Theme.FG256(i.cfg.Theme.Muted, text))
420 }
421 }
422
423 // Bottom-sticky sections (always visible, never scroll).
424 bottom := make([]string, 0, len(dialog)+len(suggest)+len(queue)+len(edLines)+1)
425 bottom = append(bottom, dialog...)
426 bottom = append(bottom, suggest...)
427 bottom = append(bottom, queue...)
428 bottom = append(bottom, status)
429 bottom = append(bottom, edLines...)
430
431 _, rows := i.cfg.Terminal.Size()
432 chatRows := rows - len(bottom)
433 if chatRows < 1 {
434 chatRows = 1
435 }
436
437 // Apply scroll offset to the chat slice.
438 maxOffset := len(chat) - chatRows
439 if maxOffset < 0 {
440 maxOffset = 0
441 }
442 if i.scrollOffset > maxOffset {
443 i.scrollOffset = maxOffset
444 }
445 if i.scrollOffset < 0 {
446 i.scrollOffset = 0
447 }
448
449 var visibleChat []string
450 if len(chat) <= chatRows {
451 visibleChat = chat
452 } else {
453 end := len(chat) - i.scrollOffset
454 start := end - chatRows
455 if start < 0 {
456 start = 0
457 }
458 visibleChat = chat[start:end]
459 }
460
461 // A tiny "scrolled up" indicator in the top-right of the chat pane
462 // so you know you're not at the bottom.
463 if i.scrollOffset > 0 && len(visibleChat) > 0 {
464 note := i.cfg.Theme.FG256(i.cfg.Theme.Muted,
465 fmt.Sprintf(" ↑ %d lines more below (end to jump)", i.scrollOffset))
466 visibleChat = append([]string{note}, visibleChat...)
467 if len(visibleChat) > chatRows {
468 visibleChat = visibleChat[:chatRows]
469 }
470 }
471
472 frame := make([]string, 0, len(visibleChat)+len(bottom))
473 frame = append(frame, visibleChat...)
474 frame = append(frame, bottom...)
475
476 cursorRow := len(visibleChat) + len(dialog) + len(suggest) + len(queue) + 1 + curR
477 cursorCol := curC
478 i.rend.Draw(frame, cursorRow, cursorCol)
479}
480
481// truncateLine shortens s so it fits within n display cells, with an
482// ellipsis if trimmed. Used by the "sliding in" chips so a pasted
483// novel doesn't blow past the status line.
484func truncateLine(s string, n int) string {
485 if n <= 0 {
486 return ""
487 }
488 // Collapse newlines — chips are single line.
489 s = strings.ReplaceAll(s, "\n", " ↩ ")
490 runes := []rune(s)
491 if len(runes) <= n {
492 return s
493 }
494 if n <= 1 {
495 return "…"
496 }
497 return string(runes[:n-1]) + "…"
498}
499
500func (i *Interactive) handleKey(ctx context.Context, k tui.Key) (done bool) {
501 // Dialogs consume keys while open (except ctrl+c, which always closes them).
502 if i.dialog.Active() {
503 if k.Kind == tui.KeyCtrlC {
504 i.dialog.Close()
505 if i.cfg.AuthManager != nil {
506 i.cfg.AuthManager.CancelOAuth()
507 }
508 return false
509 }
510 act := i.dialog.HandleKey(k)
511 if act.StartAPIKey {
512 i.startAPIKeyFlow(act.Provider)
513 }
514 if act.StartOAuth {
515 i.startOAuthFlow(act.Provider)
516 }
517 return false
518 }
519 if i.modelDialog.Active() {
520 if k.Kind == tui.KeyCtrlC {
521 i.modelDialog.Close()
522 return false
523 }
524 act := i.modelDialog.HandleKey(k)
525 if act.Select {
526 i.applyModelSelection(act.Provider, act.Model)
527 }
528 return false
529 }
530 if i.sessionDialog.Active() {
531 if k.Kind == tui.KeyCtrlC {
532 i.sessionDialog.Close()
533 return false
534 }
535 act := i.sessionDialog.HandleKey(k)
536 if act.Select {
537 i.applySessionSelection(act.Path)
538 }
539 return false
540 }
541
542 // Global keys.
543 switch k.Kind {
544 case tui.KeyCtrlC:
545 if i.busy && i.cancelTurn != nil {
546 i.cancelTurn()
547 return false
548 }
549 return true
550 case tui.KeyEsc:
551 // Esc interrupts a running turn. When idle, fall through so the
552 // editor can clear itself.
553 if i.busy && i.cancelTurn != nil {
554 i.cancelTurn()
555 return false
556 }
557 case tui.KeyCtrlD:
558 if i.ed.IsEmpty() && !i.busy {
559 return true
560 }
561 case tui.KeyCtrlL:
562 i.rend.Clear()
563 i.invalidate()
564 return false
565 case tui.KeyCtrlO:
566 // Toggle expansion of collapsed tool results. Affects every tool
567 // call in the transcript — press again to re-collapse.
568 i.mu.Lock()
569 i.view.ExpandAll = !i.view.ExpandAll
570 i.mu.Unlock()
571 i.invalidate()
572 return false
573 case tui.KeyPageUp:
574 i.scrollBy(+i.chatPage())
575 return false
576 case tui.KeyPageDown:
577 i.scrollBy(-i.chatPage())
578 return false
579 case tui.KeyUp:
580 // Wheel-up in alt screen sends Up arrows on most terminals. When the
581 // editor is empty and we're not busy, use that for chat scroll-up.
582 if i.ed.IsEmpty() && !i.busy {
583 i.scrollBy(+3)
584 return false
585 }
586 case tui.KeyDown:
587 if i.ed.IsEmpty() && !i.busy {
588 if i.scrollOffset > 0 {
589 i.scrollBy(-3)
590 }
591 return false
592 }
593 }
594
595 // Note: we intentionally do NOT gate the editor on i.busy here.
596 // Typing while the agent is working is supported — submitted
597 // messages are queued and delivered as follow-up turns when the
598 // current turn ends. See the submit handler below.
599
600 if k.Kind == tui.KeyEnter && k.Alt {
601 i.ed.HandleKey(tui.Key{Kind: tui.KeyRune, Rune: '\n', Alt: true})
602 return false
603 }
604
605 // Slash suggestions: intercept up/down/tab/enter when the popup is visible.
606 if i.suggest.Active(i.ed.Value()) {
607 switch k.Kind {
608 case tui.KeyUp:
609 i.suggest.Up()
610 return false
611 case tui.KeyDown:
612 i.suggest.Down()
613 return false
614 case tui.KeyTab:
615 if name := i.suggest.Selection(i.ed.Value()); name != "" {
616 i.ed.SetValue(name)
617 i.suggest.Reset()
618 }
619 return false
620 case tui.KeyEnter:
621 // Enter on an ambiguous or partial slash prefix: complete to the
622 // currently highlighted command and run it. That way typing
623 // "/lo" + enter picks whichever of /login or /logout is selected
624 // in the popup instead of submitting "/lo" as unknown. Also
625 // clear the editor so the command doesn't linger after the
626 // dialog opens/closes.
627 if name := i.suggest.Selection(i.ed.Value()); name != "" {
628 i.ed.PushHistory(name)
629 i.ed.Clear()
630 i.suggest.Reset()
631 return i.runSlash(ctx, name)
632 }
633 case tui.KeyEsc:
634 i.ed.Clear()
635 i.suggest.Reset()
636 return false
637 }
638 }
639
640 if submit := i.ed.HandleKey(k); submit {
641 text := strings.TrimRight(i.ed.Value(), "\n")
642 if text == "" {
643 return false
644 }
645 i.ed.PushHistory(text)
646 i.ed.Clear()
647 i.suggest.Reset()
648
649 if looksLikeSlashCommand(text) {
650 if !isKnownSlashCommand(text) {
651 head := text
652 if idx := strings.IndexAny(text, " \t"); idx >= 0 {
653 head = text[:idx]
654 }
655 i.mu.Lock()
656 i.statusErr = "unknown command " + head + " — type /help to see the list"
657 i.statusOK = ""
658 i.mu.Unlock()
659 return false
660 }
661 // Slash commands need a quiet state (they may swap models,
662 // compact the transcript, open dialogs, etc). Refuse while
663 // a turn is in flight — esc / ctrl+c cancels first.
664 i.mu.Lock()
665 busy := i.busy
666 i.mu.Unlock()
667 if busy {
668 i.mu.Lock()
669 i.statusErr = "cancel the current turn (esc) before running a slash command"
670 i.mu.Unlock()
671 return false
672 }
673 return i.runSlash(ctx, text)
674 }
675
676 if i.agent == nil {
677 i.mu.Lock()
678 i.statusErr = "not logged in. type /login first."
679 i.mu.Unlock()
680 return false
681 }
682 // If a turn is already in flight, queue this prompt instead of
683 // starting a second one. The drain loop at the end of startTurn
684 // will pick it up when the current turn finishes.
685 i.mu.Lock()
686 if i.busy {
687 i.queued = append(i.queued, text)
688 i.mu.Unlock()
689 i.invalidate()
690 return false
691 }
692 i.mu.Unlock()
693 i.startTurn(ctx, text)
694 }
695 return false
696}
697
698func (i *Interactive) runSlash(ctx context.Context, cmd string) (done bool) {
699 parts := strings.Fields(cmd)
700 switch parts[0] {
701 case "/exit":
702 return true
703 case "/clear":
704 if i.agent != nil {
705 i.agent.SetMessages(nil)
706 }
707 i.mu.Lock()
708 i.toolCalls = map[string]*tui.ToolCallView{}
709 i.toolOrder = nil
710 i.statusErr = ""
711 i.statusOK = ""
712 i.helpBlock = nil
713 i.mu.Unlock()
714 case "/help":
715 i.mu.Lock()
716 i.helpBlock = renderHelpBlock(i.cfg.Theme, i.lastCols())
717 i.statusErr = ""
718 i.statusOK = ""
719 i.mu.Unlock()
720 case "/login":
721 i.dialog.Open()
722 case "/logout":
723 target := "all"
724 if len(parts) >= 2 {
725 target = parts[1]
726 }
727 i.doLogout(target)
728 case "/model":
729 if len(parts) >= 2 {
730 i.applyModelSelection("", parts[1])
731 } else {
732 i.modelDialog.Open(i.cfg.Model)
733 }
734 case "/sessions":
735 i.sessionDialog.Open(i.cfg.ZotHome, i.cfg.CWD)
736 case "/compact":
737 i.runCompact(ctx, false)
738 case "/lock":
739 if i.cfg.Sandbox == nil {
740 i.mu.Lock()
741 i.statusErr = "sandbox not available in this build"
742 i.mu.Unlock()
743 break
744 }
745 i.cfg.Sandbox.Lock()
746 i.mu.Lock()
747 i.statusOK = "locked to " + i.cfg.CWD + " (tools cannot touch paths outside this directory)"
748 i.statusErr = ""
749 i.mu.Unlock()
750 case "/unlock":
751 if i.cfg.Sandbox == nil {
752 i.mu.Lock()
753 i.statusErr = "sandbox not available in this build"
754 i.mu.Unlock()
755 break
756 }
757 i.cfg.Sandbox.Unlock()
758 i.mu.Lock()
759 i.statusOK = "unlocked"
760 i.statusErr = ""
761 i.mu.Unlock()
762 default:
763 i.mu.Lock()
764 i.statusErr = "unknown command: " + parts[0]
765 i.mu.Unlock()
766 }
767 return false
768}
769
770// doLogout clears credentials for the given provider (or all providers)
771// from auth.json. If the active agent was using those credentials, it
772// is torn down so the user is forced through /login before their next
773// prompt.
774//
775// target: "anthropic" | "openai" | "all"
776func (i *Interactive) doLogout(target string) {
777 if i.cfg.AuthManager == nil {
778 i.mu.Lock()
779 i.statusErr = "no auth manager configured"
780 i.mu.Unlock()
781 return
782 }
783 store := i.cfg.AuthManager.Store()
784 if store == nil {
785 i.mu.Lock()
786 i.statusErr = "auth store is not available"
787 i.mu.Unlock()
788 return
789 }
790
791 var providers []string
792 switch target {
793 case "", "all":
794 providers = []string{"anthropic", "openai"}
795 case "anthropic", "openai":
796 providers = []string{target}
797 default:
798 i.mu.Lock()
799 i.statusErr = "unknown provider: " + target + " (use anthropic, openai, or all)"
800 i.mu.Unlock()
801 return
802 }
803
804 var errs []string
805 clearedCurrent := false
806 for _, p := range providers {
807 if err := store.Clear(p); err != nil {
808 errs = append(errs, p+": "+err.Error())
809 continue
810 }
811 if p == i.cfg.Provider {
812 clearedCurrent = true
813 }
814 }
815
816 i.mu.Lock()
817 defer i.mu.Unlock()
818 if len(errs) > 0 {
819 i.statusErr = "logout errors: " + strings.Join(errs, "; ")
820 return
821 }
822 i.statusErr = ""
823 if clearedCurrent {
824 // The running agent was using a credential we just wiped. Drop
825 // it so prompts can't go out with the stale client, and hint at
826 // /login.
827 i.agent = nil
828 i.statusOK = "logged out of " + strings.Join(providers, ", ") + ". type /login to sign back in."
829 } else {
830 i.statusOK = "logged out of " + strings.Join(providers, ", ")
831 }
832}
833
834func (i *Interactive) startAPIKeyFlow(provider string) {
835 url, err := i.cfg.AuthManager.StartAPIKey(provider)
836 if err != nil {
837 i.dialog.ShowResult(false, err.Error())
838 return
839 }
840 i.dialog.ShowWaiting(url)
841}
842
843func (i *Interactive) startOAuthFlow(provider string) {
844 url, err := i.cfg.AuthManager.StartOAuth(provider)
845 if err != nil {
846 i.dialog.ShowResult(false, err.Error())
847 return
848 }
849 i.dialog.ShowWaiting(url)
850}
851
852// applyModelSelection switches the active model (and provider, if the
853// new model belongs to a different one). It rebuilds the underlying
854// client when needed so the provider wire-protocol matches.
855// applySessionSelection loads the given session via the cli-provided callback.
856func (i *Interactive) applySessionSelection(path string) {
857 if i.cfg.LoadSession == nil {
858 i.mu.Lock()
859 i.statusErr = "session loading is not wired in this build"
860 i.mu.Unlock()
861 return
862 }
863 if err := i.cfg.LoadSession(path); err != nil {
864 i.mu.Lock()
865 i.statusErr = err.Error()
866 i.mu.Unlock()
867 return
868 }
869 i.mu.Lock()
870 i.statusOK = "resumed session: " + path
871 i.statusErr = ""
872 i.scrollOffset = 0
873 i.mu.Unlock()
874}
875
876func (i *Interactive) applyModelSelection(prov, model string) {
877 if model == "" {
878 return
879 }
880 m, err := provider.FindModel(prov, model)
881 if err != nil {
882 i.mu.Lock()
883 i.statusErr = err.Error()
884 i.mu.Unlock()
885 return
886 }
887 // Same provider? Just swap the model on the existing agent.
888 if i.agent != nil && m.Provider == i.cfg.Provider {
889 i.mu.Lock()
890 i.cfg.Model = m.ID
891 i.agent.Model = m.ID
892 i.statusOK = "model: " + m.ID
893 i.statusErr = ""
894 i.mu.Unlock()
895 if i.cfg.PersistModel != nil {
896 i.cfg.PersistModel(i.cfg.Provider, m.ID)
897 }
898 return
899 }
900 // Different provider: rebuild agent (needs credentials for target provider).
901 if i.cfg.BuildAgentFor == nil {
902 i.mu.Lock()
903 i.statusErr = "cannot switch provider: no builder configured"
904 i.mu.Unlock()
905 return
906 }
907 ag, p, md, err := i.cfg.BuildAgentFor(m.Provider, m.ID)
908 if err != nil {
909 i.mu.Lock()
910 i.statusErr = err.Error()
911 i.mu.Unlock()
912 return
913 }
914 i.mu.Lock()
915 i.agent = ag
916 i.cfg.Provider = p
917 i.cfg.Model = md
918 i.statusOK = "switched to " + p + " / " + md
919 i.statusErr = ""
920 i.mu.Unlock()
921 if i.cfg.PersistModel != nil {
922 i.cfg.PersistModel(p, md)
923 }
924}
925
926func (i *Interactive) handleAuthEvent(ev auth.Event) {
927 switch ev.Kind {
928 case "started":
929 i.dialog.ShowWaiting(ev.URL)
930 case "browser_open":
931 // no-op
932 case "error":
933 i.dialog.ShowResult(false, ev.Message)
934 case "success":
935 // Rebuild the agent with the fresh credential.
936 ag, prov, model, err := i.cfg.BuildAgent()
937 if err != nil {
938 i.dialog.ShowResult(false, err.Error())
939 return
940 }
941 i.mu.Lock()
942 i.agent = ag
943 i.cfg.Provider = prov
944 i.cfg.Model = model
945 i.statusErr = ""
946 i.statusOK = "logged in to " + ev.Provider + " via " + ev.Method
947 i.mu.Unlock()
948 i.dialog.ShowResult(true, "")
949 }
950}
951
952// runCompact invokes core.Agent.Compact and reflects the progress in
953// the tui. It runs in a goroutine so the ui stays responsive; esc/ctrl+c
954// cancel via the same cancelTurn channel used for normal turns.
955//
956// When auto is true the spinner message is pinned to "condensing
957// history" and the status bar surfaces "(auto)" next to the context
958// percentage so it's obvious the system triggered this, not the user.
959func (i *Interactive) runCompact(parent context.Context, auto bool) {
960 if i.agent == nil {
961 i.mu.Lock()
962 i.statusErr = "not logged in. type /login first."
963 i.mu.Unlock()
964 return
965 }
966 ctx, cancel := context.WithCancel(parent)
967 i.mu.Lock()
968 i.busy = true
969 if auto {
970 i.spin.StartFixed("condensing history")
971 i.autoCompacting = true
972 i.statusOK = "condensing history… (esc to cancel)"
973 } else {
974 i.spin.Start()
975 i.statusOK = "compacting..."
976 }
977 i.cancelTurn = cancel
978 i.statusErr = ""
979 i.streaming.Reset()
980 i.streamOn = true
981 i.scrollOffset = 0
982 i.helpBlock = nil
983 i.mu.Unlock()
984 i.invalidate()
985
986 go func() {
987 sink := func(delta string) {
988 i.mu.Lock()
989 i.streaming.WriteString(delta)
990 i.mu.Unlock()
991 i.invalidate()
992 }
993 summary, err := i.agent.Compact(ctx, 4, sink)
994 i.mu.Lock()
995 i.busy = false
996 i.streamOn = false
997 i.streaming.Reset()
998 i.cancelTurn = nil
999 i.autoCompacting = false
1000 switch {
1001 case err != nil && ctx.Err() != nil:
1002 i.statusErr = ""
1003 if auto {
1004 i.statusOK = "auto-condense cancelled"
1005 } else {
1006 i.statusOK = "compaction cancelled"
1007 }
1008 case err != nil:
1009 i.statusErr = "compaction failed: " + err.Error()
1010 i.statusOK = ""
1011 default:
1012 i.statusErr = ""
1013 i.statusOK = fmt.Sprintf("compacted transcript (%d chars of summary)", len(summary))
1014 i.lastCtxInput = 0 // reset; next turn will get a fresh measurement
1015 i.toolCalls = map[string]*tui.ToolCallView{}
1016 i.toolOrder = nil
1017 }
1018 i.mu.Unlock()
1019 i.invalidate()
1020 }()
1021}
1022
1023func (i *Interactive) startTurn(parent context.Context, prompt string) {
1024 if i.agent == nil {
1025 return
1026 }
1027 ctx, cancel := context.WithCancel(parent)
1028 i.mu.Lock()
1029 i.busy = true
1030 i.spin.Start()
1031 i.cancelTurn = cancel
1032 i.statusErr = ""
1033 i.statusOK = ""
1034 i.streaming.Reset()
1035 i.streamOn = true
1036 i.toolCalls = map[string]*tui.ToolCallView{}
1037 i.toolOrder = nil
1038 i.scrollOffset = 0 // jump back to the bottom on new turn
1039 i.helpBlock = nil // hide the help block once the user asks something
1040 i.mu.Unlock()
1041 i.invalidate()
1042
1043 sink := func(ev core.AgentEvent) {
1044 i.handleEvent(ev)
1045 i.invalidate()
1046 }
1047
1048 go func() {
1049 err := i.agent.Prompt(ctx, prompt, nil, sink)
1050 i.mu.Lock()
1051 i.busy = false
1052 i.streamOn = false
1053 i.cancelTurn = nil
1054 if err != nil && ctx.Err() == nil {
1055 i.statusErr = err.Error()
1056 }
1057 // Pop the next queued message, if any, and relaunch.
1058 var next string
1059 var hasNext bool
1060 if len(i.queued) > 0 && ctx.Err() == nil && err == nil {
1061 next, i.queued = i.queued[0], i.queued[1:]
1062 hasNext = true
1063 }
1064 // If the turn was cancelled or errored, drop the queue so the
1065 // user isn't bombarded with stale messages after an interrupt.
1066 if ctx.Err() != nil || err != nil {
1067 i.queued = nil
1068 }
1069 // Decide whether the next thing to do is an auto-compaction.
1070 // Only fires when the turn completed cleanly AND the queue is
1071 // empty (otherwise a queued message would race the condense).
1072 shouldAutoCompact := !hasNext && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
1073 i.mu.Unlock()
1074 i.invalidate()
1075 parent := i.runCtx
1076 if parent == nil {
1077 parent = context.Background()
1078 }
1079 switch {
1080 case hasNext:
1081 i.startTurn(parent, next)
1082 case shouldAutoCompact:
1083 i.runCompact(parent, true)
1084 }
1085 }()
1086}
1087
1088// autoCompactThreshold is the context-window fraction at which the
1089// agent will auto-compact after a turn ends. 0.85 leaves enough
1090// headroom for one more user prompt + response before we bump the
1091// hard limit.
1092const autoCompactThreshold = 0.85
1093
1094// shouldAutoCompactLocked reports whether the last turn pushed context
1095// usage past the auto-compact threshold. Must be called with i.mu
1096// held; it reads lastCtxInput and the current model's context window.
1097func (i *Interactive) shouldAutoCompactLocked() bool {
1098 if i.agent == nil {
1099 return false
1100 }
1101 if i.autoCompacting {
1102 return false
1103 }
1104 m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
1105 if err != nil || m.ContextWindow <= 0 {
1106 return false
1107 }
1108 if i.lastCtxInput <= 0 {
1109 return false
1110 }
1111 return float64(i.lastCtxInput)/float64(m.ContextWindow) >= autoCompactThreshold
1112}
1113
1114func (i *Interactive) handleEvent(ev core.AgentEvent) {
1115 i.mu.Lock()
1116 defer i.mu.Unlock()
1117 switch e := ev.(type) {
1118 case core.EvTextDelta:
1119 i.streaming.WriteString(e.Delta)
1120 case core.EvAssistantMessage:
1121 i.streaming.Reset()
1122 i.streamOn = false
1123 if i.cfg.OnAssistant != nil {
1124 i.cfg.OnAssistant(e.Message)
1125 }
1126 case core.EvToolCall:
1127 tcv := &tui.ToolCallView{
1128 ID: e.ID,
1129 Name: e.Name,
1130 Args: shortArgs(e.Args),
1131 }
1132 i.toolCalls[e.ID] = tcv
1133 i.toolOrder = append(i.toolOrder, e.ID)
1134 case core.EvToolResult:
1135 if tc, ok := i.toolCalls[e.ID]; ok {
1136 tc.Done = true
1137 tc.Error = e.Result.IsError
1138 var text strings.Builder
1139 for _, c := range e.Result.Content {
1140 if tb, ok := c.(provider.TextBlock); ok {
1141 if text.Len() > 0 {
1142 text.WriteString("\n")
1143 }
1144 text.WriteString(tb.Text)
1145 }
1146 }
1147 tc.Result = text.String()
1148 }
1149 if i.cfg.OnToolResult != nil {
1150 i.cfg.OnToolResult(e.ID, e.Result)
1151 }
1152 case core.EvUsage:
1153 i.cumUsage = e.Cumulative
1154 if e.Usage.InputTokens > 0 {
1155 i.lastCtxInput = e.Usage.InputTokens + e.Usage.CacheReadTokens + e.Usage.CacheWriteTokens
1156 }
1157 case core.EvTurnEnd:
1158 if e.Stop == provider.StopAborted {
1159 // Aborted turn: discard the partial streaming text (it is not
1160 // persisted in the transcript) and clear any transient error.
1161 i.streaming.Reset()
1162 i.streamOn = false
1163 i.statusErr = ""
1164 i.statusOK = "cancelled"
1165 return
1166 }
1167 if e.Err != nil && !strings.Contains(e.Err.Error(), "context canceled") {
1168 i.statusErr = e.Err.Error()
1169 }
1170 }
1171}
1172
1173// Agent returns the current agent, if any. Used by cli.go to flush the
1174// final transcript to the session file.
1175func (i *Interactive) Agent() *core.Agent {
1176 i.mu.Lock()
1177 defer i.mu.Unlock()
1178 return i.agent
1179}
1180
1181func shortArgs(raw json.RawMessage) string {
1182 var v any
1183 if err := json.Unmarshal(raw, &v); err != nil {
1184 return ""
1185 }
1186 if m, ok := v.(map[string]any); ok {
1187 for _, k := range []string{"path", "file_path", "command"} {
1188 if s, ok := m[k].(string); ok {
1189 if len(s) > 60 {
1190 s = s[:57] + "..."
1191 }
1192 return s
1193 }
1194 }
1195 }
1196 b, _ := json.Marshal(v)
1197 s := string(b)
1198 if len(s) > 60 {
1199 s = s[:57] + "..."
1200 }
1201 return s
1202}
1203
1204// silence unused import in some build configs
1205var _ = fmt.Sprintf