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