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