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