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