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