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