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