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