1package modes
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strings"
9 "sync"
10 "time"
11
12 "github.com/patriceckhart/zot/internal/agent/extensions"
13 "github.com/patriceckhart/zot/internal/agent/modes/telegram"
14 "github.com/patriceckhart/zot/internal/agent/tools"
15 "github.com/patriceckhart/zot/internal/auth"
16 "github.com/patriceckhart/zot/internal/core"
17 "github.com/patriceckhart/zot/internal/extproto"
18 "github.com/patriceckhart/zot/internal/provider"
19 "github.com/patriceckhart/zot/internal/skills"
20 "github.com/patriceckhart/zot/internal/tui"
21)
22
23// InteractiveConfig configures the interactive loop.
24type InteractiveConfig struct {
25 Terminal tui.Terminal
26 Theme tui.Theme
27 Model string
28 Provider string
29 AuthMethod string // "apikey" | "oauth" — used to tag cost as (sub) in status bar
30 BaseURL string
31 Reasoning string
32 SystemPrompt string
33 Tools core.Registry
34 MaxSteps int
35 CWD string
36
37 // Agent is optional. If nil, zot opens without credentials; the
38 // user must /login before they can prompt.
39 Agent *core.Agent
40
41 InitialInput string
42
43 // Auth is required. When the user runs /login, Interactive talks to
44 // AuthManager to open a browser and wait for the callback.
45 AuthManager *auth.Manager
46 // BuildAgent is called after a successful login to (re)construct the
47 // agent with the fresh credential. It returns the new agent and
48 // the concrete provider/model in use.
49 BuildAgent func() (*core.Agent, string, string, error)
50
51 // BuildAgentFor rebuilds the agent with an explicit provider/model
52 // override (used by the /model picker when switching providers).
53 // If providerOverride is empty, the current provider is kept.
54 BuildAgentFor func(providerOverride, modelOverride string) (*core.Agent, string, string, error)
55
56 // ZotHome is the root directory for sessions/, used by /sessions
57 // and the update-check cache.
58 ZotHome string
59
60 // Version is the binary's current version (from main.version).
61 // Used only for display; the update check itself is done outside
62 // this package to avoid an import cycle.
63 Version string
64
65 // UpdateInfoChan is an optional channel that delivers the result
66 // of the github-release update check. Interactive reads at most
67 // one value, drops it if the check reported nothing, and otherwise
68 // surfaces a yellow "update available" banner at the top of the
69 // chat. Nil channel = no banner, no startup cost.
70 UpdateInfoChan <-chan UpdateInfo
71
72 // Sandbox is the shared sandbox pointer. Toggled by /jail and /unjail.
73 Sandbox *tools.Sandbox
74
75 // LoadSession swaps the current session for the one at path. The
76 // callback returns the new agent message slice so the TUI can invalidate.
77 LoadSession func(path string) error
78
79 // CurrentSessionPath returns the path of the live session file
80 // on disk (the one every AppendMessage writes to). Used by
81 // /session export so the exporter ships the exact bytes on
82 // disk. Returns an empty string when --no-session is set or
83 // no session is open.
84 CurrentSessionPath func() string
85
86 // FlushSession writes any in-memory agent messages to the
87 // session file that haven't been persisted yet. Called by
88 // /session export right before reading the file so the
89 // exported bytes reflect the full current conversation, not
90 // just the rows the agent happened to write synchronously.
91 // The default WriteNewTranscript-at-exit strategy means most
92 // of a running session lives only in memory until the tui
93 // closes; without a flush hook, /session export writes a
94 // file that only has the meta row.
95 FlushSession func()
96
97 // PersistModel is called whenever the user switches model or provider.
98 // It should update config.json and (if there's an active session)
99 // write a new meta row so resume picks up the same model.
100 PersistModel func(providerName, model string)
101
102 OnAssistant func(m provider.Message)
103 OnToolResult func(id string, r core.ToolResult)
104
105 // Extensions, if non-nil, lets users invoke extension-registered
106 // slash commands. Commands declared by extensions are looked up
107 // AFTER the built-in catalog so a built-in name always wins.
108 Extensions *extensions.Manager
109
110 // SkillSnapshot, if non-nil, returns the current list of
111 // discovered SKILL.md files. Re-invoked each time /skills opens
112 // so the picker reflects edits made during the session.
113 SkillSnapshot func() []*skills.Skill
114
115 // ChangelogChan, if non-nil, delivers release-notes for the
116 // current binary version once at startup. Interactive opens a
117 // dismissible overlay when the channel produces a non-empty
118 // body. Receiver fires at most once.
119 ChangelogChan <-chan ChangelogPayload
120
121 // OnChangelogDismiss, if non-nil, is called once the user
122 // closes the changelog overlay. The cli wires this to a
123 // MarkChangelogShown call so the same version doesn't show
124 // again on the next launch.
125 OnChangelogDismiss func()
126
127 // NoYolo is true when --no-yolo was passed. Interactive opens
128 // a confirmation dialog before every tool call and blocks the
129 // tool until the user picks yes / always-this-tool /
130 // always-all / no. When false (default), tools run freely.
131 NoYolo bool
132
133 // ConfirmGate is the session-scoped gate wrapping this
134 // interactive's Confirmer. When non-nil, /yolo can call
135 // AllowAll() on it to disable confirmation for the rest of the
136 // session. When nil (yolo mode), /yolo reports that there's
137 // nothing to disable.
138 ConfirmGate *core.ConfirmGate
139}
140
141// ChangelogPayload mirrors agent.ChangelogInfo without the import
142// cycle. The cli builds one from the http response, the tui opens
143// the overlay when one arrives.
144type ChangelogPayload struct {
145 Version string
146 Body string
147 URL string
148}
149
150// Interactive is the TUI chat loop.
151type Interactive struct {
152 cfg InteractiveConfig
153 view *tui.View
154 ed *tui.Editor
155 rend *tui.Renderer
156
157 mu sync.Mutex
158 agent *core.Agent
159 streaming strings.Builder // what's currently painted on screen
160 streamOn bool
161
162 // streamPending is the runes buffered after each EvTextDelta that
163 // haven't yet been promoted into `streaming` for rendering. It
164 // exists because some provider paths (notably Anthropic via the
165 // oauth/subscription channel) coalesce the model's output into a
166 // few fat chunks instead of drip-streaming. Painting those fat
167 // chunks verbatim looks like the summary "just appears". The
168 // paintPace goroutine drains a handful of runes per tick from
169 // this buffer into `streaming`, giving every path the same
170 // typewriter feel regardless of upstream chunk size.
171 streamPending []rune
172 // streamFlushPending is set when EvAssistantMessage fires while
173 // streamPending still has unrendered runes. The ticker flushes
174 // them, then closes out the stream (clearing flags, resetting
175 // buffers) so the final paint matches the on-disk message.
176 streamFlushPending bool
177 toolCalls map[string]*tui.ToolCallView
178 toolOrder []string
179 statusErr string
180 statusOK string
181 helpBlock []string // rendered above the chat when /help was typed
182 cumUsage provider.Usage
183 lastCtxInput int // input_tokens of the most recent turn — approximates current context size
184 busy bool
185 dirty chan struct{}
186 cancelTurn context.CancelFunc
187 scrollOffset int // rows from the bottom; 0 = pinned to latest
188
189 // Messages typed while a turn is in flight. Each is delivered as
190 // its own follow-up turn once the current one finishes. Rendered
191 // above the status bar as "sliding in: ..." chips.
192 queued []string
193
194 // runCtx is the top-level context passed to Run(). Follow-up turns
195 // drained from `queued` are started against this context so they
196 // survive past the ctx of the key event that enqueued them.
197 runCtx context.Context
198
199 // autoCompacting is true while a model-triggered compaction is in
200 // flight. Surfaced in the status bar so the user can tell a
201 // condense pass from a regular assistant turn.
202 autoCompacting bool
203
204 // updateInfo is the result of the async update check. Zero value
205 // while the check hasn't completed or nothing is available.
206 updateInfo UpdateInfo
207
208 dialog *loginDialog
209 modelDialog *modelDialog
210 sessionDialog *sessionDialog
211 jumpDialog *jumpDialog
212 btwDialog *btwDialog
213 skillsDialog *skillsDialog
214 changelogDialog *changelogDialog
215 confirmDialog *confirmDialog
216 logoutDialog *logoutDialog
217 telegramDialog *telegramDialog
218 telegramBridge *telegram.Bridge
219 sessionOpsDialog *sessionOpsDialog
220 sessionTreeDialog *sessionTreeDialog
221 extPanel *extPanelDialog
222
223 // pendingFork is true when the user ran /session fork: the next
224 // jump-picker selection should branch off that message instead
225 // of scrolling. Flag resets after the action fires or the dialog
226 // is dismissed, so repeated /jump calls don't turn into forks.
227 pendingFork bool
228 suggest *slashSuggester
229 spin *spinner
230
231 // parkedTurn is the 1-based turn number the viewport is currently
232 // scrolled to by /jump. 0 = not parked, showing the tail as usual.
233 // Rendered as a muted footer at the bottom of the chat so users
234 // don't forget they're looking at history.
235 parkedTurn int
236 parkedTotal int
237
238 // lastCtrlC is when the user last pressed ctrl+c. The first press
239 // clears the editor / cancels a turn / shows a hint; a second press
240 // within ctrlCExitWindow exits. Mirrors the python-repl convention.
241 lastCtrlC time.Time
242
243 // welcomeStart is when the interactive run began. The welcome
244 // banner shows the binary version for welcomeVersionDuration
245 // after this point and reverts to plain text after.
246 welcomeStart time.Time
247
248 // extNotes are one-shot styled lines pushed by extensions via
249 // Notify / Display. They live above the editor (just below the
250 // transcript) until cleared by /clear or another reset.
251 extNotes []string
252}
253
254// welcomeVersionDuration is how long the welcome banner shows the
255// version suffix before reverting to the plain headline. 1.5s is
256// enough to read at a glance and keeps the splash short.
257const welcomeVersionDuration = 1500 * time.Millisecond
258
259// NewInteractive constructs an Interactive from cfg.
260func NewInteractive(cfg InteractiveConfig) *Interactive {
261 i := &Interactive{
262 cfg: cfg,
263 view: &tui.View{
264 Theme: cfg.Theme,
265 ImageProto: tui.DetectImageProtocol(),
266 },
267 ed: tui.NewEditor(cfg.Theme.FG256(cfg.Theme.Accent, "▌ ")),
268 rend: tui.NewRenderer(cfg.Terminal),
269 toolCalls: map[string]*tui.ToolCallView{},
270 dirty: make(chan struct{}, 8),
271 dialog: newLoginDialog(),
272 modelDialog: newModelDialog(),
273 sessionDialog: newSessionDialog(),
274 jumpDialog: newJumpDialog(),
275 btwDialog: newBtwDialog(),
276 skillsDialog: newSkillsDialog(),
277 changelogDialog: newChangelogDialog(),
278 confirmDialog: newConfirmDialog(),
279 logoutDialog: newLogoutDialog(),
280 telegramDialog: newTelegramDialog(),
281 sessionOpsDialog: newSessionOpsDialog(),
282 sessionTreeDialog: newSessionTreeDialog(),
283 extPanel: newExtPanelDialog(),
284 suggest: newSlashSuggester(),
285 spin: newSpinner(),
286 }
287 if cfg.Agent != nil {
288 i.agent = cfg.Agent
289 i.view.Messages = cfg.Agent.Messages()
290 }
291 return i
292}
293
294// Run blocks until the user quits.
295func (i *Interactive) Run(ctx context.Context) error {
296 i.runCtx = ctx
297 term := i.cfg.Terminal
298 restore, err := term.EnterRaw()
299 if err != nil {
300 return err
301 }
302 defer restore()
303 defer func() {
304 if i.telegramBridge != nil {
305 i.telegramBridge.Stop()
306 }
307 }()
308
309 _, _ = term.Write([]byte(tui.SeqBracketedPasteOn))
310 _, _ = term.Write([]byte(tui.SeqAltScreenOn))
311 defer term.Write([]byte(tui.SeqAltScreenOff + tui.SeqBracketedPasteOff + tui.SeqShowCursor))
312
313 // Streaming pacer: drains buffered text deltas at a steady rate
314 // so typewriter feel is identical across providers regardless of
315 // upstream chunk size. Starts here so it lives for the whole
316 // session and exits with ctx.
317 go i.runStreamPacer(ctx)
318
319 cols, rows := term.Size()
320 i.rend.Resize(cols, rows)
321 term.OnResize(func() {
322 c, r := term.Size()
323 i.rend.Resize(c, r)
324 // Force an immediate redraw on resize. The throttled invalidate
325 // path is fine for animation, but a window resize is a discrete
326 // user action where any visible delay (or stale frame) reads as
327 // brokenness. redraw() is mutex-safe; the worst that happens is
328 // a duplicate paint if the throttler is mid-flight, which is
329 // invisible.
330 i.redraw()
331 })
332
333 if i.cfg.InitialInput != "" {
334 i.ed.SetValue(i.cfg.InitialInput)
335 }
336
337 // Stamp the welcome time and schedule a one-shot redraw at the
338 // expiry so the version suffix disappears on its own even if the
339 // user hasn't typed anything yet.
340 i.welcomeStart = time.Now()
341 time.AfterFunc(welcomeVersionDuration, i.invalidate)
342
343 // If the agent was constructed with a pre-loaded transcript
344 // (--continue, --resume, --session) park the viewport on the
345 // most recent turn so the user lands looking at where the
346 // previous session left off rather than at the bottom of an
347 // already-rendered final reply.
348 if i.agent != nil {
349 if msgs := i.agent.Messages(); len(msgs) > 0 {
350 i.scrollToLastTurn(msgs)
351 }
352 }
353
354 // No credential at startup? Auto-open the login dialog, and mark
355 // the status line. The user can Esc out of the dialog if they
356 // want to dismiss it (e.g. to check /help or /exit first).
357 if i.agent == nil {
358 i.statusErr = "not logged in. pick a login method below or press esc to dismiss."
359 i.dialog.Open(i.cfg.ZotHome)
360 }
361
362 // Input goroutine.
363 keys := make(chan tui.Key, 8)
364 go func() {
365 reader := tui.NewReaderWithPeek(term.ReadByte, term.PeekByteTimeout)
366 for {
367 k, err := reader.Read()
368 if err != nil {
369 return
370 }
371 keys <- k
372 }
373 }()
374
375 // Subscribe to auth events.
376 var authEvents <-chan auth.Event
377 if i.cfg.AuthManager != nil {
378 authEvents = i.cfg.AuthManager.Events()
379 }
380
381 // Animation ticker: drives spinner and dialog-related redraws when
382 // nothing else changed. 120ms is slow enough that highlighting a huge
383 // transcript doesn't spin the cpu.
384 tick := time.NewTicker(120 * time.Millisecond)
385 defer tick.Stop()
386
387 // Redraw throttle: coalesce bursts of invalidate() calls so we paint
388 // at most once every redrawMinInterval. Huge tool-result dumps can
389 // fire hundreds of invalidations while the user is typing; without
390 // this, the input goroutine never gets CPU and keystrokes lag.
391 const redrawMinInterval = 16 * time.Millisecond
392 var lastRedraw time.Time
393 var pendingRedraw bool
394 var pendingTimer *time.Timer
395
396 drainPending := func() {
397 if pendingTimer != nil {
398 pendingTimer.Stop()
399 pendingTimer = nil
400 }
401 if pendingRedraw {
402 pendingRedraw = false
403 lastRedraw = time.Now()
404 i.redraw()
405 }
406 }
407
408 requestRedraw := func() {
409 since := time.Since(lastRedraw)
410 if since >= redrawMinInterval {
411 // Redrawing right now subsumes any pending redraw, so clear
412 // the throttle state. Without this, a pending flag stays
413 // stuck at true and subsequent invalidate() calls within
414 // redrawMinInterval get dropped — which is exactly how the
415 // final "turn finished" frame went missing until the user
416 // nudged the ui by typing or scrolling.
417 if pendingTimer != nil {
418 pendingTimer.Stop()
419 }
420 pendingRedraw = false
421 lastRedraw = time.Now()
422 i.redraw()
423 return
424 }
425 if pendingRedraw {
426 return // already scheduled
427 }
428 pendingRedraw = true
429 wait := redrawMinInterval - since
430 if pendingTimer == nil {
431 pendingTimer = time.AfterFunc(wait, func() {
432 // Poke the dirty channel so the main loop wakes and
433 // drains the pending redraw on its own goroutine. We
434 // can't call drainPending here directly — it touches
435 // closure state shared with the main loop.
436 i.invalidate()
437 })
438 } else {
439 pendingTimer.Reset(wait)
440 }
441 }
442
443 i.invalidate()
444
445 updates := i.cfg.UpdateInfoChan // nil-safe; nil channel blocks forever in select
446 changelog := i.cfg.ChangelogChan // single-shot, see case below
447
448 for {
449 select {
450 case <-ctx.Done():
451 return ctx.Err()
452 case k := <-keys:
453 if done := i.handleKey(ctx, k); done {
454 return nil
455 }
456 i.invalidate()
457 case ev := <-authEvents:
458 i.handleAuthEvent(ev)
459 i.invalidate()
460 case info, ok := <-updates:
461 if ok && info.Available {
462 i.mu.Lock()
463 i.updateInfo = info
464 i.mu.Unlock()
465 i.invalidate()
466 }
467 updates = nil // single-shot; subsequent iterations skip this case
468 case cl, ok := <-changelog:
469 if ok && cl.Body != "" {
470 i.changelogDialog.Open(cl.Version, cl.URL, cl.Body)
471 i.invalidate()
472 }
473 changelog = nil // single-shot
474 case <-i.dirty:
475 requestRedraw()
476 case <-tick.C:
477 // Always drain a pending redraw on the tick. This is the
478 // safety net that catches the case where the dirty channel
479 // was saturated when the final "turn finished" invalidate
480 // fired, or where the throttle scheduled a deferred redraw
481 // and the AfterFunc-driven invalidate got dropped on a
482 // full channel.
483 drainPending()
484 // Only force a periodic redraw when something is actually
485 // animating (the main spinner during a busy turn, or the
486 // btw side-chat spinner while it's awaiting a response).
487 // Static pickers (model, session, jump, etc.) don't need
488 // the tick and firing it cancels the terminal's cursor
489 // blink inside dialogs that host their own editor (btw),
490 // because each frame re-emits hide-cursor + show-cursor.
491 if i.busy || i.btwDialog.Loading() {
492 requestRedraw()
493 }
494 }
495 }
496}
497
498func (i *Interactive) invalidate() {
499 select {
500 case i.dirty <- struct{}{}:
501 default:
502 }
503}
504
505// lastCols returns the current terminal width in columns.
506func (i *Interactive) lastCols() int {
507 cols, _ := i.cfg.Terminal.Size()
508 return cols
509}
510
511// chatPage returns the number of chat rows currently visible, used
512// as the page size for PageUp/PageDown.
513func (i *Interactive) chatPage() int {
514 _, rows := i.cfg.Terminal.Size()
515 p := rows - 6 // rough reservation for status + editor + a dialog line
516 if p < 4 {
517 p = 4
518 }
519 return p
520}
521
522// scrollBy adjusts the scroll offset. Positive = up (into history).
523// Clearing the parked-turn label when we're back at the bottom means
524// the "viewing turn N" footer goes away automatically as soon as you
525// scroll back to the live tail.
526func (i *Interactive) scrollBy(delta int) {
527 i.mu.Lock()
528 i.scrollOffset += delta
529 if i.scrollOffset < 0 {
530 i.scrollOffset = 0
531 }
532 if i.scrollOffset == 0 {
533 i.parkedTurn = 0
534 i.parkedTotal = 0
535 }
536 if i.rend != nil {
537 // VS Code's terminal is especially prone to leaving stray
538 // wrapped-character fragments behind during scroll-driven
539 // viewport changes. Force a full repaint on scroll, but
540 // avoid a whole-screen clear because that visibly flickers.
541 i.rend.Invalidate()
542 }
543 i.mu.Unlock()
544 i.invalidate()
545}
546
547// scrollToBottom pins the view to the latest content.
548func (i *Interactive) scrollToBottom() {
549 i.mu.Lock()
550 i.scrollOffset = 0
551 i.parkedTurn = 0
552 i.parkedTotal = 0
553 if i.rend != nil {
554 i.rend.Invalidate()
555 }
556 i.mu.Unlock()
557 i.invalidate()
558}
559
560func (i *Interactive) redraw() {
561 i.mu.Lock()
562 defer i.mu.Unlock()
563
564 cols, _ := i.cfg.Terminal.Size()
565 if i.agent != nil {
566 i.view.Messages = filterHiddenTranscriptMessages(i.agent.Messages())
567 } else {
568 i.view.Messages = nil
569 }
570 // Pacer flush: while the streaming pacer is still draining the
571 // buffer (i.e. EvAssistantMessage already fired but more runes
572 // are queued), the final assistant message is already in
573 // i.agent.Messages() in full. Painting it in the transcript
574 // AND the streaming block at the same time shows the user the
575 // complete text immediately — which defeats the whole pacer.
576 // Hide the last message until the pacer catches up; once the
577 // flush-pending latch clears, the message is revealed (the
578 // streaming block disappears the same frame because streamOn
579 // flips off, so the transition is seamless).
580 if i.streamFlushPending && len(i.view.Messages) > 0 {
581 i.view.Messages = i.view.Messages[:len(i.view.Messages)-1]
582 }
583 i.view.Streaming = i.streaming.String()
584 i.view.StreamingActive = i.streamOn
585 // Guard against the narrow race where EvAssistantMessage has
586 // just promoted a streaming reply into the transcript but a
587 // render tick hasn't flipped streamOn off yet. Without the
588 // guard, the same text would appear twice (once as the
589 // in-flight streaming block, once as the last transcript
590 // message). We detect the duplicate strictly: the last
591 // assistant message's visible text must equal the streaming
592 // buffer. Just matching on role is too broad — it also hides
593 // the next round's typewriter streaming after a tool turn,
594 // because the last transcript message is always assistant
595 // (the tool-use block) until the follow-up summary lands.
596 if i.streamOn && i.streaming.Len() > 0 {
597 if n := len(i.view.Messages); n > 0 && i.view.Messages[n-1].Role == provider.RoleAssistant {
598 if assistantText(i.view.Messages[n-1]) == i.streaming.String() {
599 i.view.StreamingActive = false
600 }
601 }
602 }
603 // Live tool-call view: only shown while a turn is in flight. Once
604 // the agent is idle, every tool call has already been folded into
605 // the transcript (as assistant.ToolCallBlock + a tool-role message),
606 // so showing v.ToolCalls a second time would duplicate them below
607 // the final assistant text — which looks like the summary came
608 // "before" the tools.
609 i.view.ToolCalls = i.view.ToolCalls[:0]
610 if i.busy {
611 for _, id := range i.toolOrder {
612 if tc, ok := i.toolCalls[id]; ok {
613 i.view.ToolCalls = append(i.view.ToolCalls, *tc)
614 }
615 }
616 }
617 i.view.Err = i.statusErr
618
619 chat := i.view.Build(cols)
620
621 // Welcome banner: shown at the top of the chat area when there is
622 // no transcript yet. Disappears after the first message is sent.
623 // The version suffix is shown for welcomeVersionDuration after
624 // startup, then drops off automatically.
625 if len(i.view.Messages) == 0 && !i.streamOn && len(i.toolOrder) == 0 {
626 showVer := !i.welcomeStart.IsZero() && time.Since(i.welcomeStart) < welcomeVersionDuration
627 chat = append(welcomeBanner(i.cfg.Theme, i.cfg.Version, showVer), chat...)
628 }
629
630 // Update-available banner: prepended above everything else so it's
631 // the first thing the user sees when opening a new zot session.
632 // Once rendered, it stays until the user updates to a newer
633 // version — we don't persist a "dismissed" flag because this is
634 // cheap and re-showing it is how most users remember to update.
635 if i.updateInfo.Available {
636 banner := renderUpdateBanner(i.cfg.Theme, i.updateInfo, cols)
637 chat = append(banner, chat...)
638 }
639
640 // /help block: appended to the transcript so it appears at the
641 // bottom of the chat area (right above the status bar / editor).
642 // Prepending it would push long conversations off the top of the
643 // viewport, which users would miss entirely.
644 if len(i.helpBlock) > 0 {
645 chat = append(chat, i.helpBlock...)
646 }
647
648 if i.statusOK != "" {
649 // Hard-truncate the OK line to the visible width so a long
650 // session path ("resumed session: /Users/.../sessions/...")
651 // doesn't overflow past the right edge and look broken on a
652 // narrow terminal.
653 line := "✓ " + i.statusOK
654 if cols > 4 && len(line) > cols {
655 line = line[:cols-1] + "…"
656 }
657 chat = append(chat, i.cfg.Theme.FG256(i.cfg.Theme.Tool, line), "")
658 }
659
660 // Extension notes (notify / display) live just under the
661 // transcript, above the dialog/editor band. Cleared by /clear.
662 if len(i.extNotes) > 0 {
663 chat = append(chat, i.extNotes...)
664 chat = append(chat, "")
665 }
666
667 // Dialogs (login or model picker) render between chat and the editor.
668 var dialog []string
669 switch {
670 case i.dialog.Active():
671 dialog = i.dialog.Render(i.cfg.Theme, cols)
672 case i.modelDialog.Active():
673 dialog = i.modelDialog.Render(i.cfg.Theme, cols)
674 case i.sessionDialog.Active():
675 // Reserve rows for the editor (~3), status line (1-2),
676 // dialog chrome (header + hint + rule + indicators, ~5),
677 // and leave the remainder for session rows. Minimum of 3
678 // rows so even a very small terminal shows something.
679 _, rows := i.cfg.Terminal.Size()
680 avail := rows - 12
681 if avail < 3 {
682 avail = 3
683 }
684 i.sessionDialog.MaxRows = avail
685 dialog = i.sessionDialog.Render(i.cfg.Theme, cols)
686 case i.jumpDialog.Active():
687 dialog = i.jumpDialog.Render(i.cfg.Theme, cols)
688 case i.btwDialog.Active():
689 dialog = i.btwDialog.Render(i.cfg.Theme, cols)
690 case i.skillsDialog.Active():
691 dialog = i.skillsDialog.Render(i.cfg.Theme, cols)
692 case i.changelogDialog.Active():
693 dialog = i.changelogDialog.Render(i.cfg.Theme, cols)
694 case i.confirmDialog.Active():
695 dialog = i.confirmDialog.Render(i.cfg.Theme, cols)
696 case i.logoutDialog.Active():
697 dialog = i.logoutDialog.Render(i.cfg.Theme, cols)
698 case i.telegramDialog.Active():
699 dialog = i.telegramDialog.Render(i.cfg.Theme, cols)
700 case i.sessionOpsDialog.Active():
701 dialog = i.sessionOpsDialog.Render(i.cfg.Theme, cols)
702 case i.sessionTreeDialog.Active():
703 dialog = i.sessionTreeDialog.Render(i.cfg.Theme, cols)
704 case i.extPanel.Active():
705 dialog = i.extPanel.Render(i.cfg.Theme, cols)
706 }
707
708 // Slash-command autocomplete: popup above the status line, only
709 // when the editor starts with "/" and no dialog is already open.
710 // Feed extension-registered commands into the suggester first so
711 // they show up in tab-complete + the popup alongside the built-ins.
712 if i.cfg.Extensions != nil {
713 catalog := i.cfg.Extensions.Commands()
714 extra := make([]slashCommand, 0, len(catalog))
715 for _, c := range catalog {
716 // The popup renders extension commands under a dedicated
717 // "── extensions ───" divider, so the description doesn't
718 // need to repeat the source. If the description is empty,
719 // fall back to the extension name so the row isn't blank.
720 desc := c.Description
721 if strings.TrimSpace(desc) == "" {
722 desc = "(" + c.Extension + ")"
723 }
724 extra = append(extra, slashCommand{
725 Name: "/" + c.Name,
726 Desc: desc,
727 })
728 }
729 i.suggest.SetExtra(extra)
730 }
731 var suggest []string
732 currentInput := i.ed.Value()
733 // Slash popup renders even while the agent is busy so the user
734 // can queue a destructive command (/clear, /compact, /logout,
735 // /model) or a read-only one (/help, /jump, /sessions, etc.)
736 // without waiting for the current turn to finish. The dispatcher
737 // in runSlash already handles the busy case per-command: safe
738 // ones run immediately, destructive ones cancel the turn first.
739 if len(dialog) == 0 && i.suggest.Active(currentInput) {
740 suggest = i.suggest.Render(currentInput, i.cfg.Theme, cols)
741 }
742
743 // Busy prefix shown at the far left of the status bar. The
744 // spinner glyph and its funny-line message share the `zot`
745 // label colour (Theme.Assistant) so the whole "who's working"
746 // band reads at a glance. Elapsed time stays muted because it
747 // drifts every second and shouldn't grab focus.
748 var busyPrefix string
749 if i.busy {
750 busyPrefix = fmt.Sprintf("%s %s %s %s",
751 i.cfg.Theme.FG256(i.cfg.Theme.Assistant, i.spin.Frame()),
752 i.cfg.Theme.FG256(i.cfg.Theme.Assistant, i.spin.Message()),
753 i.cfg.Theme.FG256(i.cfg.Theme.Muted, "-"),
754 i.cfg.Theme.FG256(i.cfg.Theme.Muted, i.spin.Elapsed().String()),
755 )
756 }
757
758 ctxMax := 0
759 if m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model); err == nil {
760 ctxMax = m.ContextWindow
761 }
762 statusLines := tui.StatusBar(tui.StatusBarParams{
763 Theme: i.cfg.Theme,
764 Provider: i.cfg.Provider,
765 Model: i.cfg.Model,
766 Busy: i.busy,
767 BusyPrefix: busyPrefix,
768 CWD: i.cfg.CWD,
769 Locked: i.cfg.Sandbox.Locked(),
770 Usage: i.cumUsage,
771 Subscription: i.cfg.AuthMethod == "oauth",
772 ContextUsed: i.lastCtxInput,
773 ContextMax: ctxMax,
774 AutoCompacting: i.autoCompacting,
775 Telegram: i.telegramBridge != nil && i.telegramBridge.Active(),
776 Cols: cols,
777 })
778 edLines, curR, curC := i.ed.Render(cols)
779
780 // "Sliding in" chips for messages the user typed while a turn is
781 // in flight. Shown directly above the status bar so they're close
782 // to the editor but don't push the chat around.
783 var queue []string
784 if len(i.queued) > 0 {
785 for _, q := range i.queued {
786 label := i.cfg.Theme.FG256(i.cfg.Theme.Accent, "sliding in: ")
787 text := truncateLine(q, cols-15)
788 queue = append(queue, label+i.cfg.Theme.FG256(i.cfg.Theme.Muted, text))
789 }
790 }
791
792 // Bottom-sticky sections (always visible, never scroll).
793 bottom := make([]string, 0, len(dialog)+len(suggest)+len(queue)+len(edLines)+1)
794 bottom = append(bottom, dialog...)
795 bottom = append(bottom, suggest...)
796 bottom = append(bottom, queue...)
797 bottom = append(bottom, statusLines...)
798 bottom = append(bottom, edLines...)
799
800 _, rows := i.cfg.Terminal.Size()
801 chatRows := rows - len(bottom)
802 if chatRows < 1 {
803 chatRows = 1
804 }
805
806 // Apply scroll offset to the chat slice.
807 maxOffset := len(chat) - chatRows
808 if maxOffset < 0 {
809 maxOffset = 0
810 }
811 if i.scrollOffset > maxOffset {
812 i.scrollOffset = maxOffset
813 }
814 if i.scrollOffset < 0 {
815 i.scrollOffset = 0
816 }
817
818 var visibleChat []string
819 if len(chat) <= chatRows {
820 visibleChat = chat
821 } else {
822 end := len(chat) - i.scrollOffset
823 start := end - chatRows
824 if start < 0 {
825 start = 0
826 }
827 start = alignSliceStartToImageBlock(chat, start, end)
828 visibleChat = chat[start:end]
829 }
830 visibleChat = clipBottomClippedImages(visibleChat)
831
832 // A tiny "scrolled up" indicator in the top-right of the chat pane
833 // so you know you're not at the bottom. When the viewport was
834 // parked by /jump we include the turn number so the user remembers
835 // they're reading history rather than the live conversation.
836 if i.scrollOffset > 0 && len(visibleChat) > 0 {
837 var text string
838 if i.parkedTurn > 0 && i.parkedTotal > 0 {
839 text = fmt.Sprintf(" ↑ viewing turn %d of %d - %d lines more below (pgdn / end)",
840 i.parkedTurn, i.parkedTotal, i.scrollOffset)
841 } else {
842 text = fmt.Sprintf(" ↑ %d lines more below (end to jump)", i.scrollOffset)
843 }
844 note := i.cfg.Theme.FG256(i.cfg.Theme.Muted, text)
845 visibleChat = append([]string{note}, visibleChat...)
846 if len(visibleChat) > chatRows {
847 visibleChat = visibleChat[:chatRows]
848 }
849 }
850
851 frame := make([]string, 0, len(visibleChat)+len(bottom))
852 frame = append(frame, visibleChat...)
853 frame = append(frame, bottom...)
854
855 // Default: the real terminal cursor sits on the main editor's
856 // input position. When an overlay dialog has its own input
857 // field (today just /btw), route the cursor there instead so
858 // the blinking cursor shows where the user is actually typing.
859 // Dialogs without a cursor (model picker, /help, /login, etc.)
860 // return -1 and the main editor keeps the cursor.
861 cursorRow := len(visibleChat) + len(dialog) + len(suggest) + len(queue) + len(statusLines) + curR
862 cursorCol := curC
863 if i.btwDialog.Active() {
864 if r, c := i.btwDialog.CursorPos(cols); r >= 0 {
865 cursorRow = len(visibleChat) + r
866 cursorCol = c
867 }
868 }
869 if i.extPanel.Active() {
870 cursorRow = -1
871 cursorCol = 0
872 }
873 i.rend.Draw(frame, cursorRow, cursorCol)
874}
875
876func alignSliceStartToImageBlock(chat []string, start, end int) int {
877 if start <= 0 || start >= len(chat) || start >= end {
878 return start
879 }
880 // If the slice already starts on an image row, keep it.
881 if strings.Contains(chat[start], "\x1b]1337;File=") || strings.Contains(chat[start], "\x1b_G") {
882 return start
883 }
884 // When the viewport begins inside an image block, the image escape row
885 // sits just above a run of blank reservation rows, followed by an
886 // "image - ..." info line. In that case, snap the slice start up to the
887 // escape row so the image actually renders instead of showing only the
888 // reserved blank area and metadata.
889 j := start
890 for j < end && strings.TrimSpace(chat[j]) == "" {
891 j++
892 }
893 if j >= end || !strings.Contains(chat[j], "image - ") {
894 return start
895 }
896 for k := start - 1; k >= 0; k-- {
897 line := chat[k]
898 if strings.Contains(line, "\x1b]1337;File=") || strings.Contains(line, "\x1b_G") {
899 return k
900 }
901 if strings.TrimSpace(line) != "" {
902 break
903 }
904 }
905 return start
906}
907
908const hiddenOpenAIImageMirrorPrefix = "Tool output included the following image content:"
909
910func filterHiddenTranscriptMessages(msgs []provider.Message) []provider.Message {
911 if len(msgs) == 0 {
912 return nil
913 }
914 out := make([]provider.Message, 0, len(msgs))
915 for _, m := range msgs {
916 if isHiddenTranscriptMessage(m) {
917 continue
918 }
919 out = append(out, m)
920 }
921 return out
922}
923
924func isHiddenTranscriptMessage(m provider.Message) bool {
925 if m.Role != provider.RoleUser || len(m.Content) == 0 {
926 return false
927 }
928 tb, ok := m.Content[0].(provider.TextBlock)
929 if !ok {
930 return false
931 }
932 return strings.TrimSpace(tb.Text) == hiddenOpenAIImageMirrorPrefix
933}
934
935func clipBottomClippedImages(lines []string) []string {
936 if len(lines) == 0 {
937 return lines
938 }
939 out := append([]string(nil), lines...)
940 for i, line := range out {
941 if !strings.Contains(line, "\x1b]1337;File=") && !strings.Contains(line, "\x1b_G") {
942 continue
943 }
944 // Image blocks render as: image escape, zero or more blank
945 // reservation rows, then the muted "image - ..." info line,
946 // then one trailing blank. If the info line isn't visible in
947 // the current chat slice, the image would paint down into the
948 // fixed status bar area. Suppress that image for this frame.
949 foundInfo := false
950 for j := i + 1; j < len(out); j++ {
951 if strings.Contains(out[j], "image - ") {
952 foundInfo = true
953 break
954 }
955 if strings.TrimSpace(out[j]) != "" {
956 break
957 }
958 }
959 if !foundInfo {
960 out[i] = ""
961 }
962 }
963 return out
964}
965
966// truncateLine shortens s so it fits within n display cells, with an
967// ellipsis if trimmed. Used by the "sliding in" chips so a pasted
968// novel doesn't blow past the status line.
969func panelKeyName(k tui.Key) string {
970 switch k.Kind {
971 case tui.KeyUp:
972 return "up"
973 case tui.KeyDown:
974 return "down"
975 case tui.KeyLeft:
976 return "left"
977 case tui.KeyRight:
978 return "right"
979 case tui.KeyEnter:
980 return "enter"
981 case tui.KeyEsc:
982 return "esc"
983 case tui.KeyTab:
984 return "tab"
985 case tui.KeyBackspace:
986 return "backspace"
987 case tui.KeyDelete:
988 return "delete"
989 case tui.KeyHome:
990 return "home"
991 case tui.KeyEnd:
992 return "end"
993 case tui.KeyPageUp:
994 return "pageup"
995 case tui.KeyPageDown:
996 return "pagedown"
997 case tui.KeyRune:
998 return "rune"
999 default:
1000 return "unknown"
1001 }
1002}
1003
1004func panelKeyText(k tui.Key) string {
1005 if k.Kind == tui.KeyRune {
1006 return string(k.Rune)
1007 }
1008 return ""
1009}
1010
1011func truncateLine(s string, n int) string {
1012 if n <= 0 {
1013 return ""
1014 }
1015 // Collapse newlines — chips are single line.
1016 s = strings.ReplaceAll(s, "\n", " ↩ ")
1017 runes := []rune(s)
1018 if len(runes) <= n {
1019 return s
1020 }
1021 if n <= 1 {
1022 return "…"
1023 }
1024 return string(runes[:n-1]) + "…"
1025}
1026
1027// ctrlCExitWindow is how long after a ctrl+c press a *second* press
1028// will exit instead of just clearing input. Long enough to be
1029// deliberate (rules out accidental key chord), short enough that the
1030// hint stays meaningful.
1031const ctrlCExitWindow = 2 * time.Second
1032
1033// armCtrlCExit records the timestamp of the current ctrl+c so the next
1034// one within ctrlCExitWindow exits.
1035func (i *Interactive) armCtrlCExit() {
1036 i.mu.Lock()
1037 i.lastCtrlC = time.Now()
1038 i.mu.Unlock()
1039}
1040
1041// ctrlCExitArmed reports whether a previous ctrl+c was recent enough
1042// that another press should now exit.
1043func (i *Interactive) ctrlCExitArmed() bool {
1044 i.mu.Lock()
1045 t := i.lastCtrlC
1046 i.mu.Unlock()
1047 return !t.IsZero() && time.Since(t) <= ctrlCExitWindow
1048}
1049
1050func (i *Interactive) handleKey(ctx context.Context, k tui.Key) (done bool) {
1051 // Any key that isn't ctrl+c invalidates an armed ctrl+c-exit, so
1052 // pressing ctrl+c then typing then ctrl+c much later doesn't quit
1053 // unexpectedly. The hint message also goes stale; clear it.
1054 if k.Kind != tui.KeyCtrlC {
1055 i.mu.Lock()
1056 if !i.lastCtrlC.IsZero() {
1057 i.lastCtrlC = time.Time{}
1058 if strings.HasPrefix(i.statusOK, "input cleared") || strings.HasPrefix(i.statusOK, "press ctrl+c") {
1059 i.statusOK = ""
1060 }
1061 }
1062 i.mu.Unlock()
1063 }
1064
1065 // Dialogs consume keys while open (except ctrl+c, which always closes them).
1066
1067 // Confirm dialog has highest priority: the agent goroutine is
1068 // blocked waiting for an answer, so we must not let keys leak
1069 // anywhere else while it's up.
1070 if i.confirmDialog.Active() {
1071 i.confirmDialog.HandleKey(k)
1072 i.invalidate()
1073 return false
1074 }
1075 if i.dialog.Active() {
1076 if k.Kind == tui.KeyCtrlC {
1077 i.dialog.Close()
1078 if i.cfg.AuthManager != nil {
1079 i.cfg.AuthManager.CancelOAuth()
1080 }
1081 return false
1082 }
1083 act := i.dialog.HandleKey(k)
1084 if act.StartAPIKey {
1085 i.startAPIKeyFlow(act.Provider)
1086 }
1087 if act.StartOAuth {
1088 i.startOAuthFlow(act.Provider)
1089 }
1090 return false
1091 }
1092 if i.modelDialog.Active() {
1093 if k.Kind == tui.KeyCtrlC {
1094 i.modelDialog.Close()
1095 return false
1096 }
1097 act := i.modelDialog.HandleKey(k)
1098 if act.Select {
1099 i.applyModelSelection(act.Provider, act.Model)
1100 }
1101 return false
1102 }
1103 if i.sessionDialog.Active() {
1104 if k.Kind == tui.KeyCtrlC {
1105 i.sessionDialog.Close()
1106 return false
1107 }
1108 act := i.sessionDialog.HandleKey(k)
1109 if act.Select {
1110 i.applySessionSelection(act.Path)
1111 }
1112 return false
1113 }
1114 if i.logoutDialog.Active() {
1115 if k.Kind == tui.KeyCtrlC {
1116 i.logoutDialog.Close()
1117 i.invalidate()
1118 return false
1119 }
1120 act := i.logoutDialog.HandleKey(k)
1121 if act.Select {
1122 i.doLogout(act.Target)
1123 }
1124 i.invalidate()
1125 return false
1126 }
1127 if i.telegramDialog.Active() {
1128 if k.Kind == tui.KeyCtrlC {
1129 i.telegramDialog.Close()
1130 i.invalidate()
1131 return false
1132 }
1133 act := i.telegramDialog.HandleKey(k)
1134 if act.Select {
1135 i.doTelegram(act.Action)
1136 }
1137 i.invalidate()
1138 return false
1139 }
1140 if i.sessionOpsDialog.Active() {
1141 if k.Kind == tui.KeyCtrlC {
1142 i.sessionOpsDialog.Close()
1143 i.invalidate()
1144 return false
1145 }
1146 act := i.sessionOpsDialog.HandleKey(k)
1147 if act.Select {
1148 i.doSessionOp(act.Action, "")
1149 }
1150 i.invalidate()
1151 return false
1152 }
1153 if i.sessionTreeDialog.Active() {
1154 if k.Kind == tui.KeyCtrlC {
1155 i.sessionTreeDialog.Close()
1156 i.invalidate()
1157 return false
1158 }
1159 act := i.sessionTreeDialog.HandleKey(k)
1160 if act.Select {
1161 i.applySessionTreeSelection(act.Path)
1162 }
1163 i.invalidate()
1164 return false
1165 }
1166 if i.extPanel.Active() {
1167 if k.Kind == tui.KeyCtrlC || k.Kind == tui.KeyEsc {
1168 if i.cfg.Extensions != nil {
1169 _ = i.cfg.Extensions.SendPanelClose(i.extPanel.ext, i.extPanel.id)
1170 }
1171 i.extPanel.Close()
1172 i.invalidate()
1173 return false
1174 }
1175 if i.cfg.Extensions != nil {
1176 _ = i.cfg.Extensions.SendPanelKey(i.extPanel.ext, i.extPanel.id, panelKeyName(k), panelKeyText(k))
1177 }
1178 return false
1179 }
1180 if i.jumpDialog.Active() {
1181 if k.Kind == tui.KeyCtrlC {
1182 i.jumpDialog.Close()
1183 i.pendingFork = false
1184 return false
1185 }
1186 act := i.jumpDialog.HandleKey(k)
1187 if act.Select {
1188 if i.pendingFork {
1189 i.applyForkSelection(act.MessageIdx)
1190 } else {
1191 i.applyJumpSelection(act.MessageIdx, act.TurnNo)
1192 }
1193 }
1194 // If the user dismissed the dialog without selecting, also
1195 // clear the pending-fork flag so a later plain /jump isn't
1196 // hijacked.
1197 if act.Close {
1198 i.pendingFork = false
1199 }
1200 return false
1201 }
1202 if i.btwDialog.Active() {
1203 if k.Kind == tui.KeyCtrlC {
1204 i.btwDialog.Close()
1205 i.invalidate()
1206 return false
1207 }
1208 i.btwDialog.HandleKey(k, i.invalidate)
1209 return false
1210 }
1211 if i.skillsDialog.Active() {
1212 if k.Kind == tui.KeyCtrlC {
1213 i.skillsDialog.Close()
1214 i.invalidate()
1215 return false
1216 }
1217 i.skillsDialog.HandleKey(k)
1218 i.invalidate()
1219 return false
1220 }
1221 if i.changelogDialog.Active() {
1222 if closed := i.changelogDialog.HandleKey(k); closed {
1223 // User dismissed; let the parent persist the
1224 // LastChangelogShown marker via the close callback.
1225 if i.cfg.OnChangelogDismiss != nil {
1226 i.cfg.OnChangelogDismiss()
1227 }
1228 }
1229 i.invalidate()
1230 return false
1231 }
1232
1233 // Global keys.
1234 switch k.Kind {
1235 case tui.KeyCtrlC:
1236 // While busy: do NOT cancel the turn. ctrl+c during a
1237 // running turn is almost always reflex muscle memory
1238 // ("be quiet" in a shell) rather than a deliberate
1239 // decision to kill a multi-minute model call that's
1240 // already cost tokens. Use esc to interrupt a turn; use
1241 // a deliberate double-ctrl+c to exit zot entirely. First
1242 // press arms the exit hint, second press within
1243 // ctrlCExitWindow quits.
1244 if i.busy {
1245 if i.ctrlCExitArmed() {
1246 return true
1247 }
1248 i.mu.Lock()
1249 i.statusOK = "press ctrl+c again to exit, esc to cancel the turn"
1250 i.statusErr = ""
1251 i.mu.Unlock()
1252 i.armCtrlCExit()
1253 return false
1254 }
1255 // Idle: first press clears the editor (and any queued
1256 // follow-up messages); a second press within ctrlCExitWindow
1257 // exits. With both an empty editor and no queue the first
1258 // press still just arms — require a deliberate double-tap.
1259 hadInput := !i.ed.IsEmpty() || len(i.queued) > 0
1260 if hadInput {
1261 i.ed.Clear()
1262 i.suggest.Reset()
1263 i.mu.Lock()
1264 i.queued = nil
1265 i.statusOK = "input cleared"
1266 i.statusErr = ""
1267 i.mu.Unlock()
1268 i.armCtrlCExit()
1269 return false
1270 }
1271 if i.ctrlCExitArmed() {
1272 return true
1273 }
1274 i.mu.Lock()
1275 i.statusOK = "press ctrl+c again to exit"
1276 i.statusErr = ""
1277 i.mu.Unlock()
1278 i.armCtrlCExit()
1279 return false
1280 case tui.KeyEsc:
1281 // Esc interrupts a running turn — but only when nothing
1282 // else on screen wants to consume the key first. The slash
1283 // popup has its own Esc behaviour (close + clear editor),
1284 // and transient overlays like the /help block and extension
1285 // notes should dismiss on Esc before we even consider the
1286 // turn. Without these guards, a casual Esc press after
1287 // running /help on a busy turn rips the turn away.
1288 if i.suggest.Active(i.ed.Value()) {
1289 break
1290 }
1291 i.mu.Lock()
1292 hadHelp := len(i.helpBlock) > 0
1293 hadNotes := len(i.extNotes) > 0
1294 if hadHelp {
1295 i.helpBlock = nil
1296 }
1297 if hadNotes {
1298 i.extNotes = nil
1299 }
1300 i.mu.Unlock()
1301 if hadHelp || hadNotes {
1302 i.invalidate()
1303 return false
1304 }
1305 if i.busy && i.cancelTurn != nil {
1306 i.cancelTurn()
1307 // If a confirm dialog is pending, refuse it so the agent
1308 // goroutine unblocks and the context cancellation can
1309 // actually take effect.
1310 i.confirmDialog.CancelAll("turn cancelled")
1311 return false
1312 }
1313 case tui.KeyCtrlD:
1314 if i.ed.IsEmpty() && !i.busy {
1315 return true
1316 }
1317 case tui.KeyCtrlL:
1318 i.rend.Clear()
1319 i.invalidate()
1320 return false
1321 case tui.KeyCtrlO:
1322 // Toggle expansion of collapsed tool results. Affects every tool
1323 // call in the transcript — press again to re-collapse.
1324 i.mu.Lock()
1325 i.view.ExpandAll = !i.view.ExpandAll
1326 i.mu.Unlock()
1327 i.invalidate()
1328 return false
1329 case tui.KeyPageUp:
1330 i.scrollBy(+i.chatPage())
1331 return false
1332 case tui.KeyPageDown:
1333 i.scrollBy(-i.chatPage())
1334 return false
1335 case tui.KeyUp:
1336 // Always use up/down for chat scrolling, even when the editor
1337 // contains text. This makes keyboard scrolling consistent with
1338 // a draft present at the cost of disabling vertical cursor
1339 // motion inside the multi-line editor. Keep slash-popup
1340 // navigation working by letting it intercept later when active.
1341 if !i.suggest.Active(i.ed.Value()) {
1342 i.scrollBy(+3)
1343 return false
1344 }
1345 case tui.KeyDown:
1346 if !i.suggest.Active(i.ed.Value()) {
1347 if i.scrollOffset > 0 {
1348 i.scrollBy(-3)
1349 }
1350 return false
1351 }
1352 }
1353
1354 // Note: we intentionally do NOT gate the editor on i.busy here.
1355 // Typing while the agent is working is supported — submitted
1356 // messages are queued and delivered as follow-up turns when the
1357 // current turn ends. See the submit handler below.
1358
1359 if k.Kind == tui.KeyEnter && k.Alt {
1360 i.ed.HandleKey(tui.Key{Kind: tui.KeyRune, Rune: '\n', Alt: true})
1361 return false
1362 }
1363
1364 // Slash suggestions: intercept up/down/tab/enter when the popup is visible.
1365 if i.suggest.Active(i.ed.Value()) {
1366 switch k.Kind {
1367 case tui.KeyUp:
1368 i.suggest.Up()
1369 return false
1370 case tui.KeyDown:
1371 i.suggest.Down()
1372 return false
1373 case tui.KeyTab:
1374 if name := i.suggest.Selection(i.ed.Value()); name != "" {
1375 i.ed.SetValue(name)
1376 i.suggest.Reset()
1377 }
1378 return false
1379 case tui.KeyEnter:
1380 // Enter on an ambiguous or partial slash prefix: complete to the
1381 // currently highlighted command and run it. That way typing
1382 // "/lo" + enter picks whichever of /login or /logout is selected
1383 // in the popup instead of submitting "/lo" as unknown. Also
1384 // clear the editor so the command doesn't linger after the
1385 // dialog opens/closes.
1386 if name := i.suggest.Selection(i.ed.Value()); name != "" {
1387 i.ed.Clear()
1388 i.suggest.Reset()
1389 return i.runSlash(ctx, name)
1390 }
1391 case tui.KeyEsc:
1392 i.ed.Clear()
1393 i.suggest.Reset()
1394 return false
1395 }
1396 }
1397
1398 if submit := i.ed.HandleKey(k); submit {
1399 // SubmitValue() expands any [pasted text #N +L lines]
1400 // placeholders back into their bodies; the raw Value()
1401 // is only what the user sees on screen.
1402 text := strings.TrimRight(i.ed.SubmitValue(), "\n")
1403 if text == "" {
1404 return false
1405 }
1406 i.ed.Clear()
1407 i.suggest.Reset()
1408
1409 if looksLikeSlashCommand(text) {
1410 head := text
1411 rest := ""
1412 if idx := strings.IndexAny(text, " \t"); idx >= 0 {
1413 head = text[:idx]
1414 rest = strings.TrimSpace(text[idx:])
1415 }
1416 if !isKnownSlashCommand(text) {
1417 // Try extensions before giving up. Extensions register
1418 // commands by bare name (no leading slash); strip it here.
1419 extName := strings.TrimPrefix(head, "/")
1420 if i.cfg.Extensions != nil && i.cfg.Extensions.HasCommand(extName) {
1421 go i.invokeExtensionCommand(ctx, extName, rest)
1422 return false
1423 }
1424 i.mu.Lock()
1425 i.statusErr = "unknown command " + head + " — type /help to see the list"
1426 i.statusOK = ""
1427 i.mu.Unlock()
1428 return false
1429 }
1430 // Slash commands run regardless of busy state. Commands that
1431 // would mutate the transcript or replace the agent (/clear,
1432 // /compact, /logout, /login, /model) cancel the active turn
1433 // first and wait for the goroutine to wind down so they don't
1434 // race with a streaming response. Safe commands (/help,
1435 // /jump, /sessions, /jail, /unjail, /exit) run immediately
1436 // without disturbing the active turn.
1437 if slashCancelsTurn(head) {
1438 i.cancelAndWaitForIdle()
1439 }
1440 return i.runSlash(ctx, text)
1441 }
1442
1443 if i.agent == nil {
1444 i.mu.Lock()
1445 i.statusErr = "not logged in. type /login first."
1446 i.mu.Unlock()
1447 return false
1448 }
1449 // Mirror the user's typed prompt into the paired Telegram
1450 // chat (when the bridge is active) so the Telegram thread
1451 // stays a complete record of the session, not just the half
1452 // that originated on the phone. On a goroutine so the
1453 // network write doesn't delay the local turn.
1454 if i.telegramBridge != nil && i.telegramBridge.Active() {
1455 go i.telegramBridge.OnUserTyped(text)
1456 }
1457 // If a turn is already in flight, queue this prompt instead of
1458 // starting a second one. The drain loop at the end of startTurn
1459 // will pick it up when the current turn finishes.
1460 i.mu.Lock()
1461 if i.busy {
1462 i.queued = append(i.queued, text)
1463 i.mu.Unlock()
1464 i.invalidate()
1465 return false
1466 }
1467 i.mu.Unlock()
1468 i.startTurn(ctx, text)
1469 }
1470 return false
1471}
1472
1473// invokeExtensionCommand fires an extension-registered slash command
1474// in a background goroutine, awaits the response, and applies the
1475// requested action (prompt / insert / display / noop). Errors and
1476// timeouts surface as a status_err line.
1477func (i *Interactive) invokeExtensionCommand(ctx context.Context, name, args string) {
1478 resp, err := i.cfg.Extensions.Invoke(ctx, name, args, 30*time.Second)
1479 if err != nil {
1480 i.mu.Lock()
1481 i.statusErr = "extension /" + name + ": " + err.Error()
1482 i.statusOK = ""
1483 i.mu.Unlock()
1484 i.invalidate()
1485 return
1486 }
1487 if resp.Error != "" {
1488 i.mu.Lock()
1489 i.statusErr = "extension /" + name + ": " + resp.Error
1490 i.statusOK = ""
1491 i.mu.Unlock()
1492 i.invalidate()
1493 return
1494 }
1495 switch resp.Action {
1496 case "open_panel":
1497 if resp.OpenPanel != nil {
1498 extName := name
1499 if i.cfg.Extensions != nil {
1500 if owner := i.cfg.Extensions.CommandOwner(name); owner != "" {
1501 extName = owner
1502 }
1503 }
1504 i.OpenPanel(extName, *resp.OpenPanel)
1505 }
1506 case "prompt":
1507 if strings.TrimSpace(resp.Prompt) == "" {
1508 return
1509 }
1510 i.startTurn(i.runCtx, resp.Prompt)
1511 case "insert":
1512 i.ed.Insert(resp.Insert)
1513 i.invalidate()
1514 case "display":
1515 i.appendExtensionNote(name, resp.Display, "info")
1516 case "noop", "":
1517 // nothing
1518 default:
1519 i.mu.Lock()
1520 i.statusErr = "extension /" + name + ": unknown action " + resp.Action
1521 i.mu.Unlock()
1522 i.invalidate()
1523 }
1524}
1525
1526// appendExtensionNote renders an extension-originated note in the
1527// chat. Levels: "info" (muted), "warn" (warning), "error" (error),
1528// "success" (tool/ok green).
1529func (i *Interactive) appendExtensionNote(extName, msg, level string) {
1530 if msg == "" {
1531 return
1532 }
1533 i.mu.Lock()
1534 defer i.mu.Unlock()
1535 color := i.cfg.Theme.Muted
1536 switch level {
1537 case "warn":
1538 color = i.cfg.Theme.Warning
1539 case "error":
1540 color = i.cfg.Theme.Error
1541 case "success":
1542 color = i.cfg.Theme.Tool
1543 }
1544 prefix := i.cfg.Theme.FG256(i.cfg.Theme.Accent, "["+extName+"] ")
1545 for _, line := range strings.Split(msg, "\n") {
1546 i.statusOK = "" // clear any stale ok
1547 i.statusErr = ""
1548 i.extNotes = append(i.extNotes, prefix+i.cfg.Theme.FG256(color, line))
1549 }
1550}
1551
1552// HostHooks implementation for the extension manager. The manager
1553// holds an interface, not a concrete *Interactive, so these methods
1554// are the only thing the manager sees.
1555
1556// Notify is the manager's NotifyFromExt entry point.
1557func (i *Interactive) Notify(extName, level, message string) {
1558 i.appendExtensionNote(extName, message, level)
1559 i.invalidate()
1560}
1561
1562// Submit feeds text through the agent loop as if the user had typed it.
1563func (i *Interactive) Submit(text string) {
1564 i.startTurn(i.runCtx, text)
1565}
1566
1567// SubmitOrQueue runs text immediately if the agent is idle, or
1568// appends it to the pending queue if a turn is already in flight.
1569// Used by the telegram bridge (and by the editor submit path) so
1570// both input sources share the same "queue behind an active turn"
1571// semantics. Images are ignored for now — only the text prompt is
1572// forwarded — because the queued-prompt path is text-only; a
1573// follow-up can expand the queue entry to carry images.
1574func (i *Interactive) SubmitOrQueue(text string, images []provider.ImageBlock) {
1575 _ = images // reserved for future queued-with-images support
1576 i.mu.Lock()
1577 if i.agent == nil {
1578 i.statusErr = "not logged in. type /login first."
1579 i.mu.Unlock()
1580 i.invalidate()
1581 return
1582 }
1583 if i.busy {
1584 i.queued = append(i.queued, text)
1585 i.mu.Unlock()
1586 i.invalidate()
1587 return
1588 }
1589 i.mu.Unlock()
1590 i.startTurn(i.runCtx, text)
1591}
1592
1593// CancelTurn aborts the active turn if one is running. Used by the
1594// telegram bridge when the paired user sends /stop.
1595func (i *Interactive) CancelTurn() {
1596 i.mu.Lock()
1597 cancel := i.cancelTurn
1598 i.mu.Unlock()
1599 if cancel != nil {
1600 cancel()
1601 }
1602}
1603
1604// Insert places text at the cursor in the editor.
1605func (i *Interactive) Insert(text string) {
1606 i.ed.Insert(text)
1607 i.invalidate()
1608}
1609
1610// Display appends a styled note from extName to the chat without a
1611// model call.
1612func (i *Interactive) Display(extName, text string) {
1613 i.appendExtensionNote(extName, text, "info")
1614 i.invalidate()
1615}
1616
1617func (i *Interactive) OpenPanel(extName string, spec extproto.PanelSpec) {
1618 i.mu.Lock()
1619 defer i.mu.Unlock()
1620 i.extPanel.Open(extName, spec.ID, spec.Title, spec.Lines, spec.Footer)
1621 if i.cfg.Extensions != nil {
1622 cols, rows := i.cfg.Terminal.Size()
1623 _ = cols
1624 _ = rows
1625 }
1626 i.invalidate()
1627}
1628
1629func (i *Interactive) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
1630 i.mu.Lock()
1631 defer i.mu.Unlock()
1632 if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
1633 i.extPanel.Update(title, lines, footer)
1634 i.invalidate()
1635 }
1636}
1637
1638func (i *Interactive) ClosePanel(extName, panelID string) {
1639 i.mu.Lock()
1640 defer i.mu.Unlock()
1641 if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
1642 i.extPanel.Close()
1643 i.invalidate()
1644 }
1645}
1646
1647func (i *Interactive) runSlash(ctx context.Context, cmd string) (done bool) {
1648 parts := strings.Fields(cmd)
1649 switch parts[0] {
1650 case "/exit":
1651 return true
1652 case "/clear":
1653 if i.agent != nil {
1654 i.agent.SetMessages(nil)
1655 }
1656 i.mu.Lock()
1657 i.toolCalls = map[string]*tui.ToolCallView{}
1658 i.toolOrder = nil
1659 i.statusErr = ""
1660 i.statusOK = ""
1661 i.helpBlock = nil
1662 i.parkedTurn = 0
1663 i.parkedTotal = 0
1664 i.scrollOffset = 0
1665 i.extNotes = nil
1666 i.view.InvalidateRenderCache()
1667 i.mu.Unlock()
1668 case "/help":
1669 i.mu.Lock()
1670 i.helpBlock = renderHelpBlock(i.cfg.Theme, i.lastCols())
1671 i.statusErr = ""
1672 i.statusOK = ""
1673 // Pin the viewport to the newest content so the help block,
1674 // which we just appended to the end of the transcript, is
1675 // what the user actually sees.
1676 i.scrollOffset = 0
1677 i.mu.Unlock()
1678 case "/login":
1679 i.dialog.Open(i.cfg.ZotHome)
1680 case "/logout":
1681 if len(parts) >= 2 {
1682 // Explicit target: /logout anthropic | openai | all
1683 i.doLogout(parts[1])
1684 break
1685 }
1686 // No arg: open the picker over whichever providers are
1687 // currently logged in. If nothing's logged in, bail with a
1688 // status line.
1689 i.openLogoutDialog()
1690 case "/model":
1691 if len(parts) >= 2 {
1692 i.applyModelSelection("", parts[1])
1693 } else {
1694 i.modelDialog.Open(i.cfg.Model)
1695 }
1696 case "/sessions":
1697 i.sessionDialog.Open(i.cfg.ZotHome, i.cfg.CWD)
1698 case "/jump":
1699 i.openJumpDialog(parts[1:])
1700 case "/btw":
1701 i.openBtwDialog(parts[1:])
1702 case "/skills":
1703 i.openSkillsDialog()
1704 case "/compact":
1705 i.runCompact(ctx, false)
1706 case "/study":
1707 // Canned prompt that tells the agent to read every file
1708 // in the current directory so its later turns have the
1709 // whole project in context. Dispatched through the normal
1710 // queue-or-start path so it behaves identically to
1711 // typing the prompt by hand.
1712 const studyPrompt = "Read and understand everything in the current directory."
1713 i.mu.Lock()
1714 if i.busy {
1715 i.queued = append(i.queued, studyPrompt)
1716 i.mu.Unlock()
1717 i.invalidate()
1718 break
1719 }
1720 i.mu.Unlock()
1721 i.startTurn(ctx, studyPrompt)
1722 case "/jail":
1723 if i.cfg.Sandbox == nil {
1724 i.mu.Lock()
1725 i.statusErr = "sandbox not available in this build"
1726 i.mu.Unlock()
1727 break
1728 }
1729 i.cfg.Sandbox.Lock()
1730 i.mu.Lock()
1731 i.statusOK = "jailed to " + i.cfg.CWD + " (tools cannot touch paths outside this directory)"
1732 i.statusErr = ""
1733 i.mu.Unlock()
1734 case "/unjail":
1735 if i.cfg.Sandbox == nil {
1736 i.mu.Lock()
1737 i.statusErr = "sandbox not available in this build"
1738 i.mu.Unlock()
1739 break
1740 }
1741 i.cfg.Sandbox.Unlock()
1742 i.mu.Lock()
1743 i.statusOK = "unjailed"
1744 i.statusErr = ""
1745 i.mu.Unlock()
1746 case "/reload-ext":
1747 i.runReloadExt(ctx)
1748 case "/yolo":
1749 i.runYoloOn()
1750 case "/telegram", "/tg":
1751 if len(parts) >= 2 {
1752 i.doTelegram(parts[1])
1753 break
1754 }
1755 i.openTelegramDialog()
1756 case "/session":
1757 if len(parts) >= 2 {
1758 action := parts[1]
1759 arg := ""
1760 if len(parts) >= 3 {
1761 arg = strings.Join(parts[2:], " ")
1762 }
1763 i.doSessionOp(action, arg)
1764 break
1765 }
1766 i.openSessionOpsDialog()
1767 default:
1768 // Last-resort fallback: try the extension manager. Built-in
1769 // cases above always win; this branch only fires for slash
1770 // commands the extension manager registered. Same routing as
1771 // the editor's submit-handler dispatch path so the autocomplete
1772 // "enter on highlighted suggestion" flow also works.
1773 extName := strings.TrimPrefix(parts[0], "/")
1774 if i.cfg.Extensions != nil && i.cfg.Extensions.HasCommand(extName) {
1775 rest := ""
1776 if len(parts) > 1 {
1777 rest = strings.Join(parts[1:], " ")
1778 }
1779 go i.invokeExtensionCommand(ctx, extName, rest)
1780 return false
1781 }
1782 i.mu.Lock()
1783 i.statusErr = "unknown command: " + parts[0]
1784 i.mu.Unlock()
1785 }
1786 return false
1787}
1788
1789// openLogoutDialog shows the provider picker for `/logout` with no
1790// argument. Only providers the user is currently logged into are
1791// listed, plus an "all" entry when more than one is present. If
1792// nothing's logged in, writes a status line instead of opening an
1793// empty dialog.
1794func (i *Interactive) openLogoutDialog() {
1795 if i.cfg.AuthManager == nil {
1796 i.mu.Lock()
1797 i.statusErr = "no auth manager configured"
1798 i.mu.Unlock()
1799 i.invalidate()
1800 return
1801 }
1802 store := i.cfg.AuthManager.Store()
1803 if store == nil {
1804 i.mu.Lock()
1805 i.statusErr = "auth store is not available"
1806 i.mu.Unlock()
1807 i.invalidate()
1808 return
1809 }
1810 creds, err := store.Load()
1811 if err != nil {
1812 i.mu.Lock()
1813 i.statusErr = "read auth store: " + err.Error()
1814 i.mu.Unlock()
1815 i.invalidate()
1816 return
1817 }
1818
1819 var items []logoutItem
1820 for _, p := range []string{"anthropic", "openai"} {
1821 if creds.Has(p) {
1822 items = append(items, logoutItem{
1823 label: p,
1824 target: p,
1825 method: creds.Method(p),
1826 })
1827 }
1828 }
1829 if len(items) == 0 {
1830 i.mu.Lock()
1831 i.statusOK = "no credentials stored; already logged out"
1832 i.statusErr = ""
1833 i.mu.Unlock()
1834 i.invalidate()
1835 return
1836 }
1837 if len(items) > 1 {
1838 items = append(items, logoutItem{label: "all", target: "all"})
1839 }
1840
1841 i.logoutDialog.Open(items)
1842 i.invalidate()
1843}
1844
1845// doLogout clears credentials for the given provider (or all providers)
1846// from auth.json. If the active agent was using those credentials, it
1847// is torn down so the user is forced through /login before their next
1848// prompt.
1849//
1850// target: "anthropic" | "openai" | "all"
1851func (i *Interactive) doLogout(target string) {
1852 if i.cfg.AuthManager == nil {
1853 i.mu.Lock()
1854 i.statusErr = "no auth manager configured"
1855 i.mu.Unlock()
1856 return
1857 }
1858 store := i.cfg.AuthManager.Store()
1859 if store == nil {
1860 i.mu.Lock()
1861 i.statusErr = "auth store is not available"
1862 i.mu.Unlock()
1863 return
1864 }
1865
1866 var providers []string
1867 switch target {
1868 case "", "all":
1869 providers = []string{"anthropic", "openai"}
1870 case "anthropic", "openai":
1871 providers = []string{target}
1872 default:
1873 i.mu.Lock()
1874 i.statusErr = "unknown provider: " + target + " (use anthropic, openai, or all)"
1875 i.mu.Unlock()
1876 return
1877 }
1878
1879 var errs []string
1880 clearedCurrent := false
1881 for _, p := range providers {
1882 if err := store.Clear(p); err != nil {
1883 errs = append(errs, p+": "+err.Error())
1884 continue
1885 }
1886 if p == i.cfg.Provider {
1887 clearedCurrent = true
1888 }
1889 }
1890
1891 i.mu.Lock()
1892 defer i.mu.Unlock()
1893 if len(errs) > 0 {
1894 i.statusErr = "logout errors: " + strings.Join(errs, "; ")
1895 return
1896 }
1897 i.statusErr = ""
1898 if clearedCurrent {
1899 // The running agent was using a credential we just wiped. Drop
1900 // it so prompts can't go out with the stale client, and hint at
1901 // /login.
1902 i.agent = nil
1903 i.statusOK = "logged out of " + strings.Join(providers, ", ") + ". type /login to sign back in."
1904 } else {
1905 i.statusOK = "logged out of " + strings.Join(providers, ", ")
1906 }
1907}
1908
1909func (i *Interactive) startAPIKeyFlow(provider string) {
1910 url, err := i.cfg.AuthManager.StartAPIKey(provider)
1911 if err != nil {
1912 i.dialog.ShowResult(false, err.Error())
1913 return
1914 }
1915 i.dialog.ShowWaiting(url)
1916}
1917
1918func (i *Interactive) startOAuthFlow(provider string) {
1919 url, err := i.cfg.AuthManager.StartOAuth(provider)
1920 if err != nil {
1921 i.dialog.ShowResult(false, err.Error())
1922 return
1923 }
1924 i.dialog.ShowWaiting(url)
1925}
1926
1927// applyModelSelection switches the active model (and provider, if the
1928// new model belongs to a different one). It rebuilds the underlying
1929// client when needed so the provider wire-protocol matches.
1930// cancelAndWaitForIdle cancels the active turn (if any) and blocks
1931// briefly until the turn goroutine has updated i.busy = false. Used
1932// before destructive slash commands so transcript-mutating work
1933// (/clear, /compact, /logout, /login completion, cross-provider
1934// /model swap) doesn't race with the still-running stream.
1935//
1936// The wait is bounded; if the turn doesn't release within the timeout
1937// we proceed anyway. Worst case is a brief overlap that the agent's
1938// own mutex protects against.
1939func (i *Interactive) cancelAndWaitForIdle() {
1940 i.mu.Lock()
1941 busy := i.busy
1942 cancel := i.cancelTurn
1943 i.mu.Unlock()
1944 if !busy {
1945 return
1946 }
1947 if cancel != nil {
1948 cancel()
1949 }
1950 deadline := time.Now().Add(2 * time.Second)
1951 for time.Now().Before(deadline) {
1952 i.mu.Lock()
1953 done := !i.busy
1954 i.mu.Unlock()
1955 if done {
1956 return
1957 }
1958 time.Sleep(10 * time.Millisecond)
1959 }
1960}
1961
1962// openBtwDialog opens the side-chat overlay with a frozen snapshot
1963// of the current main session. The optional argument is auto-
1964// submitted as the first question, so '/btw does X work?' fires the
1965// model call immediately instead of just opening an empty dialog.
1966func (i *Interactive) openBtwDialog(args []string) {
1967 if i.agent == nil {
1968 i.mu.Lock()
1969 i.statusErr = "not logged in. type /login first."
1970 i.mu.Unlock()
1971 return
1972 }
1973 seed := strings.TrimSpace(strings.Join(args, " "))
1974 i.btwDialog.Open(i.cfg.Theme, i.agent, i.agent.System, i.cfg.Model, seed, i.invalidate)
1975 i.invalidate()
1976}
1977
1978// openSkillsDialog opens the skill inspector. The picker reflects
1979// whatever SkillSnapshot returns at call time, so edits to a
1980// SKILL.md made during a session show up on the next /skills.
1981func (i *Interactive) openSkillsDialog() {
1982 var list []*skills.Skill
1983 if i.cfg.SkillSnapshot != nil {
1984 list = i.cfg.SkillSnapshot()
1985 }
1986 i.skillsDialog.Open(list)
1987 i.invalidate()
1988}
1989
1990// openJumpDialog builds a /jump picker from the current transcript.
1991// If the user typed "/jump foo" with a filter and it matches exactly
1992// one turn, jump there directly without showing the dialog.
1993func (i *Interactive) openJumpDialog(args []string) {
1994 if i.view == nil || len(i.view.Messages) == 0 {
1995 i.mu.Lock()
1996 i.statusErr = "nothing to jump to \u2014 the session is empty"
1997 i.mu.Unlock()
1998 return
1999 }
2000 filter := strings.TrimSpace(strings.Join(args, " "))
2001 i.jumpDialog.Open(i.view.Messages, filter)
2002 // Shortcut: with a filter argument that matches exactly one turn,
2003 // jump immediately and skip the picker.
2004 if filter != "" {
2005 if tgts := i.jumpDialog.Targets(); len(tgts) == 1 {
2006 t := tgts[0]
2007 i.jumpDialog.Close()
2008 i.applyJumpSelection(t.MessageIdx, t.TurnNo)
2009 }
2010 }
2011}
2012
2013// applyJumpSelection scrolls the chat viewport so the user message at
2014// msgIdx is visible at (or near) the top of the chat area. Uses the
2015// anchor slice returned by view.BuildWithAnchors so the mapping from
2016// message index to row is exact, regardless of variable-height tool
2017// blocks above the target.
2018func (i *Interactive) applyJumpSelection(msgIdx, turnNo int) {
2019 cols := i.lastCols()
2020 chat, anchors := i.view.BuildWithAnchors(cols)
2021 var row int
2022 found := false
2023 for _, a := range anchors {
2024 if a.MessageIdx == msgIdx {
2025 row = a.Row
2026 found = true
2027 break
2028 }
2029 }
2030 if !found {
2031 i.mu.Lock()
2032 i.statusErr = "could not resolve jump target"
2033 i.mu.Unlock()
2034 return
2035 }
2036
2037 chatLen := len(chat)
2038 page := i.chatPage()
2039 if page < 1 {
2040 page = 1
2041 }
2042 // scrollOffset is measured from the bottom of the chat slice, so
2043 // to place `row` at the top of the viewport we want:
2044 // chatLen - scrollOffset - page == row
2045 // Solve for scrollOffset and clamp to [0, chatLen-page].
2046 offset := chatLen - (row + page)
2047 if offset < 0 {
2048 offset = 0
2049 }
2050 maxOffset := chatLen - page
2051 if maxOffset < 0 {
2052 maxOffset = 0
2053 }
2054 if offset > maxOffset {
2055 offset = maxOffset
2056 }
2057
2058 i.mu.Lock()
2059 i.scrollOffset = offset
2060 i.parkedTurn = turnNo
2061 i.parkedTotal = totalTurnsLocked(i.view.Messages)
2062 i.statusOK = fmt.Sprintf("jumped to turn %d", turnNo)
2063 i.statusErr = ""
2064 i.mu.Unlock()
2065}
2066
2067// totalTurnsLocked counts user messages in the transcript. Caller is
2068// assumed to hold i.mu (the name is a mild reminder; this function
2069// itself doesn't touch shared state beyond the slice it's handed).
2070func totalTurnsLocked(msgs []provider.Message) int {
2071 n := 0
2072 for _, m := range msgs {
2073 if m.Role == provider.RoleUser {
2074 n++
2075 }
2076 }
2077 return n
2078}
2079
2080// applySessionSelection loads the given session via the cli-provided
2081// callback and parks the viewport on the last turn so the user lands
2082// looking at where the conversation left off (their last prompt at the
2083// top of the chat, the assistant's last reply right below). Older
2084// history is one scroll up; pgdn or end snaps to the current tail.
2085//
2086// Without this, scrollOffset stayed at 0 (pinned to the live tail),
2087// which on a long resumed session showed only the last few rows of
2088// the final assistant message — the user read that as "only one liner
2089// happened, the resume didn't work".
2090func (i *Interactive) applySessionSelection(path string) {
2091 if i.cfg.LoadSession == nil {
2092 i.mu.Lock()
2093 i.statusErr = "session loading is not wired in this build"
2094 i.mu.Unlock()
2095 return
2096 }
2097 if err := i.cfg.LoadSession(path); err != nil {
2098 i.mu.Lock()
2099 i.statusErr = err.Error()
2100 i.mu.Unlock()
2101 return
2102 }
2103
2104 i.mu.Lock()
2105 i.statusOK = "resumed session: " + path
2106 i.statusErr = ""
2107 i.parkedTurn = 0
2108 i.parkedTotal = 0
2109 i.view.InvalidateRenderCache()
2110 // Pull the freshly-loaded transcript into the view so the anchor
2111 // math below sees the post-resume messages, not the empty pre-load
2112 // state. redraw() does the same on its next pass; we just front-run
2113 // it here to compute the scroll target.
2114 if i.agent != nil {
2115 i.view.Messages = i.agent.Messages()
2116 }
2117 msgs := i.view.Messages
2118 i.mu.Unlock()
2119
2120 i.scrollToLastTurn(msgs)
2121}
2122
2123// scrollToLastTurn parks the viewport at the most recent user turn,
2124// or at the top if the transcript has no user messages. Used after
2125// resume so the user lands looking at where they left off.
2126func (i *Interactive) scrollToLastTurn(msgs []provider.Message) {
2127 if len(msgs) == 0 {
2128 i.mu.Lock()
2129 i.scrollOffset = 0
2130 i.mu.Unlock()
2131 return
2132 }
2133 // Find the last user message index.
2134 lastUser := -1
2135 turnNo, totalTurns := 0, 0
2136 for idx, m := range msgs {
2137 if m.Role == provider.RoleUser {
2138 totalTurns++
2139 lastUser = idx
2140 }
2141 }
2142 if lastUser < 0 {
2143 i.mu.Lock()
2144 i.scrollOffset = 0
2145 i.mu.Unlock()
2146 return
2147 }
2148 turnNo = totalTurns
2149
2150 cols := i.lastCols()
2151 chat, anchors := i.view.BuildWithAnchors(cols)
2152 var row int
2153 found := false
2154 for _, a := range anchors {
2155 if a.MessageIdx == lastUser {
2156 row = a.Row
2157 found = true
2158 break
2159 }
2160 }
2161 if !found {
2162 i.mu.Lock()
2163 i.scrollOffset = 0
2164 i.mu.Unlock()
2165 return
2166 }
2167
2168 chatLen := len(chat)
2169 page := i.chatPage()
2170 if page < 1 {
2171 page = 1
2172 }
2173 offset := chatLen - (row + page)
2174 if offset < 0 {
2175 offset = 0
2176 }
2177 maxOffset := chatLen - page
2178 if maxOffset < 0 {
2179 maxOffset = 0
2180 }
2181 if offset > maxOffset {
2182 offset = maxOffset
2183 }
2184
2185 i.mu.Lock()
2186 i.scrollOffset = offset
2187 // Mark the parked-turn footer so the user sees "viewing turn N of
2188 // M - pgdn to catch up" — same affordance as /jump. Tells them at
2189 // a glance that they're looking at history, not the live tail.
2190 if offset > 0 {
2191 i.parkedTurn = turnNo
2192 i.parkedTotal = totalTurns
2193 }
2194 i.mu.Unlock()
2195 i.invalidate()
2196}
2197
2198func (i *Interactive) applyModelSelection(prov, model string) {
2199 if model == "" {
2200 return
2201 }
2202 m, err := provider.FindModel(prov, model)
2203 if err != nil {
2204 i.mu.Lock()
2205 i.statusErr = err.Error()
2206 i.mu.Unlock()
2207 return
2208 }
2209 // Same provider? Just swap the model on the existing agent.
2210 if i.agent != nil && m.Provider == i.cfg.Provider {
2211 i.mu.Lock()
2212 i.cfg.Model = m.ID
2213 i.agent.Model = m.ID
2214 i.statusOK = "model: " + m.ID
2215 i.statusErr = ""
2216 i.mu.Unlock()
2217 if i.cfg.PersistModel != nil {
2218 i.cfg.PersistModel(i.cfg.Provider, m.ID)
2219 }
2220 return
2221 }
2222 // Different provider: rebuild agent (needs credentials for target provider).
2223 if i.cfg.BuildAgentFor == nil {
2224 i.mu.Lock()
2225 i.statusErr = "cannot switch provider: no builder configured"
2226 i.mu.Unlock()
2227 return
2228 }
2229 // Snapshot the current transcript and cumulative usage BEFORE we
2230 // build the replacement agent so we can hand them off. Without
2231 // this the user perceives the entire session as wiped on a
2232 // cross-provider /model swap.
2233 var carryMsgs []provider.Message
2234 var carryCost provider.Usage
2235 if i.agent != nil {
2236 carryMsgs = i.agent.Messages()
2237 carryCost = i.agent.Cost()
2238 }
2239
2240 ag, p, md, err := i.cfg.BuildAgentFor(m.Provider, m.ID)
2241 if err != nil {
2242 i.mu.Lock()
2243 i.statusErr = err.Error()
2244 i.mu.Unlock()
2245 return
2246 }
2247
2248 // Replay the transcript and seed the cost on the freshly-built
2249 // agent. Messages travel cleanly between providers because they
2250 // use the same provider.Message shape; tool-call ids are local
2251 // to a turn so cross-provider continuation never confuses the
2252 // new model (it just sees the assistant's reply, no orphan
2253 // tool_use blocks because /model swaps are gated to idle state).
2254 if len(carryMsgs) > 0 {
2255 ag.SetMessages(carryMsgs)
2256 }
2257 ag.SeedCost(carryCost)
2258
2259 i.mu.Lock()
2260 i.agent = ag
2261 i.cfg.Provider = p
2262 i.cfg.Model = md
2263 i.statusOK = "switched to " + p + " / " + md
2264 i.statusErr = ""
2265 // Render cache keys are width+content based, so the new agent's
2266 // identical messages will reuse the existing entries. Nothing
2267 // to invalidate.
2268 i.mu.Unlock()
2269 if i.cfg.PersistModel != nil {
2270 i.cfg.PersistModel(p, md)
2271 }
2272}
2273
2274func (i *Interactive) handleAuthEvent(ev auth.Event) {
2275 switch ev.Kind {
2276 case "started":
2277 i.dialog.ShowWaiting(ev.URL)
2278 case "browser_open":
2279 // no-op
2280 case "error":
2281 i.dialog.ShowResult(false, ev.Message)
2282 case "success":
2283 // Rebuild the agent with the fresh credential.
2284 ag, prov, model, err := i.cfg.BuildAgent()
2285 if err != nil {
2286 i.dialog.ShowResult(false, err.Error())
2287 return
2288 }
2289 i.mu.Lock()
2290 i.agent = ag
2291 i.cfg.Provider = prov
2292 i.cfg.Model = model
2293 i.statusErr = ""
2294 i.statusOK = "logged in to " + ev.Provider + " via " + ev.Method
2295 i.mu.Unlock()
2296 i.dialog.ShowResult(true, "")
2297 }
2298}
2299
2300// runCompact invokes core.Agent.Compact and reflects the progress in
2301// the tui. It runs in a goroutine so the ui stays responsive; esc/ctrl+c
2302// cancel via the same cancelTurn channel used for normal turns.
2303//
2304// When auto is true the spinner message is pinned to "condensing
2305// history" and the status bar surfaces "(auto)" next to the context
2306// percentage so it's obvious the system triggered this, not the user.
2307func (i *Interactive) runCompact(parent context.Context, auto bool) {
2308 if i.agent == nil {
2309 i.mu.Lock()
2310 i.statusErr = "not logged in. type /login first."
2311 i.mu.Unlock()
2312 return
2313 }
2314 ctx, cancel := context.WithCancel(parent)
2315 i.mu.Lock()
2316 i.busy = true
2317 if auto {
2318 i.spin.StartFixed("condensing history")
2319 i.autoCompacting = true
2320 i.statusOK = "condensing history… (esc to cancel)"
2321 } else {
2322 i.spin.Start()
2323 i.statusOK = "compacting..."
2324 }
2325 i.cancelTurn = cancel
2326 i.statusErr = ""
2327 i.streaming.Reset()
2328 i.streamOn = true
2329 i.scrollOffset = 0
2330 i.helpBlock = nil
2331 i.mu.Unlock()
2332 i.invalidate()
2333
2334 go func() {
2335 sink := func(delta string) {
2336 i.mu.Lock()
2337 i.streaming.WriteString(delta)
2338 i.mu.Unlock()
2339 i.invalidate()
2340 }
2341 summary, err := i.agent.Compact(ctx, 4, sink)
2342 i.mu.Lock()
2343 i.busy = false
2344 i.resetStreamingStateLocked()
2345 i.cancelTurn = nil
2346 i.autoCompacting = false
2347 switch {
2348 case err != nil && ctx.Err() != nil:
2349 i.statusErr = ""
2350 if auto {
2351 i.statusOK = "auto-condense cancelled"
2352 } else {
2353 i.statusOK = "compaction cancelled"
2354 }
2355 case err != nil:
2356 i.statusErr = "compaction failed: " + err.Error()
2357 i.statusOK = ""
2358 default:
2359 i.statusErr = ""
2360 i.statusOK = fmt.Sprintf("compacted transcript (%d chars of summary)", len(summary))
2361 i.lastCtxInput = 0 // reset; next turn will get a fresh measurement
2362 i.toolCalls = map[string]*tui.ToolCallView{}
2363 i.toolOrder = nil
2364 // Transcript was rewritten in place — purge the per-message
2365 // render cache so stale entries keyed on the old messages
2366 // don't linger.
2367 i.view.InvalidateRenderCache()
2368 }
2369 i.mu.Unlock()
2370 i.invalidate()
2371 }()
2372}
2373
2374func (i *Interactive) startTurn(parent context.Context, prompt string) {
2375 if i.agent == nil {
2376 return
2377 }
2378 ctx, cancel := context.WithCancel(parent)
2379 i.mu.Lock()
2380 i.busy = true
2381 i.spin.Start()
2382 i.cancelTurn = cancel
2383 i.statusErr = ""
2384 i.statusOK = ""
2385 i.streaming.Reset()
2386 i.streamOn = true
2387 i.toolCalls = map[string]*tui.ToolCallView{}
2388 i.toolOrder = nil
2389 i.scrollOffset = 0 // jump back to the bottom on new turn
2390 i.parkedTurn = 0 // starting a turn clears the /jump parked state
2391 i.parkedTotal = 0
2392 i.helpBlock = nil // hide the help block once the user asks something
2393 i.mu.Unlock()
2394 i.invalidate()
2395
2396 sink := func(ev core.AgentEvent) {
2397 i.handleEvent(ev)
2398 i.invalidate()
2399 }
2400
2401 go func() {
2402 err := i.agent.Prompt(ctx, prompt, nil, sink)
2403 i.mu.Lock()
2404 i.busy = false
2405 // Don't touch streamPending / streamFlushPending here — the
2406 // pacer may still be draining the final deltas and needs to
2407 // paint them even though Prompt has returned. It will reset
2408 // streamOn on its own once the buffer empties.
2409 if len(i.streamPending) == 0 {
2410 i.streamOn = false
2411 }
2412 i.cancelTurn = nil
2413 if err != nil && ctx.Err() == nil {
2414 i.statusErr = err.Error()
2415 }
2416 // Persist the assistant's reply (and every tool row before
2417 // it) to the session file while the turn memory is hot.
2418 // Without this, WriteNewTranscript only fires at zot exit,
2419 // meaning a crash or ungraceful kill drops the whole
2420 // conversation. FlushSession is idempotent (it advances the
2421 // baseline so subsequent flushes only write new rows).
2422 flush := i.cfg.FlushSession
2423 i.mu.Unlock()
2424 if flush != nil {
2425 flush()
2426 }
2427 i.mu.Lock()
2428 // Pop the next queued message, if any, and relaunch.
2429 var next string
2430 var hasNext bool
2431 if len(i.queued) > 0 && ctx.Err() == nil && err == nil {
2432 next, i.queued = i.queued[0], i.queued[1:]
2433 hasNext = true
2434 }
2435 // If the turn was cancelled or errored, drop the queue so the
2436 // user isn't bombarded with stale messages after an interrupt.
2437 if ctx.Err() != nil || err != nil {
2438 i.queued = nil
2439 }
2440 // Decide whether the next thing to do is an auto-compaction.
2441 // Only fires when the turn completed cleanly AND the queue is
2442 // empty (otherwise a queued message would race the condense).
2443 shouldAutoCompact := !hasNext && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
2444 i.mu.Unlock()
2445 i.invalidate()
2446 parent := i.runCtx
2447 if parent == nil {
2448 parent = context.Background()
2449 }
2450 switch {
2451 case hasNext:
2452 i.startTurn(parent, next)
2453 case shouldAutoCompact:
2454 i.runCompact(parent, true)
2455 }
2456 }()
2457}
2458
2459// autoCompactThreshold is the context-window fraction at which the
2460// agent will auto-compact after a turn ends. 0.85 leaves enough
2461// headroom for one more user prompt + response before we bump the
2462// hard limit.
2463const autoCompactThreshold = 0.85
2464
2465// shouldAutoCompactLocked reports whether the last turn pushed context
2466// usage past the auto-compact threshold. Must be called with i.mu
2467// held; it reads lastCtxInput and the current model's context window.
2468func (i *Interactive) shouldAutoCompactLocked() bool {
2469 if i.agent == nil {
2470 return false
2471 }
2472 if i.autoCompacting {
2473 return false
2474 }
2475 m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
2476 if err != nil || m.ContextWindow <= 0 {
2477 return false
2478 }
2479 if i.lastCtxInput <= 0 {
2480 return false
2481 }
2482 return float64(i.lastCtxInput)/float64(m.ContextWindow) >= autoCompactThreshold
2483}
2484
2485func (i *Interactive) handleEvent(ev core.AgentEvent) {
2486 i.mu.Lock()
2487 defer i.mu.Unlock()
2488 switch e := ev.(type) {
2489 case core.EvAssistantStart:
2490 // Fires at the top of every oneTurn, including follow-up
2491 // turns after tool use. Without this, the streaming buffer
2492 // is still marked off from the previous assistant message
2493 // and the final summary text pops in all at once instead
2494 // of typewriter-streaming delta by delta.
2495 i.streaming.Reset()
2496 i.streamPending = i.streamPending[:0]
2497 i.streamFlushPending = false
2498 i.streamOn = true
2499 // Clear the live tool-call overlay. Any tools from the
2500 // previous round are now fully folded into the transcript
2501 // (assistant tool_use block + tool role message with the
2502 // result), so keeping them in the overlay would duplicate
2503 // them in the view — once inside the finalised transcript
2504 // and once below the streaming block, with the streaming
2505 // summary sandwiched in between. The next EvToolUseStart
2506 // will populate fresh entries for this turn's tools.
2507 i.toolCalls = map[string]*tui.ToolCallView{}
2508 i.toolOrder = nil
2509 case core.EvTextDelta:
2510 // Buffer into streamPending; the paintPace ticker drains
2511 // it into i.streaming a few runes at a time for a smooth
2512 // typewriter effect independent of upstream chunk size.
2513 i.streamPending = append(i.streamPending, []rune(e.Delta)...)
2514 i.streamOn = true
2515 case core.EvAssistantMessage:
2516 // OnAssistant + telegram mirroring always fire on message
2517 // arrival — they read the FINAL message content, which is
2518 // complete regardless of what's still in the pacer.
2519 i.assistantMessageSideEffects(e.Message)
2520 // If the pacer still has characters to drain, keep streamOn
2521 // true and mark flush pending; the paintPace ticker will
2522 // drain the remainder and reset streaming state when done.
2523 // Otherwise (rare: full-replay sessions, abort paths) clear
2524 // synchronously so a later render doesn't show stale text.
2525 if len(i.streamPending) > 0 {
2526 i.streamFlushPending = true
2527 return
2528 }
2529 i.resetStreamingStateLocked()
2530 case core.EvToolUseStart:
2531 // Live streaming: pre-create the view so the user sees the
2532 // tool call being composed in real time. Any subsequent
2533 // EvToolCall for the same ID updates the same struct (the
2534 // final parsed args + name are already known here).
2535 if _, exists := i.toolCalls[e.ID]; !exists {
2536 i.toolCalls[e.ID] = &tui.ToolCallView{
2537 ID: e.ID,
2538 Name: e.Name,
2539 Streaming: true,
2540 }
2541 i.toolOrder = append(i.toolOrder, e.ID)
2542 }
2543 case core.EvToolUseArgs:
2544 if tc, ok := i.toolCalls[e.ID]; ok {
2545 tc.RawJSONBuf += e.Delta
2546 // Refresh the live path as soon as it parses; used in
2547 // the header (write /Users/pat/Desktop/demo.ts)
2548 // while the content is still streaming.
2549 if p, pok, _ := tui.ExtractPartialStringField(tc.RawJSONBuf, "path"); pok {
2550 tc.LivePath = p
2551 } else if p, pok, _ := tui.ExtractPartialStringField(tc.RawJSONBuf, "file_path"); pok {
2552 tc.LivePath = p
2553 }
2554 }
2555 case core.EvToolUseEnd:
2556 if tc, ok := i.toolCalls[e.ID]; ok {
2557 tc.Streaming = false
2558 }
2559 case core.EvToolCall:
2560 // If we already pre-created the view during streaming, just
2561 // refresh the final Args summary. Otherwise create a new one
2562 // (non-streaming providers or legacy paths).
2563 if tc, ok := i.toolCalls[e.ID]; ok {
2564 tc.Args = tui.ShortArgs(e.Name, e.Args)
2565 tc.Streaming = false
2566 } else {
2567 i.toolCalls[e.ID] = &tui.ToolCallView{
2568 ID: e.ID,
2569 Name: e.Name,
2570 Args: tui.ShortArgs(e.Name, e.Args),
2571 }
2572 i.toolOrder = append(i.toolOrder, e.ID)
2573 }
2574 case core.EvToolResult:
2575 if tc, ok := i.toolCalls[e.ID]; ok {
2576 tc.Done = true
2577 tc.Error = e.Result.IsError
2578 var text strings.Builder
2579 for _, c := range e.Result.Content {
2580 if tb, ok := c.(provider.TextBlock); ok {
2581 if text.Len() > 0 {
2582 text.WriteString("\n")
2583 }
2584 text.WriteString(tb.Text)
2585 }
2586 }
2587 tc.Result = text.String()
2588 }
2589 if i.cfg.OnToolResult != nil {
2590 i.cfg.OnToolResult(e.ID, e.Result)
2591 }
2592 case core.EvUsage:
2593 i.cumUsage = e.Cumulative
2594 if e.Usage.InputTokens > 0 {
2595 i.lastCtxInput = e.Usage.InputTokens + e.Usage.CacheReadTokens + e.Usage.CacheWriteTokens
2596 }
2597 case core.EvTurnEnd:
2598 if e.Stop == provider.StopAborted {
2599 // Aborted turn: discard the partial streaming text (it
2600 // is not persisted in the transcript) and clear any
2601 // transient error. Also drop anything still buffered in
2602 // the pacer so nothing keeps drawing after the cancel.
2603 i.resetStreamingStateLocked()
2604 i.statusErr = ""
2605 i.statusOK = "cancelled"
2606 return
2607 }
2608 if e.Err != nil && !strings.Contains(e.Err.Error(), "context canceled") {
2609 i.statusErr = e.Err.Error()
2610 }
2611 }
2612}
2613
2614// Agent returns the current agent, if any. Used by cli.go to flush the
2615// final transcript to the session file.
2616func (i *Interactive) Agent() *core.Agent {
2617 i.mu.Lock()
2618 defer i.mu.Unlock()
2619 return i.agent
2620}
2621
2622// silence unused import in some build configs
2623var _ = fmt.Sprintf
2624
2625// runReloadExt triggers a live reload of every extension (discovered
2626// + explicit). Runs on a goroutine so the TUI stays responsive; the
2627// Manager.Reload takes a couple of hundred ms to shut down subprocs
2628// and respawn them. Shows a status line throughout.
2629func (i *Interactive) runReloadExt(ctx context.Context) {
2630 if i.cfg.Extensions == nil {
2631 i.mu.Lock()
2632 i.statusErr = "no extension manager in this build"
2633 i.mu.Unlock()
2634 i.invalidate()
2635 return
2636 }
2637 i.mu.Lock()
2638 i.statusOK = "reloading extensions…"
2639 i.statusErr = ""
2640 i.mu.Unlock()
2641 i.invalidate()
2642
2643 go func() {
2644 stats := i.cfg.Extensions.Reload(ctx, 2*time.Second)
2645 msg := fmt.Sprintf("reloaded: %d stopped, %d loaded (%d ready)", stats.Stopped, stats.Loaded, stats.Ready)
2646 if len(stats.Errors) > 0 {
2647 msg += fmt.Sprintf(", %d error(s)", len(stats.Errors))
2648 }
2649 i.mu.Lock()
2650 i.statusOK = msg
2651 i.statusErr = ""
2652 i.mu.Unlock()
2653 i.invalidate()
2654 }()
2655}
2656
2657// Confirm implements core.Confirmer. The agent goroutine calls
2658// this synchronously before every tool invocation when --no-yolo is
2659// active. We push the request onto the confirmDialog queue, trigger
2660// a redraw, and block the caller until the user answers.
2661//
2662// If the session is cancelled or the TUI exits mid-prompt, any
2663// pending request is refused via CancelAll so the agent doesn't
2664// deadlock.
2665func (i *Interactive) Confirm(toolName string, preview string) core.ConfirmDecision {
2666 resp := make(chan core.ConfirmDecision, 1)
2667 i.confirmDialog.Enqueue(&confirmRequest{
2668 toolName: toolName,
2669 preview: preview,
2670 resp: resp,
2671 })
2672 i.invalidate()
2673 return <-resp
2674}
2675
2676// runYoloOn disables --no-yolo for the rest of the session. Tool
2677// calls run without prompting after this; there's intentionally no
2678// way to re-enable gating mid-session, if the user wants that back
2679// they can exit and restart with --no-yolo.
2680func (i *Interactive) runYoloOn() {
2681 if i.cfg.ConfirmGate == nil {
2682 i.mu.Lock()
2683 i.statusOK = "yolo mode is already on (no --no-yolo in this session)"
2684 i.statusErr = ""
2685 i.mu.Unlock()
2686 i.invalidate()
2687 return
2688 }
2689 i.cfg.ConfirmGate.AllowAll()
2690 // Also auto-allow any currently pending confirmation so the
2691 // agent doesn't deadlock if /yolo is typed while a prompt is
2692 // open.
2693 i.confirmDialog.AllowAllPending()
2694 i.mu.Lock()
2695 i.statusOK = "yolo engaged: no more tool-call confirmations this session"
2696 i.statusErr = ""
2697 i.mu.Unlock()
2698 i.invalidate()
2699}
2700
2701// openTelegramDialog shows the picker for `/telegram` with no arg.
2702// Items depend on current state: disconnect + status when running,
2703// connect + status when stopped.
2704func (i *Interactive) openTelegramDialog() {
2705 items := i.telegramMenuItems()
2706 if len(items) == 0 {
2707 i.mu.Lock()
2708 i.statusErr = "telegram not configured. run `zot telegram-bot setup` first."
2709 i.mu.Unlock()
2710 i.invalidate()
2711 return
2712 }
2713 i.telegramDialog.Open(items)
2714 i.invalidate()
2715}
2716
2717// telegramMenuItems builds the dialog entries for the current
2718// bridge state. Returns empty when no bot.json exists so the
2719// caller can show a helpful status line instead of an empty menu.
2720func (i *Interactive) telegramMenuItems() []telegramItem {
2721 cfg, err := telegram.LoadConfig(i.cfg.ZotHome)
2722 if err != nil || cfg.BotToken == "" {
2723 return nil
2724 }
2725 var items []telegramItem
2726 if i.telegramBridge != nil && i.telegramBridge.Active() {
2727 items = append(items, telegramItem{label: "disconnect", action: "disconnect", hint: "stop mirroring"})
2728 st := i.telegramBridge.State()
2729 hint := "active"
2730 if st.Username != "" {
2731 hint += " as @" + st.Username
2732 }
2733 items = append(items, telegramItem{label: "status", action: "status", hint: hint})
2734 } else {
2735 label := "connect"
2736 hint := "start mirroring dms into this session"
2737 if cfg.AllowedUserID == 0 {
2738 hint = "awaiting pairing (send /start to the bot once connected)"
2739 }
2740 items = append(items, telegramItem{label: label, action: "connect", hint: hint})
2741 items = append(items, telegramItem{label: "status", action: "status", hint: "disconnected"})
2742 }
2743 return items
2744}
2745
2746// doTelegram dispatches one of the three explicit actions. Called
2747// from /telegram <action> or after the picker selects a row.
2748func (i *Interactive) doTelegram(action string) {
2749 switch action {
2750 case "connect":
2751 i.telegramConnect()
2752 case "disconnect":
2753 i.telegramDisconnect()
2754 case "status":
2755 i.telegramStatus()
2756 default:
2757 i.mu.Lock()
2758 i.statusErr = "unknown telegram action: " + action + " (use connect, disconnect, or status)"
2759 i.mu.Unlock()
2760 i.invalidate()
2761 }
2762}
2763
2764// telegramConnect starts the bridge. Refuses if it's already
2765// running or if the on-disk bot.json is missing a token.
2766func (i *Interactive) telegramConnect() {
2767 if i.telegramBridge != nil && i.telegramBridge.Active() {
2768 i.mu.Lock()
2769 i.statusOK = "telegram already connected"
2770 i.statusErr = ""
2771 i.mu.Unlock()
2772 i.invalidate()
2773 return
2774 }
2775 cfg, err := telegram.LoadConfig(i.cfg.ZotHome)
2776 if err != nil {
2777 i.mu.Lock()
2778 i.statusErr = "telegram: " + err.Error()
2779 i.mu.Unlock()
2780 i.invalidate()
2781 return
2782 }
2783 if cfg.BotToken == "" {
2784 i.mu.Lock()
2785 i.statusErr = "telegram: no bot token configured. run `zot telegram-bot setup` first."
2786 i.mu.Unlock()
2787 i.invalidate()
2788 return
2789 }
2790 // Refuse to start when a background daemon is already polling
2791 // the same bot. Two concurrent long-poll consumers race each
2792 // update and one always loses, so DMs get half-delivered. The
2793 // user can `zot telegram-bot stop` first, then /telegram connect.
2794 if pid, alive, _ := telegram.IsRunning(i.cfg.ZotHome); alive && pid > 0 {
2795 i.mu.Lock()
2796 i.statusErr = fmt.Sprintf("telegram: bot daemon already running (pid %d). stop it with `zot telegram-bot stop` first.", pid)
2797 i.mu.Unlock()
2798 i.invalidate()
2799 return
2800 }
2801 i.telegramBridge = &telegram.Bridge{
2802 Client: telegram.NewClient(cfg.BotToken),
2803 Config: cfg,
2804 Save: func(next telegram.Config) error {
2805 return telegram.SaveConfig(i.cfg.ZotHome, next)
2806 },
2807 Host: &telegramHost{iv: i},
2808 }
2809 if err := i.telegramBridge.Start(i.runCtx); err != nil {
2810 i.telegramBridge = nil
2811 i.mu.Lock()
2812 i.statusErr = "telegram connect failed: " + err.Error()
2813 i.mu.Unlock()
2814 i.invalidate()
2815 return
2816 }
2817 state := i.telegramBridge.State()
2818 label := "telegram connected"
2819 if state.Username != "" {
2820 label += " as @" + state.Username
2821 }
2822 if state.PairedID == 0 {
2823 label += " — send /start to the bot from your phone to claim it"
2824 }
2825 i.mu.Lock()
2826 i.statusOK = label
2827 i.statusErr = ""
2828 i.mu.Unlock()
2829 i.invalidate()
2830}
2831
2832// telegramDisconnect stops the bridge. No-op when already stopped.
2833func (i *Interactive) telegramDisconnect() {
2834 if i.telegramBridge == nil || !i.telegramBridge.Active() {
2835 i.mu.Lock()
2836 i.statusOK = "telegram already disconnected"
2837 i.statusErr = ""
2838 i.mu.Unlock()
2839 i.invalidate()
2840 return
2841 }
2842 i.telegramBridge.Stop()
2843 i.mu.Lock()
2844 i.statusOK = "telegram disconnected"
2845 i.statusErr = ""
2846 i.mu.Unlock()
2847 i.invalidate()
2848}
2849
2850// telegramStatus writes a one-liner describing the bridge state.
2851// Reports on both the in-tui bridge and the background daemon so
2852// the user isn't confused when the daemon owns the poll loop.
2853func (i *Interactive) telegramStatus() {
2854 var msg string
2855 if i.telegramBridge != nil && i.telegramBridge.Active() {
2856 s := i.telegramBridge.State()
2857 msg = "telegram: connected (tui bridge)"
2858 if s.Username != "" {
2859 msg += " as @" + s.Username
2860 }
2861 if s.PairedID != 0 {
2862 msg += fmt.Sprintf(" - paired with user %d", s.PairedID)
2863 } else {
2864 msg += " - awaiting pairing"
2865 }
2866 } else if pid, alive, _ := telegram.IsRunning(i.cfg.ZotHome); alive && pid > 0 {
2867 msg = fmt.Sprintf("telegram: background daemon running (pid %d) - /telegram connect won't work until you stop it", pid)
2868 } else {
2869 cfg, _ := telegram.LoadConfig(i.cfg.ZotHome)
2870 if cfg.BotToken == "" {
2871 msg = "telegram: not configured. run `zot telegram-bot setup` first."
2872 } else {
2873 msg = "telegram: disconnected"
2874 if cfg.BotUsername != "" {
2875 msg += " (@" + cfg.BotUsername + " ready to connect)"
2876 }
2877 }
2878 }
2879 i.mu.Lock()
2880 i.statusOK = msg
2881 i.statusErr = ""
2882 i.mu.Unlock()
2883 i.invalidate()
2884}
2885
2886// telegramHost adapts *Interactive to telegram.Host so the bridge
2887// can call back into the TUI without importing modes directly.
2888type telegramHost struct{ iv *Interactive }
2889
2890func (h *telegramHost) SubmitOrQueue(prompt string, images []provider.ImageBlock) {
2891 h.iv.SubmitOrQueue(prompt, images)
2892}
2893
2894func (h *telegramHost) CancelTurn() { h.iv.CancelTurn() }
2895
2896func (h *telegramHost) Notify(level, message string) {
2897 h.iv.mu.Lock()
2898 switch level {
2899 case "error", "warn":
2900 h.iv.statusErr = message
2901 h.iv.statusOK = ""
2902 default:
2903 h.iv.statusOK = message
2904 h.iv.statusErr = ""
2905 }
2906 h.iv.mu.Unlock()
2907 h.iv.invalidate()
2908}
2909
2910// openSessionOpsDialog shows the picker for `/session` with no arg.
2911// Always offers export, import, fork, tree; the handlers bail with
2912// a clear status message when the precondition isn't met (empty
2913// transcript on fork; no parent/siblings on tree).
2914func (i *Interactive) openSessionOpsDialog() {
2915 items := []sessionOpsItem{
2916 {label: "export", action: "export", hint: "write the current session to a .zotsession file"},
2917 {label: "import", action: "import", hint: "load a .zotsession file into this directory"},
2918 {label: "fork", action: "fork", hint: "branch from a past user message into a new session"},
2919 {label: "tree", action: "tree", hint: "switch between branches in this directory"},
2920 }
2921 i.sessionOpsDialog.Open(items)
2922 i.invalidate()
2923}
2924
2925// doSessionOp dispatches export, import, fork, or tree. arg is the
2926// optional positional argument from e.g. /session export <path>
2927// or /session import <path>; fork and tree ignore it.
2928func (i *Interactive) doSessionOp(action, arg string) {
2929 switch action {
2930 case "export":
2931 i.doSessionExport(arg)
2932 case "import":
2933 i.doSessionImport(arg)
2934 case "fork":
2935 i.doSessionFork()
2936 case "tree":
2937 i.doSessionTree()
2938 default:
2939 i.mu.Lock()
2940 i.statusErr = "unknown /session action: " + action + " (use export, import, fork, or tree)"
2941 i.mu.Unlock()
2942 i.invalidate()
2943 }
2944}
2945
2946// doSessionExport writes the live session file to destination path
2947// dst. When dst is empty we default to ~/Downloads (falling back to
2948// the user's home directory if it doesn't exist). The helper
2949// expands a leading `~` and creates any missing parent directories.
2950func (i *Interactive) doSessionExport(dst string) {
2951 if i.cfg.CurrentSessionPath == nil {
2952 i.mu.Lock()
2953 i.statusErr = "export: no session is active (running with --no-session?)"
2954 i.mu.Unlock()
2955 i.invalidate()
2956 return
2957 }
2958 src := i.cfg.CurrentSessionPath()
2959 if src == "" {
2960 i.mu.Lock()
2961 i.statusErr = "export: no session is active (running with --no-session?)"
2962 i.mu.Unlock()
2963 i.invalidate()
2964 return
2965 }
2966 // Persist any in-memory agent messages to the session file so
2967 // the export carries the full conversation. Without this, the
2968 // default lazy-flush-at-exit strategy leaves most of a running
2969 // session unwritten and the export ends up with only the meta.
2970 if i.cfg.FlushSession != nil {
2971 i.cfg.FlushSession()
2972 }
2973 dst = unquotePath(dst)
2974 if dst == "" {
2975 dst = defaultExportDir()
2976 } else {
2977 dst = expandTilde(dst)
2978 }
2979 out, err := core.ExportSession(src, dst)
2980 if err != nil {
2981 i.mu.Lock()
2982 i.statusErr = "export: " + err.Error()
2983 i.mu.Unlock()
2984 i.invalidate()
2985 return
2986 }
2987 i.mu.Lock()
2988 i.statusOK = "exported session to " + friendlyPath(out)
2989 i.statusErr = ""
2990 i.mu.Unlock()
2991 i.invalidate()
2992}
2993
2994// doSessionImport copies the .zotsession file at src into the
2995// running cwd's sessions directory and loads it as the active
2996// session, same as `/sessions` -> pick. When src is empty we ask
2997// the user to pass a path (no usable default here).
2998func (i *Interactive) doSessionImport(src string) {
2999 src = unquotePath(src)
3000 if src == "" {
3001 i.mu.Lock()
3002 i.statusErr = "import: pass a path — e.g. /session import ~/Downloads/work.zotsession"
3003 i.mu.Unlock()
3004 i.invalidate()
3005 return
3006 }
3007 src = expandTilde(src)
3008 if _, err := os.Stat(src); err != nil {
3009 i.mu.Lock()
3010 i.statusErr = "import: " + err.Error()
3011 i.mu.Unlock()
3012 i.invalidate()
3013 return
3014 }
3015 newPath, err := core.ImportSession(src, i.cfg.ZotHome, i.cfg.CWD, i.cfg.Version)
3016 if err != nil {
3017 i.mu.Lock()
3018 i.statusErr = "import: " + err.Error()
3019 i.mu.Unlock()
3020 i.invalidate()
3021 return
3022 }
3023 if i.cfg.LoadSession == nil {
3024 i.mu.Lock()
3025 i.statusOK = "imported session at " + friendlyPath(newPath) + " (run /sessions to resume it)"
3026 i.statusErr = ""
3027 i.mu.Unlock()
3028 i.invalidate()
3029 return
3030 }
3031 if err := i.cfg.LoadSession(newPath); err != nil {
3032 i.mu.Lock()
3033 i.statusErr = "import: load failed: " + err.Error()
3034 i.mu.Unlock()
3035 i.invalidate()
3036 return
3037 }
3038 i.mu.Lock()
3039 i.statusOK = "imported and switched to session " + friendlyPath(newPath)
3040 i.statusErr = ""
3041 i.mu.Unlock()
3042 i.invalidate()
3043}
3044
3045// defaultExportDir returns ~/Downloads when it exists, or ~ as a
3046// fallback, or /tmp on exotic machines with no home dir.
3047func defaultExportDir() string {
3048 home, err := os.UserHomeDir()
3049 if err != nil || home == "" {
3050 return os.TempDir()
3051 }
3052 downloads := filepath.Join(home, "Downloads")
3053 if fi, err := os.Stat(downloads); err == nil && fi.IsDir() {
3054 return downloads
3055 }
3056 return home
3057}
3058
3059// expandTilde turns a leading ~ into the user's home directory.
3060// Returns the input unchanged when there's no tilde or no home.
3061func expandTilde(p string) string {
3062 if p == "" || p[0] != '~' {
3063 return p
3064 }
3065 home, err := os.UserHomeDir()
3066 if err != nil || home == "" {
3067 return p
3068 }
3069 if len(p) == 1 {
3070 return home
3071 }
3072 if p[1] == '/' || p[1] == filepath.Separator {
3073 return filepath.Join(home, p[2:])
3074 }
3075 return p
3076}
3077
3078// unquotePath strips a matching pair of surrounding single or
3079// double quotes. Drag-drop paste in the tui auto-quotes dropped
3080// file paths so the shell-like `/session import 'foo bar.zs'`
3081// stays well-formed; when the TUI's own slash handler consumes
3082// the arg, we want the raw path back.
3083func unquotePath(p string) string {
3084 p = strings.TrimSpace(p)
3085 if len(p) >= 2 {
3086 first := p[0]
3087 last := p[len(p)-1]
3088 if (first == '\'' && last == '\'') || (first == '"' && last == '"') {
3089 p = p[1 : len(p)-1]
3090 }
3091 }
3092 return p
3093}
3094
3095// friendlyPath collapses the user's home directory to a leading ~
3096// so status messages read cleanly. Falls back to the raw path when
3097// the home dir is unknown.
3098func friendlyPath(p string) string {
3099 home, err := os.UserHomeDir()
3100 if err != nil || home == "" {
3101 return p
3102 }
3103 if strings.HasPrefix(p, home+string(filepath.Separator)) {
3104 return "~" + p[len(home):]
3105 }
3106 return p
3107}
3108
3109// doSessionFork opens the /jump turn picker in "fork mode". The
3110// next selection branches the current session at that user turn
3111// instead of scrolling the viewport to it.
3112func (i *Interactive) doSessionFork() {
3113 if i.cfg.CurrentSessionPath == nil || i.cfg.CurrentSessionPath() == "" {
3114 i.mu.Lock()
3115 i.statusErr = "fork: no session is active (running with --no-session?)"
3116 i.mu.Unlock()
3117 i.invalidate()
3118 return
3119 }
3120 msgs := []provider.Message{}
3121 if i.agent != nil {
3122 msgs = i.agent.Messages()
3123 }
3124 if len(msgs) == 0 {
3125 i.mu.Lock()
3126 i.statusErr = "fork: transcript is empty; nothing to fork from"
3127 i.mu.Unlock()
3128 i.invalidate()
3129 return
3130 }
3131 i.pendingFork = true
3132 i.jumpDialog.Open(msgs, "")
3133 i.invalidate()
3134}
3135
3136// doSessionTree shows the branch topology picker for this cwd.
3137// Pick an entry to switch into it (same semantics as /sessions
3138// picking a past session, but with the parent/child indentation).
3139func (i *Interactive) doSessionTree() {
3140 if i.cfg.ZotHome == "" || i.cfg.CWD == "" {
3141 i.mu.Lock()
3142 i.statusErr = "tree: session storage not configured"
3143 i.mu.Unlock()
3144 i.invalidate()
3145 return
3146 }
3147 // Flush the running agent's transcript first so its message
3148 // count + latest preview are accurate in the tree.
3149 if i.cfg.FlushSession != nil {
3150 i.cfg.FlushSession()
3151 }
3152 roots := core.BuildSessionTree(i.cfg.ZotHome, i.cfg.CWD)
3153 if len(roots) == 0 {
3154 i.mu.Lock()
3155 i.statusErr = "tree: no sessions in this directory yet"
3156 i.mu.Unlock()
3157 i.invalidate()
3158 return
3159 }
3160 current := ""
3161 if i.cfg.CurrentSessionPath != nil {
3162 current = i.cfg.CurrentSessionPath()
3163 }
3164 if !i.sessionTreeDialog.Open(roots, current) {
3165 i.mu.Lock()
3166 i.statusErr = "tree: no branches to show"
3167 i.mu.Unlock()
3168 }
3169 i.invalidate()
3170}
3171
3172// applySessionTreeSelection switches the running agent to the
3173// session file at path. Thin wrapper around LoadSession that also
3174// writes a status line.
3175func (i *Interactive) applySessionTreeSelection(path string) {
3176 if i.cfg.LoadSession == nil {
3177 i.mu.Lock()
3178 i.statusErr = "tree: session swap not available in this build"
3179 i.mu.Unlock()
3180 i.invalidate()
3181 return
3182 }
3183 if err := i.cfg.LoadSession(path); err != nil {
3184 i.mu.Lock()
3185 i.statusErr = "tree: load failed: " + err.Error()
3186 i.mu.Unlock()
3187 i.invalidate()
3188 return
3189 }
3190 i.mu.Lock()
3191 i.statusOK = "switched to branch " + friendlyPath(path)
3192 i.statusErr = ""
3193 i.mu.Unlock()
3194 i.invalidate()
3195}
3196
3197// applyForkSelection branches the current session at msgIdx+1 (so
3198// the selected user message and everything before it is included
3199// in the new branch), then switches the running agent to the new
3200// file. Called from the jump-dialog handler when pendingFork=true.
3201func (i *Interactive) applyForkSelection(msgIdx int) {
3202 i.pendingFork = false
3203 if i.cfg.CurrentSessionPath == nil {
3204 i.mu.Lock()
3205 i.statusErr = "fork: no session is active"
3206 i.mu.Unlock()
3207 i.invalidate()
3208 return
3209 }
3210 src := i.cfg.CurrentSessionPath()
3211 if src == "" {
3212 i.mu.Lock()
3213 i.statusErr = "fork: no session is active"
3214 i.mu.Unlock()
3215 i.invalidate()
3216 return
3217 }
3218 if i.cfg.FlushSession != nil {
3219 i.cfg.FlushSession()
3220 }
3221 // msgIdx is 0-indexed message position; copy msgIdx+1 rows so
3222 // the selected user message is included.
3223 upTo := msgIdx + 1
3224 newPath, err := core.BranchSession(src, i.cfg.ZotHome, i.cfg.CWD, i.cfg.Version, upTo)
3225 if err != nil {
3226 i.mu.Lock()
3227 i.statusErr = "fork: " + err.Error()
3228 i.mu.Unlock()
3229 i.invalidate()
3230 return
3231 }
3232 if i.cfg.LoadSession == nil {
3233 i.mu.Lock()
3234 i.statusOK = "forked at message " + formatInt(upTo) + " (run /sessions to resume)"
3235 i.statusErr = ""
3236 i.mu.Unlock()
3237 i.invalidate()
3238 return
3239 }
3240 if err := i.cfg.LoadSession(newPath); err != nil {
3241 i.mu.Lock()
3242 i.statusErr = "fork: switch failed: " + err.Error()
3243 i.mu.Unlock()
3244 i.invalidate()
3245 return
3246 }
3247 i.mu.Lock()
3248 i.statusOK = "forked and switched to new branch at " + friendlyPath(newPath)
3249 i.statusErr = ""
3250 i.mu.Unlock()
3251 i.invalidate()
3252}
3253
3254// formatInt is a tiny strconv.Itoa shim; keeps the handler above
3255// from needing a strconv import just for one call.
3256func formatInt(n int) string {
3257 return fmt.Sprintf("%d", n)
3258}
3259
3260// assistantText returns the concatenated text of every TextBlock in
3261// m. Used by the streaming-view dedupe guard to tell when a live
3262// streamed reply has already been promoted into the transcript.
3263func assistantText(m provider.Message) string {
3264 var sb strings.Builder
3265 for _, c := range m.Content {
3266 if tb, ok := c.(provider.TextBlock); ok {
3267 if sb.Len() > 0 {
3268 sb.WriteByte('\n')
3269 }
3270 sb.WriteString(tb.Text)
3271 }
3272 }
3273 return sb.String()
3274}
3275
3276// resetStreamingStateLocked clears every piece of streaming state
3277// in one shot. Used by abort paths (turn cancel, compact finish,
3278// queue drain) so the pacer doesn't keep draining stale runes from
3279// a prior turn. Must be called with i.mu held.
3280func (i *Interactive) resetStreamingStateLocked() {
3281 i.streaming.Reset()
3282 i.streamPending = i.streamPending[:0]
3283 i.streamFlushPending = false
3284 i.streamOn = false
3285}
3286
3287// assistantMessageSideEffects runs the non-visual hooks attached to
3288// EvAssistantMessage: the host-provided OnAssistant callback and the
3289// telegram-bridge mirror. Called with i.mu held.
3290//
3291// Factored out of handleEvent because the streaming pacer may defer
3292// visual reset until after the last buffered rune has painted, but
3293// the callbacks themselves must fire on message arrival so
3294// downstream observers (session persistence, telegram, cost panels)
3295// don't wait on a UI animation to catch up.
3296func (i *Interactive) assistantMessageSideEffects(m provider.Message) {
3297 if i.cfg.OnAssistant != nil {
3298 i.cfg.OnAssistant(m)
3299 }
3300 if i.telegramBridge != nil && i.telegramBridge.Active() {
3301 var sb strings.Builder
3302 for _, c := range m.Content {
3303 if tb, ok := c.(provider.TextBlock); ok {
3304 if sb.Len() > 0 {
3305 sb.WriteString("\n")
3306 }
3307 sb.WriteString(tb.Text)
3308 }
3309 }
3310 if text := sb.String(); strings.TrimSpace(text) != "" {
3311 go i.telegramBridge.OnAssistantText(text)
3312 }
3313 }
3314}
3315
3316// paintPaceRate is how many runes the streaming pacer releases per
3317// tick. With a 16ms tick, 6 runes/tick is ~375 runes/s — fast enough
3318// that a 500-rune summary finishes in ~1.3s, slow enough to look
3319// like a human typing. Empirically matches the feel of provider
3320// paths that already drip-stream natively.
3321const paintPaceRate = 6
3322
3323// paintPaceInterval is the tick interval for the streaming pacer.
3324// 16ms lines up with the redraw throttle so we never paint faster
3325// than the terminal can keep up.
3326const paintPaceInterval = 16 * time.Millisecond
3327
3328// runStreamPacer drains buffered deltas from streamPending into
3329// streaming a small batch per tick, invalidating after each move.
3330// It stops when the context cancels (tui shutdown).
3331//
3332// Why a pacer: providers differ wildly in how they chunk their
3333// text_delta events. The API-key path on Anthropic emits ~30 drips
3334// for a 400-token summary; the OAuth path can coalesce the same
3335// summary into 3 fat chunks, visually indistinguishable from "the
3336// whole reply just appeared". The pacer normalizes that so every
3337// path looks the same on screen.
3338func (i *Interactive) runStreamPacer(ctx context.Context) {
3339 t := time.NewTicker(paintPaceInterval)
3340 defer t.Stop()
3341 for {
3342 select {
3343 case <-ctx.Done():
3344 return
3345 case <-t.C:
3346 i.mu.Lock()
3347 if len(i.streamPending) == 0 {
3348 // EvAssistantMessage already fired but the pacer
3349 // was still draining a tick ago. Everything is now
3350 // painted; clear the streaming flags so the next
3351 // redraw shows the finalised transcript message
3352 // and hides the streaming overlay.
3353 if i.streamFlushPending {
3354 i.streamFlushPending = false
3355 i.streaming.Reset()
3356 i.streamOn = false
3357 i.mu.Unlock()
3358 i.invalidate()
3359 continue
3360 }
3361 i.mu.Unlock()
3362 continue
3363 }
3364 n := paintPaceRate
3365 if n > len(i.streamPending) {
3366 n = len(i.streamPending)
3367 }
3368 i.streaming.WriteString(string(i.streamPending[:n]))
3369 i.streamPending = i.streamPending[n:]
3370 i.mu.Unlock()
3371 i.invalidate()
3372 }
3373 }
3374}