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 // SubmitValue() expands any [paste #N +L lines] placeholders
1185 // back into the pasted bodies; Value() is what the user
1186 // sees on screen. History stores the visible text so the
1187 // up-arrow recall shows the placeholder, not a 500-line
1188 // replay.
1189 visible := strings.TrimRight(i.ed.Value(), "\n")
1190 text := strings.TrimRight(i.ed.SubmitValue(), "\n")
1191 if text == "" {
1192 return false
1193 }
1194 i.ed.PushHistory(visible)
1195 i.ed.Clear()
1196 i.suggest.Reset()
1197
1198 if looksLikeSlashCommand(text) {
1199 head := text
1200 rest := ""
1201 if idx := strings.IndexAny(text, " \t"); idx >= 0 {
1202 head = text[:idx]
1203 rest = strings.TrimSpace(text[idx:])
1204 }
1205 if !isKnownSlashCommand(text) {
1206 // Try extensions before giving up. Extensions register
1207 // commands by bare name (no leading slash); strip it here.
1208 extName := strings.TrimPrefix(head, "/")
1209 if i.cfg.Extensions != nil && i.cfg.Extensions.HasCommand(extName) {
1210 go i.invokeExtensionCommand(ctx, extName, rest)
1211 return false
1212 }
1213 i.mu.Lock()
1214 i.statusErr = "unknown command " + head + " — type /help to see the list"
1215 i.statusOK = ""
1216 i.mu.Unlock()
1217 return false
1218 }
1219 // Slash commands run regardless of busy state. Commands that
1220 // would mutate the transcript or replace the agent (/clear,
1221 // /compact, /logout, /login, /model) cancel the active turn
1222 // first and wait for the goroutine to wind down so they don't
1223 // race with a streaming response. Safe commands (/help,
1224 // /jump, /sessions, /jail, /unjail, /exit) run immediately
1225 // without disturbing the active turn.
1226 if slashCancelsTurn(head) {
1227 i.cancelAndWaitForIdle()
1228 }
1229 return i.runSlash(ctx, text)
1230 }
1231
1232 if i.agent == nil {
1233 i.mu.Lock()
1234 i.statusErr = "not logged in. type /login first."
1235 i.mu.Unlock()
1236 return false
1237 }
1238 // Mirror the user's typed prompt into the paired Telegram
1239 // chat (when the bridge is active) so the Telegram thread
1240 // stays a complete record of the session, not just the half
1241 // that originated on the phone. On a goroutine so the
1242 // network write doesn't delay the local turn.
1243 if i.telegramBridge != nil && i.telegramBridge.Active() {
1244 go i.telegramBridge.OnUserTyped(text)
1245 }
1246 // If a turn is already in flight, queue this prompt instead of
1247 // starting a second one. The drain loop at the end of startTurn
1248 // will pick it up when the current turn finishes.
1249 i.mu.Lock()
1250 if i.busy {
1251 i.queued = append(i.queued, text)
1252 i.mu.Unlock()
1253 i.invalidate()
1254 return false
1255 }
1256 i.mu.Unlock()
1257 i.startTurn(ctx, text)
1258 }
1259 return false
1260}
1261
1262// invokeExtensionCommand fires an extension-registered slash command
1263// in a background goroutine, awaits the response, and applies the
1264// requested action (prompt / insert / display / noop). Errors and
1265// timeouts surface as a status_err line.
1266func (i *Interactive) invokeExtensionCommand(ctx context.Context, name, args string) {
1267 resp, err := i.cfg.Extensions.Invoke(ctx, name, args, 30*time.Second)
1268 if err != nil {
1269 i.mu.Lock()
1270 i.statusErr = "extension /" + name + ": " + err.Error()
1271 i.statusOK = ""
1272 i.mu.Unlock()
1273 i.invalidate()
1274 return
1275 }
1276 if resp.Error != "" {
1277 i.mu.Lock()
1278 i.statusErr = "extension /" + name + ": " + resp.Error
1279 i.statusOK = ""
1280 i.mu.Unlock()
1281 i.invalidate()
1282 return
1283 }
1284 switch resp.Action {
1285 case "prompt":
1286 if strings.TrimSpace(resp.Prompt) == "" {
1287 return
1288 }
1289 i.startTurn(i.runCtx, resp.Prompt)
1290 case "insert":
1291 i.ed.Insert(resp.Insert)
1292 i.invalidate()
1293 case "display":
1294 i.appendExtensionNote(name, resp.Display, "info")
1295 case "noop", "":
1296 // nothing
1297 default:
1298 i.mu.Lock()
1299 i.statusErr = "extension /" + name + ": unknown action " + resp.Action
1300 i.mu.Unlock()
1301 i.invalidate()
1302 }
1303}
1304
1305// appendExtensionNote renders an extension-originated note in the
1306// chat. Levels: "info" (muted), "warn" (warning), "error" (error),
1307// "success" (tool/ok green).
1308func (i *Interactive) appendExtensionNote(extName, msg, level string) {
1309 if msg == "" {
1310 return
1311 }
1312 i.mu.Lock()
1313 defer i.mu.Unlock()
1314 color := i.cfg.Theme.Muted
1315 switch level {
1316 case "warn":
1317 color = i.cfg.Theme.Warning
1318 case "error":
1319 color = i.cfg.Theme.Error
1320 case "success":
1321 color = i.cfg.Theme.Tool
1322 }
1323 prefix := i.cfg.Theme.FG256(i.cfg.Theme.Accent, "["+extName+"] ")
1324 for _, line := range strings.Split(msg, "\n") {
1325 i.statusOK = "" // clear any stale ok
1326 i.statusErr = ""
1327 i.extNotes = append(i.extNotes, prefix+i.cfg.Theme.FG256(color, line))
1328 }
1329}
1330
1331// HostHooks implementation for the extension manager. The manager
1332// holds an interface, not a concrete *Interactive, so these methods
1333// are the only thing the manager sees.
1334
1335// Notify is the manager's NotifyFromExt entry point.
1336func (i *Interactive) Notify(extName, level, message string) {
1337 i.appendExtensionNote(extName, message, level)
1338 i.invalidate()
1339}
1340
1341// Submit feeds text through the agent loop as if the user had typed it.
1342func (i *Interactive) Submit(text string) {
1343 i.startTurn(i.runCtx, text)
1344}
1345
1346// SubmitOrQueue runs text immediately if the agent is idle, or
1347// appends it to the pending queue if a turn is already in flight.
1348// Used by the telegram bridge (and by the editor submit path) so
1349// both input sources share the same "queue behind an active turn"
1350// semantics. Images are ignored for now — only the text prompt is
1351// forwarded — because the queued-prompt path is text-only; a
1352// follow-up can expand the queue entry to carry images.
1353func (i *Interactive) SubmitOrQueue(text string, images []provider.ImageBlock) {
1354 _ = images // reserved for future queued-with-images support
1355 i.mu.Lock()
1356 if i.agent == nil {
1357 i.statusErr = "not logged in. type /login first."
1358 i.mu.Unlock()
1359 i.invalidate()
1360 return
1361 }
1362 if i.busy {
1363 i.queued = append(i.queued, text)
1364 i.mu.Unlock()
1365 i.invalidate()
1366 return
1367 }
1368 i.mu.Unlock()
1369 i.startTurn(i.runCtx, text)
1370}
1371
1372// CancelTurn aborts the active turn if one is running. Used by the
1373// telegram bridge when the paired user sends /stop.
1374func (i *Interactive) CancelTurn() {
1375 i.mu.Lock()
1376 cancel := i.cancelTurn
1377 i.mu.Unlock()
1378 if cancel != nil {
1379 cancel()
1380 }
1381}
1382
1383// Insert places text at the cursor in the editor.
1384func (i *Interactive) Insert(text string) {
1385 i.ed.Insert(text)
1386 i.invalidate()
1387}
1388
1389// Display appends a styled note from extName to the chat without a
1390// model call.
1391func (i *Interactive) Display(extName, text string) {
1392 i.appendExtensionNote(extName, text, "info")
1393 i.invalidate()
1394}
1395
1396func (i *Interactive) runSlash(ctx context.Context, cmd string) (done bool) {
1397 parts := strings.Fields(cmd)
1398 switch parts[0] {
1399 case "/exit":
1400 return true
1401 case "/clear":
1402 if i.agent != nil {
1403 i.agent.SetMessages(nil)
1404 }
1405 i.mu.Lock()
1406 i.toolCalls = map[string]*tui.ToolCallView{}
1407 i.toolOrder = nil
1408 i.statusErr = ""
1409 i.statusOK = ""
1410 i.helpBlock = nil
1411 i.parkedTurn = 0
1412 i.parkedTotal = 0
1413 i.scrollOffset = 0
1414 i.extNotes = nil
1415 i.view.InvalidateRenderCache()
1416 i.mu.Unlock()
1417 case "/help":
1418 i.mu.Lock()
1419 i.helpBlock = renderHelpBlock(i.cfg.Theme, i.lastCols())
1420 i.statusErr = ""
1421 i.statusOK = ""
1422 // Pin the viewport to the newest content so the help block,
1423 // which we just appended to the end of the transcript, is
1424 // what the user actually sees.
1425 i.scrollOffset = 0
1426 i.mu.Unlock()
1427 case "/login":
1428 i.dialog.Open()
1429 case "/logout":
1430 if len(parts) >= 2 {
1431 // Explicit target: /logout anthropic | openai | all
1432 i.doLogout(parts[1])
1433 break
1434 }
1435 // No arg: open the picker over whichever providers are
1436 // currently logged in. If nothing's logged in, bail with a
1437 // status line.
1438 i.openLogoutDialog()
1439 case "/model":
1440 if len(parts) >= 2 {
1441 i.applyModelSelection("", parts[1])
1442 } else {
1443 i.modelDialog.Open(i.cfg.Model)
1444 }
1445 case "/sessions":
1446 i.sessionDialog.Open(i.cfg.ZotHome, i.cfg.CWD)
1447 case "/jump":
1448 i.openJumpDialog(parts[1:])
1449 case "/btw":
1450 i.openBtwDialog(parts[1:])
1451 case "/skills":
1452 i.openSkillsDialog()
1453 case "/compact":
1454 i.runCompact(ctx, false)
1455 case "/jail":
1456 if i.cfg.Sandbox == nil {
1457 i.mu.Lock()
1458 i.statusErr = "sandbox not available in this build"
1459 i.mu.Unlock()
1460 break
1461 }
1462 i.cfg.Sandbox.Lock()
1463 i.mu.Lock()
1464 i.statusOK = "jailed to " + i.cfg.CWD + " (tools cannot touch paths outside this directory)"
1465 i.statusErr = ""
1466 i.mu.Unlock()
1467 case "/unjail":
1468 if i.cfg.Sandbox == nil {
1469 i.mu.Lock()
1470 i.statusErr = "sandbox not available in this build"
1471 i.mu.Unlock()
1472 break
1473 }
1474 i.cfg.Sandbox.Unlock()
1475 i.mu.Lock()
1476 i.statusOK = "unjailed"
1477 i.statusErr = ""
1478 i.mu.Unlock()
1479 case "/reload-ext":
1480 i.runReloadExt(ctx)
1481 case "/yolo":
1482 i.runYoloOn()
1483 case "/telegram", "/tg":
1484 if len(parts) >= 2 {
1485 i.doTelegram(parts[1])
1486 break
1487 }
1488 i.openTelegramDialog()
1489 case "/session":
1490 if len(parts) >= 2 {
1491 action := parts[1]
1492 arg := ""
1493 if len(parts) >= 3 {
1494 arg = strings.Join(parts[2:], " ")
1495 }
1496 i.doSessionOp(action, arg)
1497 break
1498 }
1499 i.openSessionOpsDialog()
1500 default:
1501 // Last-resort fallback: try the extension manager. Built-in
1502 // cases above always win; this branch only fires for slash
1503 // commands the extension manager registered. Same routing as
1504 // the editor's submit-handler dispatch path so the autocomplete
1505 // "enter on highlighted suggestion" flow also works.
1506 extName := strings.TrimPrefix(parts[0], "/")
1507 if i.cfg.Extensions != nil && i.cfg.Extensions.HasCommand(extName) {
1508 rest := ""
1509 if len(parts) > 1 {
1510 rest = strings.Join(parts[1:], " ")
1511 }
1512 go i.invokeExtensionCommand(ctx, extName, rest)
1513 return false
1514 }
1515 i.mu.Lock()
1516 i.statusErr = "unknown command: " + parts[0]
1517 i.mu.Unlock()
1518 }
1519 return false
1520}
1521
1522// openLogoutDialog shows the provider picker for `/logout` with no
1523// argument. Only providers the user is currently logged into are
1524// listed, plus an "all" entry when more than one is present. If
1525// nothing's logged in, writes a status line instead of opening an
1526// empty dialog.
1527func (i *Interactive) openLogoutDialog() {
1528 if i.cfg.AuthManager == nil {
1529 i.mu.Lock()
1530 i.statusErr = "no auth manager configured"
1531 i.mu.Unlock()
1532 i.invalidate()
1533 return
1534 }
1535 store := i.cfg.AuthManager.Store()
1536 if store == nil {
1537 i.mu.Lock()
1538 i.statusErr = "auth store is not available"
1539 i.mu.Unlock()
1540 i.invalidate()
1541 return
1542 }
1543 creds, err := store.Load()
1544 if err != nil {
1545 i.mu.Lock()
1546 i.statusErr = "read auth store: " + err.Error()
1547 i.mu.Unlock()
1548 i.invalidate()
1549 return
1550 }
1551
1552 var items []logoutItem
1553 for _, p := range []string{"anthropic", "openai"} {
1554 if creds.Has(p) {
1555 items = append(items, logoutItem{
1556 label: p,
1557 target: p,
1558 method: creds.Method(p),
1559 })
1560 }
1561 }
1562 if len(items) == 0 {
1563 i.mu.Lock()
1564 i.statusOK = "no credentials stored; already logged out"
1565 i.statusErr = ""
1566 i.mu.Unlock()
1567 i.invalidate()
1568 return
1569 }
1570 if len(items) > 1 {
1571 items = append(items, logoutItem{label: "all", target: "all"})
1572 }
1573
1574 i.logoutDialog.Open(items)
1575 i.invalidate()
1576}
1577
1578// doLogout clears credentials for the given provider (or all providers)
1579// from auth.json. If the active agent was using those credentials, it
1580// is torn down so the user is forced through /login before their next
1581// prompt.
1582//
1583// target: "anthropic" | "openai" | "all"
1584func (i *Interactive) doLogout(target string) {
1585 if i.cfg.AuthManager == nil {
1586 i.mu.Lock()
1587 i.statusErr = "no auth manager configured"
1588 i.mu.Unlock()
1589 return
1590 }
1591 store := i.cfg.AuthManager.Store()
1592 if store == nil {
1593 i.mu.Lock()
1594 i.statusErr = "auth store is not available"
1595 i.mu.Unlock()
1596 return
1597 }
1598
1599 var providers []string
1600 switch target {
1601 case "", "all":
1602 providers = []string{"anthropic", "openai"}
1603 case "anthropic", "openai":
1604 providers = []string{target}
1605 default:
1606 i.mu.Lock()
1607 i.statusErr = "unknown provider: " + target + " (use anthropic, openai, or all)"
1608 i.mu.Unlock()
1609 return
1610 }
1611
1612 var errs []string
1613 clearedCurrent := false
1614 for _, p := range providers {
1615 if err := store.Clear(p); err != nil {
1616 errs = append(errs, p+": "+err.Error())
1617 continue
1618 }
1619 if p == i.cfg.Provider {
1620 clearedCurrent = true
1621 }
1622 }
1623
1624 i.mu.Lock()
1625 defer i.mu.Unlock()
1626 if len(errs) > 0 {
1627 i.statusErr = "logout errors: " + strings.Join(errs, "; ")
1628 return
1629 }
1630 i.statusErr = ""
1631 if clearedCurrent {
1632 // The running agent was using a credential we just wiped. Drop
1633 // it so prompts can't go out with the stale client, and hint at
1634 // /login.
1635 i.agent = nil
1636 i.statusOK = "logged out of " + strings.Join(providers, ", ") + ". type /login to sign back in."
1637 } else {
1638 i.statusOK = "logged out of " + strings.Join(providers, ", ")
1639 }
1640}
1641
1642func (i *Interactive) startAPIKeyFlow(provider string) {
1643 url, err := i.cfg.AuthManager.StartAPIKey(provider)
1644 if err != nil {
1645 i.dialog.ShowResult(false, err.Error())
1646 return
1647 }
1648 i.dialog.ShowWaiting(url)
1649}
1650
1651func (i *Interactive) startOAuthFlow(provider string) {
1652 url, err := i.cfg.AuthManager.StartOAuth(provider)
1653 if err != nil {
1654 i.dialog.ShowResult(false, err.Error())
1655 return
1656 }
1657 i.dialog.ShowWaiting(url)
1658}
1659
1660// applyModelSelection switches the active model (and provider, if the
1661// new model belongs to a different one). It rebuilds the underlying
1662// client when needed so the provider wire-protocol matches.
1663// cancelAndWaitForIdle cancels the active turn (if any) and blocks
1664// briefly until the turn goroutine has updated i.busy = false. Used
1665// before destructive slash commands so transcript-mutating work
1666// (/clear, /compact, /logout, /login completion, cross-provider
1667// /model swap) doesn't race with the still-running stream.
1668//
1669// The wait is bounded; if the turn doesn't release within the timeout
1670// we proceed anyway. Worst case is a brief overlap that the agent's
1671// own mutex protects against.
1672func (i *Interactive) cancelAndWaitForIdle() {
1673 i.mu.Lock()
1674 busy := i.busy
1675 cancel := i.cancelTurn
1676 i.mu.Unlock()
1677 if !busy {
1678 return
1679 }
1680 if cancel != nil {
1681 cancel()
1682 }
1683 deadline := time.Now().Add(2 * time.Second)
1684 for time.Now().Before(deadline) {
1685 i.mu.Lock()
1686 done := !i.busy
1687 i.mu.Unlock()
1688 if done {
1689 return
1690 }
1691 time.Sleep(10 * time.Millisecond)
1692 }
1693}
1694
1695// openBtwDialog opens the side-chat overlay with a frozen snapshot
1696// of the current main session. The optional argument is auto-
1697// submitted as the first question, so '/btw does X work?' fires the
1698// model call immediately instead of just opening an empty dialog.
1699func (i *Interactive) openBtwDialog(args []string) {
1700 if i.agent == nil {
1701 i.mu.Lock()
1702 i.statusErr = "not logged in. type /login first."
1703 i.mu.Unlock()
1704 return
1705 }
1706 seed := strings.TrimSpace(strings.Join(args, " "))
1707 i.btwDialog.Open(i.cfg.Theme, i.agent, i.agent.System, i.cfg.Model, seed)
1708 i.invalidate()
1709}
1710
1711// openSkillsDialog opens the skill inspector. The picker reflects
1712// whatever SkillSnapshot returns at call time, so edits to a
1713// SKILL.md made during a session show up on the next /skills.
1714func (i *Interactive) openSkillsDialog() {
1715 var list []*skills.Skill
1716 if i.cfg.SkillSnapshot != nil {
1717 list = i.cfg.SkillSnapshot()
1718 }
1719 i.skillsDialog.Open(list)
1720 i.invalidate()
1721}
1722
1723// openJumpDialog builds a /jump picker from the current transcript.
1724// If the user typed "/jump foo" with a filter and it matches exactly
1725// one turn, jump there directly without showing the dialog.
1726func (i *Interactive) openJumpDialog(args []string) {
1727 if i.view == nil || len(i.view.Messages) == 0 {
1728 i.mu.Lock()
1729 i.statusErr = "nothing to jump to \u2014 the session is empty"
1730 i.mu.Unlock()
1731 return
1732 }
1733 filter := strings.TrimSpace(strings.Join(args, " "))
1734 i.jumpDialog.Open(i.view.Messages, filter)
1735 // Shortcut: with a filter argument that matches exactly one turn,
1736 // jump immediately and skip the picker.
1737 if filter != "" {
1738 if tgts := i.jumpDialog.Targets(); len(tgts) == 1 {
1739 t := tgts[0]
1740 i.jumpDialog.Close()
1741 i.applyJumpSelection(t.MessageIdx, t.TurnNo)
1742 }
1743 }
1744}
1745
1746// applyJumpSelection scrolls the chat viewport so the user message at
1747// msgIdx is visible at (or near) the top of the chat area. Uses the
1748// anchor slice returned by view.BuildWithAnchors so the mapping from
1749// message index to row is exact, regardless of variable-height tool
1750// blocks above the target.
1751func (i *Interactive) applyJumpSelection(msgIdx, turnNo int) {
1752 cols := i.lastCols()
1753 chat, anchors := i.view.BuildWithAnchors(cols)
1754 var row int
1755 found := false
1756 for _, a := range anchors {
1757 if a.MessageIdx == msgIdx {
1758 row = a.Row
1759 found = true
1760 break
1761 }
1762 }
1763 if !found {
1764 i.mu.Lock()
1765 i.statusErr = "could not resolve jump target"
1766 i.mu.Unlock()
1767 return
1768 }
1769
1770 chatLen := len(chat)
1771 page := i.chatPage()
1772 if page < 1 {
1773 page = 1
1774 }
1775 // scrollOffset is measured from the bottom of the chat slice, so
1776 // to place `row` at the top of the viewport we want:
1777 // chatLen - scrollOffset - page == row
1778 // Solve for scrollOffset and clamp to [0, chatLen-page].
1779 offset := chatLen - (row + page)
1780 if offset < 0 {
1781 offset = 0
1782 }
1783 maxOffset := chatLen - page
1784 if maxOffset < 0 {
1785 maxOffset = 0
1786 }
1787 if offset > maxOffset {
1788 offset = maxOffset
1789 }
1790
1791 i.mu.Lock()
1792 i.scrollOffset = offset
1793 i.parkedTurn = turnNo
1794 i.parkedTotal = totalTurnsLocked(i.view.Messages)
1795 i.statusOK = fmt.Sprintf("jumped to turn %d", turnNo)
1796 i.statusErr = ""
1797 i.mu.Unlock()
1798}
1799
1800// totalTurnsLocked counts user messages in the transcript. Caller is
1801// assumed to hold i.mu (the name is a mild reminder; this function
1802// itself doesn't touch shared state beyond the slice it's handed).
1803func totalTurnsLocked(msgs []provider.Message) int {
1804 n := 0
1805 for _, m := range msgs {
1806 if m.Role == provider.RoleUser {
1807 n++
1808 }
1809 }
1810 return n
1811}
1812
1813// applySessionSelection loads the given session via the cli-provided
1814// callback and parks the viewport on the last turn so the user lands
1815// looking at where the conversation left off (their last prompt at the
1816// top of the chat, the assistant's last reply right below). Older
1817// history is one scroll up; pgdn or end snaps to the current tail.
1818//
1819// Without this, scrollOffset stayed at 0 (pinned to the live tail),
1820// which on a long resumed session showed only the last few rows of
1821// the final assistant message — the user read that as "only one liner
1822// happened, the resume didn't work".
1823func (i *Interactive) applySessionSelection(path string) {
1824 if i.cfg.LoadSession == nil {
1825 i.mu.Lock()
1826 i.statusErr = "session loading is not wired in this build"
1827 i.mu.Unlock()
1828 return
1829 }
1830 if err := i.cfg.LoadSession(path); err != nil {
1831 i.mu.Lock()
1832 i.statusErr = err.Error()
1833 i.mu.Unlock()
1834 return
1835 }
1836
1837 i.mu.Lock()
1838 i.statusOK = "resumed session: " + path
1839 i.statusErr = ""
1840 i.parkedTurn = 0
1841 i.parkedTotal = 0
1842 i.view.InvalidateRenderCache()
1843 // Pull the freshly-loaded transcript into the view so the anchor
1844 // math below sees the post-resume messages, not the empty pre-load
1845 // state. redraw() does the same on its next pass; we just front-run
1846 // it here to compute the scroll target.
1847 if i.agent != nil {
1848 i.view.Messages = i.agent.Messages()
1849 }
1850 msgs := i.view.Messages
1851 i.mu.Unlock()
1852
1853 i.scrollToLastTurn(msgs)
1854}
1855
1856// scrollToLastTurn parks the viewport at the most recent user turn,
1857// or at the top if the transcript has no user messages. Used after
1858// resume so the user lands looking at where they left off.
1859func (i *Interactive) scrollToLastTurn(msgs []provider.Message) {
1860 if len(msgs) == 0 {
1861 i.mu.Lock()
1862 i.scrollOffset = 0
1863 i.mu.Unlock()
1864 return
1865 }
1866 // Find the last user message index.
1867 lastUser := -1
1868 turnNo, totalTurns := 0, 0
1869 for idx, m := range msgs {
1870 if m.Role == provider.RoleUser {
1871 totalTurns++
1872 lastUser = idx
1873 }
1874 }
1875 if lastUser < 0 {
1876 i.mu.Lock()
1877 i.scrollOffset = 0
1878 i.mu.Unlock()
1879 return
1880 }
1881 turnNo = totalTurns
1882
1883 cols := i.lastCols()
1884 chat, anchors := i.view.BuildWithAnchors(cols)
1885 var row int
1886 found := false
1887 for _, a := range anchors {
1888 if a.MessageIdx == lastUser {
1889 row = a.Row
1890 found = true
1891 break
1892 }
1893 }
1894 if !found {
1895 i.mu.Lock()
1896 i.scrollOffset = 0
1897 i.mu.Unlock()
1898 return
1899 }
1900
1901 chatLen := len(chat)
1902 page := i.chatPage()
1903 if page < 1 {
1904 page = 1
1905 }
1906 offset := chatLen - (row + page)
1907 if offset < 0 {
1908 offset = 0
1909 }
1910 maxOffset := chatLen - page
1911 if maxOffset < 0 {
1912 maxOffset = 0
1913 }
1914 if offset > maxOffset {
1915 offset = maxOffset
1916 }
1917
1918 i.mu.Lock()
1919 i.scrollOffset = offset
1920 // Mark the parked-turn footer so the user sees "viewing turn N of
1921 // M · pgdn to catch up" — same affordance as /jump. Tells them at
1922 // a glance that they're looking at history, not the live tail.
1923 if offset > 0 {
1924 i.parkedTurn = turnNo
1925 i.parkedTotal = totalTurns
1926 }
1927 i.mu.Unlock()
1928 i.invalidate()
1929}
1930
1931func (i *Interactive) applyModelSelection(prov, model string) {
1932 if model == "" {
1933 return
1934 }
1935 m, err := provider.FindModel(prov, model)
1936 if err != nil {
1937 i.mu.Lock()
1938 i.statusErr = err.Error()
1939 i.mu.Unlock()
1940 return
1941 }
1942 // Same provider? Just swap the model on the existing agent.
1943 if i.agent != nil && m.Provider == i.cfg.Provider {
1944 i.mu.Lock()
1945 i.cfg.Model = m.ID
1946 i.agent.Model = m.ID
1947 i.statusOK = "model: " + m.ID
1948 i.statusErr = ""
1949 i.mu.Unlock()
1950 if i.cfg.PersistModel != nil {
1951 i.cfg.PersistModel(i.cfg.Provider, m.ID)
1952 }
1953 return
1954 }
1955 // Different provider: rebuild agent (needs credentials for target provider).
1956 if i.cfg.BuildAgentFor == nil {
1957 i.mu.Lock()
1958 i.statusErr = "cannot switch provider: no builder configured"
1959 i.mu.Unlock()
1960 return
1961 }
1962 // Snapshot the current transcript and cumulative usage BEFORE we
1963 // build the replacement agent so we can hand them off. Without
1964 // this the user perceives the entire session as wiped on a
1965 // cross-provider /model swap.
1966 var carryMsgs []provider.Message
1967 var carryCost provider.Usage
1968 if i.agent != nil {
1969 carryMsgs = i.agent.Messages()
1970 carryCost = i.agent.Cost()
1971 }
1972
1973 ag, p, md, err := i.cfg.BuildAgentFor(m.Provider, m.ID)
1974 if err != nil {
1975 i.mu.Lock()
1976 i.statusErr = err.Error()
1977 i.mu.Unlock()
1978 return
1979 }
1980
1981 // Replay the transcript and seed the cost on the freshly-built
1982 // agent. Messages travel cleanly between providers because they
1983 // use the same provider.Message shape; tool-call ids are local
1984 // to a turn so cross-provider continuation never confuses the
1985 // new model (it just sees the assistant's reply, no orphan
1986 // tool_use blocks because /model swaps are gated to idle state).
1987 if len(carryMsgs) > 0 {
1988 ag.SetMessages(carryMsgs)
1989 }
1990 ag.SeedCost(carryCost)
1991
1992 i.mu.Lock()
1993 i.agent = ag
1994 i.cfg.Provider = p
1995 i.cfg.Model = md
1996 i.statusOK = "switched to " + p + " / " + md
1997 i.statusErr = ""
1998 // Render cache keys are width+content based, so the new agent's
1999 // identical messages will reuse the existing entries. Nothing
2000 // to invalidate.
2001 i.mu.Unlock()
2002 if i.cfg.PersistModel != nil {
2003 i.cfg.PersistModel(p, md)
2004 }
2005}
2006
2007func (i *Interactive) handleAuthEvent(ev auth.Event) {
2008 switch ev.Kind {
2009 case "started":
2010 i.dialog.ShowWaiting(ev.URL)
2011 case "browser_open":
2012 // no-op
2013 case "error":
2014 i.dialog.ShowResult(false, ev.Message)
2015 case "success":
2016 // Rebuild the agent with the fresh credential.
2017 ag, prov, model, err := i.cfg.BuildAgent()
2018 if err != nil {
2019 i.dialog.ShowResult(false, err.Error())
2020 return
2021 }
2022 i.mu.Lock()
2023 i.agent = ag
2024 i.cfg.Provider = prov
2025 i.cfg.Model = model
2026 i.statusErr = ""
2027 i.statusOK = "logged in to " + ev.Provider + " via " + ev.Method
2028 i.mu.Unlock()
2029 i.dialog.ShowResult(true, "")
2030 }
2031}
2032
2033// runCompact invokes core.Agent.Compact and reflects the progress in
2034// the tui. It runs in a goroutine so the ui stays responsive; esc/ctrl+c
2035// cancel via the same cancelTurn channel used for normal turns.
2036//
2037// When auto is true the spinner message is pinned to "condensing
2038// history" and the status bar surfaces "(auto)" next to the context
2039// percentage so it's obvious the system triggered this, not the user.
2040func (i *Interactive) runCompact(parent context.Context, auto bool) {
2041 if i.agent == nil {
2042 i.mu.Lock()
2043 i.statusErr = "not logged in. type /login first."
2044 i.mu.Unlock()
2045 return
2046 }
2047 ctx, cancel := context.WithCancel(parent)
2048 i.mu.Lock()
2049 i.busy = true
2050 if auto {
2051 i.spin.StartFixed("condensing history")
2052 i.autoCompacting = true
2053 i.statusOK = "condensing history… (esc to cancel)"
2054 } else {
2055 i.spin.Start()
2056 i.statusOK = "compacting..."
2057 }
2058 i.cancelTurn = cancel
2059 i.statusErr = ""
2060 i.streaming.Reset()
2061 i.streamOn = true
2062 i.scrollOffset = 0
2063 i.helpBlock = nil
2064 i.mu.Unlock()
2065 i.invalidate()
2066
2067 go func() {
2068 sink := func(delta string) {
2069 i.mu.Lock()
2070 i.streaming.WriteString(delta)
2071 i.mu.Unlock()
2072 i.invalidate()
2073 }
2074 summary, err := i.agent.Compact(ctx, 4, sink)
2075 i.mu.Lock()
2076 i.busy = false
2077 i.resetStreamingStateLocked()
2078 i.cancelTurn = nil
2079 i.autoCompacting = false
2080 switch {
2081 case err != nil && ctx.Err() != nil:
2082 i.statusErr = ""
2083 if auto {
2084 i.statusOK = "auto-condense cancelled"
2085 } else {
2086 i.statusOK = "compaction cancelled"
2087 }
2088 case err != nil:
2089 i.statusErr = "compaction failed: " + err.Error()
2090 i.statusOK = ""
2091 default:
2092 i.statusErr = ""
2093 i.statusOK = fmt.Sprintf("compacted transcript (%d chars of summary)", len(summary))
2094 i.lastCtxInput = 0 // reset; next turn will get a fresh measurement
2095 i.toolCalls = map[string]*tui.ToolCallView{}
2096 i.toolOrder = nil
2097 // Transcript was rewritten in place — purge the per-message
2098 // render cache so stale entries keyed on the old messages
2099 // don't linger.
2100 i.view.InvalidateRenderCache()
2101 }
2102 i.mu.Unlock()
2103 i.invalidate()
2104 }()
2105}
2106
2107func (i *Interactive) startTurn(parent context.Context, prompt string) {
2108 if i.agent == nil {
2109 return
2110 }
2111 ctx, cancel := context.WithCancel(parent)
2112 i.mu.Lock()
2113 i.busy = true
2114 i.spin.Start()
2115 i.cancelTurn = cancel
2116 i.statusErr = ""
2117 i.statusOK = ""
2118 i.streaming.Reset()
2119 i.streamOn = true
2120 i.toolCalls = map[string]*tui.ToolCallView{}
2121 i.toolOrder = nil
2122 i.scrollOffset = 0 // jump back to the bottom on new turn
2123 i.parkedTurn = 0 // starting a turn clears the /jump parked state
2124 i.parkedTotal = 0
2125 i.helpBlock = nil // hide the help block once the user asks something
2126 i.mu.Unlock()
2127 i.invalidate()
2128
2129 sink := func(ev core.AgentEvent) {
2130 i.handleEvent(ev)
2131 i.invalidate()
2132 }
2133
2134 go func() {
2135 err := i.agent.Prompt(ctx, prompt, nil, sink)
2136 i.mu.Lock()
2137 i.busy = false
2138 // Don't touch streamPending / streamFlushPending here — the
2139 // pacer may still be draining the final deltas and needs to
2140 // paint them even though Prompt has returned. It will reset
2141 // streamOn on its own once the buffer empties.
2142 if len(i.streamPending) == 0 {
2143 i.streamOn = false
2144 }
2145 i.cancelTurn = nil
2146 if err != nil && ctx.Err() == nil {
2147 i.statusErr = err.Error()
2148 }
2149 // Persist the assistant's reply (and every tool row before
2150 // it) to the session file while the turn memory is hot.
2151 // Without this, WriteNewTranscript only fires at zot exit,
2152 // meaning a crash or ungraceful kill drops the whole
2153 // conversation. FlushSession is idempotent (it advances the
2154 // baseline so subsequent flushes only write new rows).
2155 flush := i.cfg.FlushSession
2156 i.mu.Unlock()
2157 if flush != nil {
2158 flush()
2159 }
2160 i.mu.Lock()
2161 // Pop the next queued message, if any, and relaunch.
2162 var next string
2163 var hasNext bool
2164 if len(i.queued) > 0 && ctx.Err() == nil && err == nil {
2165 next, i.queued = i.queued[0], i.queued[1:]
2166 hasNext = true
2167 }
2168 // If the turn was cancelled or errored, drop the queue so the
2169 // user isn't bombarded with stale messages after an interrupt.
2170 if ctx.Err() != nil || err != nil {
2171 i.queued = nil
2172 }
2173 // Decide whether the next thing to do is an auto-compaction.
2174 // Only fires when the turn completed cleanly AND the queue is
2175 // empty (otherwise a queued message would race the condense).
2176 shouldAutoCompact := !hasNext && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
2177 i.mu.Unlock()
2178 i.invalidate()
2179 parent := i.runCtx
2180 if parent == nil {
2181 parent = context.Background()
2182 }
2183 switch {
2184 case hasNext:
2185 i.startTurn(parent, next)
2186 case shouldAutoCompact:
2187 i.runCompact(parent, true)
2188 }
2189 }()
2190}
2191
2192// autoCompactThreshold is the context-window fraction at which the
2193// agent will auto-compact after a turn ends. 0.85 leaves enough
2194// headroom for one more user prompt + response before we bump the
2195// hard limit.
2196const autoCompactThreshold = 0.85
2197
2198// shouldAutoCompactLocked reports whether the last turn pushed context
2199// usage past the auto-compact threshold. Must be called with i.mu
2200// held; it reads lastCtxInput and the current model's context window.
2201func (i *Interactive) shouldAutoCompactLocked() bool {
2202 if i.agent == nil {
2203 return false
2204 }
2205 if i.autoCompacting {
2206 return false
2207 }
2208 m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
2209 if err != nil || m.ContextWindow <= 0 {
2210 return false
2211 }
2212 if i.lastCtxInput <= 0 {
2213 return false
2214 }
2215 return float64(i.lastCtxInput)/float64(m.ContextWindow) >= autoCompactThreshold
2216}
2217
2218func (i *Interactive) handleEvent(ev core.AgentEvent) {
2219 i.mu.Lock()
2220 defer i.mu.Unlock()
2221 switch e := ev.(type) {
2222 case core.EvAssistantStart:
2223 // Fires at the top of every oneTurn, including follow-up
2224 // turns after tool use. Without this, the streaming buffer
2225 // is still marked off from the previous assistant message
2226 // and the final summary text pops in all at once instead
2227 // of typewriter-streaming delta by delta.
2228 i.streaming.Reset()
2229 i.streamPending = i.streamPending[:0]
2230 i.streamFlushPending = false
2231 i.streamOn = true
2232 // Clear the live tool-call overlay. Any tools from the
2233 // previous round are now fully folded into the transcript
2234 // (assistant tool_use block + tool role message with the
2235 // result), so keeping them in the overlay would duplicate
2236 // them in the view — once inside the finalised transcript
2237 // and once below the streaming block, with the streaming
2238 // summary sandwiched in between. The next EvToolUseStart
2239 // will populate fresh entries for this turn's tools.
2240 i.toolCalls = map[string]*tui.ToolCallView{}
2241 i.toolOrder = nil
2242 case core.EvTextDelta:
2243 // Buffer into streamPending; the paintPace ticker drains
2244 // it into i.streaming a few runes at a time for a smooth
2245 // typewriter effect independent of upstream chunk size.
2246 i.streamPending = append(i.streamPending, []rune(e.Delta)...)
2247 i.streamOn = true
2248 case core.EvAssistantMessage:
2249 // OnAssistant + telegram mirroring always fire on message
2250 // arrival — they read the FINAL message content, which is
2251 // complete regardless of what's still in the pacer.
2252 i.assistantMessageSideEffects(e.Message)
2253 // If the pacer still has characters to drain, keep streamOn
2254 // true and mark flush pending; the paintPace ticker will
2255 // drain the remainder and reset streaming state when done.
2256 // Otherwise (rare: full-replay sessions, abort paths) clear
2257 // synchronously so a later render doesn't show stale text.
2258 if len(i.streamPending) > 0 {
2259 i.streamFlushPending = true
2260 return
2261 }
2262 i.resetStreamingStateLocked()
2263 case core.EvToolUseStart:
2264 // Live streaming: pre-create the view so the user sees the
2265 // tool call being composed in real time. Any subsequent
2266 // EvToolCall for the same ID updates the same struct (the
2267 // final parsed args + name are already known here).
2268 if _, exists := i.toolCalls[e.ID]; !exists {
2269 i.toolCalls[e.ID] = &tui.ToolCallView{
2270 ID: e.ID,
2271 Name: e.Name,
2272 Streaming: true,
2273 }
2274 i.toolOrder = append(i.toolOrder, e.ID)
2275 }
2276 case core.EvToolUseArgs:
2277 if tc, ok := i.toolCalls[e.ID]; ok {
2278 tc.RawJSONBuf += e.Delta
2279 // Refresh the live path as soon as it parses; used in
2280 // the header (▸ write /Users/pat/Desktop/demo.ts)
2281 // while the content is still streaming.
2282 if p, pok, _ := tui.ExtractPartialStringField(tc.RawJSONBuf, "path"); pok {
2283 tc.LivePath = p
2284 } else if p, pok, _ := tui.ExtractPartialStringField(tc.RawJSONBuf, "file_path"); pok {
2285 tc.LivePath = p
2286 }
2287 }
2288 case core.EvToolUseEnd:
2289 if tc, ok := i.toolCalls[e.ID]; ok {
2290 tc.Streaming = false
2291 }
2292 case core.EvToolCall:
2293 // If we already pre-created the view during streaming, just
2294 // refresh the final Args summary. Otherwise create a new one
2295 // (non-streaming providers or legacy paths).
2296 if tc, ok := i.toolCalls[e.ID]; ok {
2297 tc.Args = tui.ShortArgs(e.Name, e.Args)
2298 tc.Streaming = false
2299 } else {
2300 i.toolCalls[e.ID] = &tui.ToolCallView{
2301 ID: e.ID,
2302 Name: e.Name,
2303 Args: tui.ShortArgs(e.Name, e.Args),
2304 }
2305 i.toolOrder = append(i.toolOrder, e.ID)
2306 }
2307 case core.EvToolResult:
2308 if tc, ok := i.toolCalls[e.ID]; ok {
2309 tc.Done = true
2310 tc.Error = e.Result.IsError
2311 var text strings.Builder
2312 for _, c := range e.Result.Content {
2313 if tb, ok := c.(provider.TextBlock); ok {
2314 if text.Len() > 0 {
2315 text.WriteString("\n")
2316 }
2317 text.WriteString(tb.Text)
2318 }
2319 }
2320 tc.Result = text.String()
2321 }
2322 if i.cfg.OnToolResult != nil {
2323 i.cfg.OnToolResult(e.ID, e.Result)
2324 }
2325 case core.EvUsage:
2326 i.cumUsage = e.Cumulative
2327 if e.Usage.InputTokens > 0 {
2328 i.lastCtxInput = e.Usage.InputTokens + e.Usage.CacheReadTokens + e.Usage.CacheWriteTokens
2329 }
2330 case core.EvTurnEnd:
2331 if e.Stop == provider.StopAborted {
2332 // Aborted turn: discard the partial streaming text (it
2333 // is not persisted in the transcript) and clear any
2334 // transient error. Also drop anything still buffered in
2335 // the pacer so nothing keeps drawing after the cancel.
2336 i.resetStreamingStateLocked()
2337 i.statusErr = ""
2338 i.statusOK = "cancelled"
2339 return
2340 }
2341 if e.Err != nil && !strings.Contains(e.Err.Error(), "context canceled") {
2342 i.statusErr = e.Err.Error()
2343 }
2344 }
2345}
2346
2347// Agent returns the current agent, if any. Used by cli.go to flush the
2348// final transcript to the session file.
2349func (i *Interactive) Agent() *core.Agent {
2350 i.mu.Lock()
2351 defer i.mu.Unlock()
2352 return i.agent
2353}
2354
2355// silence unused import in some build configs
2356var _ = fmt.Sprintf
2357
2358// runReloadExt triggers a live reload of every extension (discovered
2359// + explicit). Runs on a goroutine so the TUI stays responsive; the
2360// Manager.Reload takes a couple of hundred ms to shut down subprocs
2361// and respawn them. Shows a status line throughout.
2362func (i *Interactive) runReloadExt(ctx context.Context) {
2363 if i.cfg.Extensions == nil {
2364 i.mu.Lock()
2365 i.statusErr = "no extension manager in this build"
2366 i.mu.Unlock()
2367 i.invalidate()
2368 return
2369 }
2370 i.mu.Lock()
2371 i.statusOK = "reloading extensions…"
2372 i.statusErr = ""
2373 i.mu.Unlock()
2374 i.invalidate()
2375
2376 go func() {
2377 stats := i.cfg.Extensions.Reload(ctx, 2*time.Second)
2378 msg := fmt.Sprintf("reloaded: %d stopped, %d loaded (%d ready)", stats.Stopped, stats.Loaded, stats.Ready)
2379 if len(stats.Errors) > 0 {
2380 msg += fmt.Sprintf(", %d error(s)", len(stats.Errors))
2381 }
2382 i.mu.Lock()
2383 i.statusOK = msg
2384 i.statusErr = ""
2385 i.mu.Unlock()
2386 i.invalidate()
2387 }()
2388}
2389
2390// Confirm implements core.Confirmer. The agent goroutine calls
2391// this synchronously before every tool invocation when --no-yolo is
2392// active. We push the request onto the confirmDialog queue, trigger
2393// a redraw, and block the caller until the user answers.
2394//
2395// If the session is cancelled or the TUI exits mid-prompt, any
2396// pending request is refused via CancelAll so the agent doesn't
2397// deadlock.
2398func (i *Interactive) Confirm(toolName string, preview string) core.ConfirmDecision {
2399 resp := make(chan core.ConfirmDecision, 1)
2400 i.confirmDialog.Enqueue(&confirmRequest{
2401 toolName: toolName,
2402 preview: preview,
2403 resp: resp,
2404 })
2405 i.invalidate()
2406 return <-resp
2407}
2408
2409// runYoloOn disables --no-yolo for the rest of the session. Tool
2410// calls run without prompting after this; there's intentionally no
2411// way to re-enable gating mid-session, if the user wants that back
2412// they can exit and restart with --no-yolo.
2413func (i *Interactive) runYoloOn() {
2414 if i.cfg.ConfirmGate == nil {
2415 i.mu.Lock()
2416 i.statusOK = "yolo mode is already on (no --no-yolo in this session)"
2417 i.statusErr = ""
2418 i.mu.Unlock()
2419 i.invalidate()
2420 return
2421 }
2422 i.cfg.ConfirmGate.AllowAll()
2423 // Also auto-allow any currently pending confirmation so the
2424 // agent doesn't deadlock if /yolo is typed while a prompt is
2425 // open.
2426 i.confirmDialog.AllowAllPending()
2427 i.mu.Lock()
2428 i.statusOK = "yolo engaged: no more tool-call confirmations this session"
2429 i.statusErr = ""
2430 i.mu.Unlock()
2431 i.invalidate()
2432}
2433
2434// openTelegramDialog shows the picker for `/telegram` with no arg.
2435// Items depend on current state: disconnect + status when running,
2436// connect + status when stopped.
2437func (i *Interactive) openTelegramDialog() {
2438 items := i.telegramMenuItems()
2439 if len(items) == 0 {
2440 i.mu.Lock()
2441 i.statusErr = "telegram not configured. run `zot telegram-bot setup` first."
2442 i.mu.Unlock()
2443 i.invalidate()
2444 return
2445 }
2446 i.telegramDialog.Open(items)
2447 i.invalidate()
2448}
2449
2450// telegramMenuItems builds the dialog entries for the current
2451// bridge state. Returns empty when no bot.json exists so the
2452// caller can show a helpful status line instead of an empty menu.
2453func (i *Interactive) telegramMenuItems() []telegramItem {
2454 cfg, err := telegram.LoadConfig(i.cfg.ZotHome)
2455 if err != nil || cfg.BotToken == "" {
2456 return nil
2457 }
2458 var items []telegramItem
2459 if i.telegramBridge != nil && i.telegramBridge.Active() {
2460 items = append(items, telegramItem{label: "disconnect", action: "disconnect", hint: "stop mirroring"})
2461 st := i.telegramBridge.State()
2462 hint := "active"
2463 if st.Username != "" {
2464 hint += " as @" + st.Username
2465 }
2466 items = append(items, telegramItem{label: "status", action: "status", hint: hint})
2467 } else {
2468 label := "connect"
2469 hint := "start mirroring dms into this session"
2470 if cfg.AllowedUserID == 0 {
2471 hint = "awaiting pairing (send /start to the bot once connected)"
2472 }
2473 items = append(items, telegramItem{label: label, action: "connect", hint: hint})
2474 items = append(items, telegramItem{label: "status", action: "status", hint: "disconnected"})
2475 }
2476 return items
2477}
2478
2479// doTelegram dispatches one of the three explicit actions. Called
2480// from /telegram <action> or after the picker selects a row.
2481func (i *Interactive) doTelegram(action string) {
2482 switch action {
2483 case "connect":
2484 i.telegramConnect()
2485 case "disconnect":
2486 i.telegramDisconnect()
2487 case "status":
2488 i.telegramStatus()
2489 default:
2490 i.mu.Lock()
2491 i.statusErr = "unknown telegram action: " + action + " (use connect, disconnect, or status)"
2492 i.mu.Unlock()
2493 i.invalidate()
2494 }
2495}
2496
2497// telegramConnect starts the bridge. Refuses if it's already
2498// running or if the on-disk bot.json is missing a token.
2499func (i *Interactive) telegramConnect() {
2500 if i.telegramBridge != nil && i.telegramBridge.Active() {
2501 i.mu.Lock()
2502 i.statusOK = "telegram already connected"
2503 i.statusErr = ""
2504 i.mu.Unlock()
2505 i.invalidate()
2506 return
2507 }
2508 cfg, err := telegram.LoadConfig(i.cfg.ZotHome)
2509 if err != nil {
2510 i.mu.Lock()
2511 i.statusErr = "telegram: " + err.Error()
2512 i.mu.Unlock()
2513 i.invalidate()
2514 return
2515 }
2516 if cfg.BotToken == "" {
2517 i.mu.Lock()
2518 i.statusErr = "telegram: no bot token configured. run `zot telegram-bot setup` first."
2519 i.mu.Unlock()
2520 i.invalidate()
2521 return
2522 }
2523 // Refuse to start when a background daemon is already polling
2524 // the same bot. Two concurrent long-poll consumers race each
2525 // update and one always loses, so DMs get half-delivered. The
2526 // user can `zot telegram-bot stop` first, then /telegram connect.
2527 if pid, alive, _ := telegram.IsRunning(i.cfg.ZotHome); alive && pid > 0 {
2528 i.mu.Lock()
2529 i.statusErr = fmt.Sprintf("telegram: bot daemon already running (pid %d). stop it with `zot telegram-bot stop` first.", pid)
2530 i.mu.Unlock()
2531 i.invalidate()
2532 return
2533 }
2534 i.telegramBridge = &telegram.Bridge{
2535 Client: telegram.NewClient(cfg.BotToken),
2536 Config: cfg,
2537 Save: func(next telegram.Config) error {
2538 return telegram.SaveConfig(i.cfg.ZotHome, next)
2539 },
2540 Host: &telegramHost{iv: i},
2541 }
2542 if err := i.telegramBridge.Start(i.runCtx); err != nil {
2543 i.telegramBridge = nil
2544 i.mu.Lock()
2545 i.statusErr = "telegram connect failed: " + err.Error()
2546 i.mu.Unlock()
2547 i.invalidate()
2548 return
2549 }
2550 state := i.telegramBridge.State()
2551 label := "telegram connected"
2552 if state.Username != "" {
2553 label += " as @" + state.Username
2554 }
2555 if state.PairedID == 0 {
2556 label += " — send /start to the bot from your phone to claim it"
2557 }
2558 i.mu.Lock()
2559 i.statusOK = label
2560 i.statusErr = ""
2561 i.mu.Unlock()
2562 i.invalidate()
2563}
2564
2565// telegramDisconnect stops the bridge. No-op when already stopped.
2566func (i *Interactive) telegramDisconnect() {
2567 if i.telegramBridge == nil || !i.telegramBridge.Active() {
2568 i.mu.Lock()
2569 i.statusOK = "telegram already disconnected"
2570 i.statusErr = ""
2571 i.mu.Unlock()
2572 i.invalidate()
2573 return
2574 }
2575 i.telegramBridge.Stop()
2576 i.mu.Lock()
2577 i.statusOK = "telegram disconnected"
2578 i.statusErr = ""
2579 i.mu.Unlock()
2580 i.invalidate()
2581}
2582
2583// telegramStatus writes a one-liner describing the bridge state.
2584// Reports on both the in-tui bridge and the background daemon so
2585// the user isn't confused when the daemon owns the poll loop.
2586func (i *Interactive) telegramStatus() {
2587 var msg string
2588 if i.telegramBridge != nil && i.telegramBridge.Active() {
2589 s := i.telegramBridge.State()
2590 msg = "telegram: connected (tui bridge)"
2591 if s.Username != "" {
2592 msg += " as @" + s.Username
2593 }
2594 if s.PairedID != 0 {
2595 msg += fmt.Sprintf(" · paired with user %d", s.PairedID)
2596 } else {
2597 msg += " · awaiting pairing"
2598 }
2599 } else if pid, alive, _ := telegram.IsRunning(i.cfg.ZotHome); alive && pid > 0 {
2600 msg = fmt.Sprintf("telegram: background daemon running (pid %d) · /telegram connect won't work until you stop it", pid)
2601 } else {
2602 cfg, _ := telegram.LoadConfig(i.cfg.ZotHome)
2603 if cfg.BotToken == "" {
2604 msg = "telegram: not configured. run `zot telegram-bot setup` first."
2605 } else {
2606 msg = "telegram: disconnected"
2607 if cfg.BotUsername != "" {
2608 msg += " (@" + cfg.BotUsername + " ready to connect)"
2609 }
2610 }
2611 }
2612 i.mu.Lock()
2613 i.statusOK = msg
2614 i.statusErr = ""
2615 i.mu.Unlock()
2616 i.invalidate()
2617}
2618
2619// telegramHost adapts *Interactive to telegram.Host so the bridge
2620// can call back into the TUI without importing modes directly.
2621type telegramHost struct{ iv *Interactive }
2622
2623func (h *telegramHost) SubmitOrQueue(prompt string, images []provider.ImageBlock) {
2624 h.iv.SubmitOrQueue(prompt, images)
2625}
2626
2627func (h *telegramHost) CancelTurn() { h.iv.CancelTurn() }
2628
2629func (h *telegramHost) Notify(level, message string) {
2630 h.iv.mu.Lock()
2631 switch level {
2632 case "error", "warn":
2633 h.iv.statusErr = message
2634 h.iv.statusOK = ""
2635 default:
2636 h.iv.statusOK = message
2637 h.iv.statusErr = ""
2638 }
2639 h.iv.mu.Unlock()
2640 h.iv.invalidate()
2641}
2642
2643// openSessionOpsDialog shows the picker for `/session` with no arg.
2644// Always offers export, import, fork, tree; the handlers bail with
2645// a clear status message when the precondition isn't met (empty
2646// transcript on fork; no parent/siblings on tree).
2647func (i *Interactive) openSessionOpsDialog() {
2648 items := []sessionOpsItem{
2649 {label: "export", action: "export", hint: "write the current session to a .zotsession file"},
2650 {label: "import", action: "import", hint: "load a .zotsession file into this directory"},
2651 {label: "fork", action: "fork", hint: "branch from a past user message into a new session"},
2652 {label: "tree", action: "tree", hint: "switch between branches in this directory"},
2653 }
2654 i.sessionOpsDialog.Open(items)
2655 i.invalidate()
2656}
2657
2658// doSessionOp dispatches export, import, fork, or tree. arg is the
2659// optional positional argument from e.g. /session export <path>
2660// or /session import <path>; fork and tree ignore it.
2661func (i *Interactive) doSessionOp(action, arg string) {
2662 switch action {
2663 case "export":
2664 i.doSessionExport(arg)
2665 case "import":
2666 i.doSessionImport(arg)
2667 case "fork":
2668 i.doSessionFork()
2669 case "tree":
2670 i.doSessionTree()
2671 default:
2672 i.mu.Lock()
2673 i.statusErr = "unknown /session action: " + action + " (use export, import, fork, or tree)"
2674 i.mu.Unlock()
2675 i.invalidate()
2676 }
2677}
2678
2679// doSessionExport writes the live session file to destination path
2680// dst. When dst is empty we default to ~/Downloads (falling back to
2681// the user's home directory if it doesn't exist). The helper
2682// expands a leading `~` and creates any missing parent directories.
2683func (i *Interactive) doSessionExport(dst string) {
2684 if i.cfg.CurrentSessionPath == nil {
2685 i.mu.Lock()
2686 i.statusErr = "export: no session is active (running with --no-session?)"
2687 i.mu.Unlock()
2688 i.invalidate()
2689 return
2690 }
2691 src := i.cfg.CurrentSessionPath()
2692 if src == "" {
2693 i.mu.Lock()
2694 i.statusErr = "export: no session is active (running with --no-session?)"
2695 i.mu.Unlock()
2696 i.invalidate()
2697 return
2698 }
2699 // Persist any in-memory agent messages to the session file so
2700 // the export carries the full conversation. Without this, the
2701 // default lazy-flush-at-exit strategy leaves most of a running
2702 // session unwritten and the export ends up with only the meta.
2703 if i.cfg.FlushSession != nil {
2704 i.cfg.FlushSession()
2705 }
2706 dst = unquotePath(dst)
2707 if dst == "" {
2708 dst = defaultExportDir()
2709 } else {
2710 dst = expandTilde(dst)
2711 }
2712 out, err := core.ExportSession(src, dst)
2713 if err != nil {
2714 i.mu.Lock()
2715 i.statusErr = "export: " + err.Error()
2716 i.mu.Unlock()
2717 i.invalidate()
2718 return
2719 }
2720 i.mu.Lock()
2721 i.statusOK = "exported session to " + friendlyPath(out)
2722 i.statusErr = ""
2723 i.mu.Unlock()
2724 i.invalidate()
2725}
2726
2727// doSessionImport copies the .zotsession file at src into the
2728// running cwd's sessions directory and loads it as the active
2729// session, same as `/sessions` -> pick. When src is empty we ask
2730// the user to pass a path (no usable default here).
2731func (i *Interactive) doSessionImport(src string) {
2732 src = unquotePath(src)
2733 if src == "" {
2734 i.mu.Lock()
2735 i.statusErr = "import: pass a path — e.g. /session import ~/Downloads/work.zotsession"
2736 i.mu.Unlock()
2737 i.invalidate()
2738 return
2739 }
2740 src = expandTilde(src)
2741 if _, err := os.Stat(src); err != nil {
2742 i.mu.Lock()
2743 i.statusErr = "import: " + err.Error()
2744 i.mu.Unlock()
2745 i.invalidate()
2746 return
2747 }
2748 newPath, err := core.ImportSession(src, i.cfg.ZotHome, i.cfg.CWD, i.cfg.Version)
2749 if err != nil {
2750 i.mu.Lock()
2751 i.statusErr = "import: " + err.Error()
2752 i.mu.Unlock()
2753 i.invalidate()
2754 return
2755 }
2756 if i.cfg.LoadSession == nil {
2757 i.mu.Lock()
2758 i.statusOK = "imported session at " + friendlyPath(newPath) + " (run /sessions to resume it)"
2759 i.statusErr = ""
2760 i.mu.Unlock()
2761 i.invalidate()
2762 return
2763 }
2764 if err := i.cfg.LoadSession(newPath); err != nil {
2765 i.mu.Lock()
2766 i.statusErr = "import: load failed: " + err.Error()
2767 i.mu.Unlock()
2768 i.invalidate()
2769 return
2770 }
2771 i.mu.Lock()
2772 i.statusOK = "imported and switched to session " + friendlyPath(newPath)
2773 i.statusErr = ""
2774 i.mu.Unlock()
2775 i.invalidate()
2776}
2777
2778// defaultExportDir returns ~/Downloads when it exists, or ~ as a
2779// fallback, or /tmp on exotic machines with no home dir.
2780func defaultExportDir() string {
2781 home, err := os.UserHomeDir()
2782 if err != nil || home == "" {
2783 return os.TempDir()
2784 }
2785 downloads := filepath.Join(home, "Downloads")
2786 if fi, err := os.Stat(downloads); err == nil && fi.IsDir() {
2787 return downloads
2788 }
2789 return home
2790}
2791
2792// expandTilde turns a leading ~ into the user's home directory.
2793// Returns the input unchanged when there's no tilde or no home.
2794func expandTilde(p string) string {
2795 if p == "" || p[0] != '~' {
2796 return p
2797 }
2798 home, err := os.UserHomeDir()
2799 if err != nil || home == "" {
2800 return p
2801 }
2802 if len(p) == 1 {
2803 return home
2804 }
2805 if p[1] == '/' || p[1] == filepath.Separator {
2806 return filepath.Join(home, p[2:])
2807 }
2808 return p
2809}
2810
2811// unquotePath strips a matching pair of surrounding single or
2812// double quotes. Drag-drop paste in the tui auto-quotes dropped
2813// file paths so the shell-like `/session import 'foo bar.zs'`
2814// stays well-formed; when the TUI's own slash handler consumes
2815// the arg, we want the raw path back.
2816func unquotePath(p string) string {
2817 p = strings.TrimSpace(p)
2818 if len(p) >= 2 {
2819 first := p[0]
2820 last := p[len(p)-1]
2821 if (first == '\'' && last == '\'') || (first == '"' && last == '"') {
2822 p = p[1 : len(p)-1]
2823 }
2824 }
2825 return p
2826}
2827
2828// friendlyPath collapses the user's home directory to a leading ~
2829// so status messages read cleanly. Falls back to the raw path when
2830// the home dir is unknown.
2831func friendlyPath(p string) string {
2832 home, err := os.UserHomeDir()
2833 if err != nil || home == "" {
2834 return p
2835 }
2836 if strings.HasPrefix(p, home+string(filepath.Separator)) {
2837 return "~" + p[len(home):]
2838 }
2839 return p
2840}
2841
2842// doSessionFork opens the /jump turn picker in "fork mode". The
2843// next selection branches the current session at that user turn
2844// instead of scrolling the viewport to it.
2845func (i *Interactive) doSessionFork() {
2846 if i.cfg.CurrentSessionPath == nil || i.cfg.CurrentSessionPath() == "" {
2847 i.mu.Lock()
2848 i.statusErr = "fork: no session is active (running with --no-session?)"
2849 i.mu.Unlock()
2850 i.invalidate()
2851 return
2852 }
2853 msgs := []provider.Message{}
2854 if i.agent != nil {
2855 msgs = i.agent.Messages()
2856 }
2857 if len(msgs) == 0 {
2858 i.mu.Lock()
2859 i.statusErr = "fork: transcript is empty; nothing to fork from"
2860 i.mu.Unlock()
2861 i.invalidate()
2862 return
2863 }
2864 i.pendingFork = true
2865 i.jumpDialog.Open(msgs, "")
2866 i.invalidate()
2867}
2868
2869// doSessionTree shows the branch topology picker for this cwd.
2870// Pick an entry to switch into it (same semantics as /sessions
2871// picking a past session, but with the parent/child indentation).
2872func (i *Interactive) doSessionTree() {
2873 if i.cfg.ZotHome == "" || i.cfg.CWD == "" {
2874 i.mu.Lock()
2875 i.statusErr = "tree: session storage not configured"
2876 i.mu.Unlock()
2877 i.invalidate()
2878 return
2879 }
2880 // Flush the running agent's transcript first so its message
2881 // count + latest preview are accurate in the tree.
2882 if i.cfg.FlushSession != nil {
2883 i.cfg.FlushSession()
2884 }
2885 roots := core.BuildSessionTree(i.cfg.ZotHome, i.cfg.CWD)
2886 if len(roots) == 0 {
2887 i.mu.Lock()
2888 i.statusErr = "tree: no sessions in this directory yet"
2889 i.mu.Unlock()
2890 i.invalidate()
2891 return
2892 }
2893 current := ""
2894 if i.cfg.CurrentSessionPath != nil {
2895 current = i.cfg.CurrentSessionPath()
2896 }
2897 if !i.sessionTreeDialog.Open(roots, current) {
2898 i.mu.Lock()
2899 i.statusErr = "tree: no branches to show"
2900 i.mu.Unlock()
2901 }
2902 i.invalidate()
2903}
2904
2905// applySessionTreeSelection switches the running agent to the
2906// session file at path. Thin wrapper around LoadSession that also
2907// writes a status line.
2908func (i *Interactive) applySessionTreeSelection(path string) {
2909 if i.cfg.LoadSession == nil {
2910 i.mu.Lock()
2911 i.statusErr = "tree: session swap not available in this build"
2912 i.mu.Unlock()
2913 i.invalidate()
2914 return
2915 }
2916 if err := i.cfg.LoadSession(path); err != nil {
2917 i.mu.Lock()
2918 i.statusErr = "tree: load failed: " + err.Error()
2919 i.mu.Unlock()
2920 i.invalidate()
2921 return
2922 }
2923 i.mu.Lock()
2924 i.statusOK = "switched to branch " + friendlyPath(path)
2925 i.statusErr = ""
2926 i.mu.Unlock()
2927 i.invalidate()
2928}
2929
2930// applyForkSelection branches the current session at msgIdx+1 (so
2931// the selected user message and everything before it is included
2932// in the new branch), then switches the running agent to the new
2933// file. Called from the jump-dialog handler when pendingFork=true.
2934func (i *Interactive) applyForkSelection(msgIdx int) {
2935 i.pendingFork = false
2936 if i.cfg.CurrentSessionPath == nil {
2937 i.mu.Lock()
2938 i.statusErr = "fork: no session is active"
2939 i.mu.Unlock()
2940 i.invalidate()
2941 return
2942 }
2943 src := i.cfg.CurrentSessionPath()
2944 if src == "" {
2945 i.mu.Lock()
2946 i.statusErr = "fork: no session is active"
2947 i.mu.Unlock()
2948 i.invalidate()
2949 return
2950 }
2951 if i.cfg.FlushSession != nil {
2952 i.cfg.FlushSession()
2953 }
2954 // msgIdx is 0-indexed message position; copy msgIdx+1 rows so
2955 // the selected user message is included.
2956 upTo := msgIdx + 1
2957 newPath, err := core.BranchSession(src, i.cfg.ZotHome, i.cfg.CWD, i.cfg.Version, upTo)
2958 if err != nil {
2959 i.mu.Lock()
2960 i.statusErr = "fork: " + err.Error()
2961 i.mu.Unlock()
2962 i.invalidate()
2963 return
2964 }
2965 if i.cfg.LoadSession == nil {
2966 i.mu.Lock()
2967 i.statusOK = "forked at message " + formatInt(upTo) + " (run /sessions to resume)"
2968 i.statusErr = ""
2969 i.mu.Unlock()
2970 i.invalidate()
2971 return
2972 }
2973 if err := i.cfg.LoadSession(newPath); err != nil {
2974 i.mu.Lock()
2975 i.statusErr = "fork: switch failed: " + err.Error()
2976 i.mu.Unlock()
2977 i.invalidate()
2978 return
2979 }
2980 i.mu.Lock()
2981 i.statusOK = "forked and switched to new branch at " + friendlyPath(newPath)
2982 i.statusErr = ""
2983 i.mu.Unlock()
2984 i.invalidate()
2985}
2986
2987// formatInt is a tiny strconv.Itoa shim; keeps the handler above
2988// from needing a strconv import just for one call.
2989func formatInt(n int) string {
2990 return fmt.Sprintf("%d", n)
2991}
2992
2993// assistantText returns the concatenated text of every TextBlock in
2994// m. Used by the streaming-view dedupe guard to tell when a live
2995// streamed reply has already been promoted into the transcript.
2996func assistantText(m provider.Message) string {
2997 var sb strings.Builder
2998 for _, c := range m.Content {
2999 if tb, ok := c.(provider.TextBlock); ok {
3000 if sb.Len() > 0 {
3001 sb.WriteByte('\n')
3002 }
3003 sb.WriteString(tb.Text)
3004 }
3005 }
3006 return sb.String()
3007}
3008
3009// resetStreamingStateLocked clears every piece of streaming state
3010// in one shot. Used by abort paths (turn cancel, compact finish,
3011// queue drain) so the pacer doesn't keep draining stale runes from
3012// a prior turn. Must be called with i.mu held.
3013func (i *Interactive) resetStreamingStateLocked() {
3014 i.streaming.Reset()
3015 i.streamPending = i.streamPending[:0]
3016 i.streamFlushPending = false
3017 i.streamOn = false
3018}
3019
3020// assistantMessageSideEffects runs the non-visual hooks attached to
3021// EvAssistantMessage: the host-provided OnAssistant callback and the
3022// telegram-bridge mirror. Called with i.mu held.
3023//
3024// Factored out of handleEvent because the streaming pacer may defer
3025// visual reset until after the last buffered rune has painted, but
3026// the callbacks themselves must fire on message arrival so
3027// downstream observers (session persistence, telegram, cost panels)
3028// don't wait on a UI animation to catch up.
3029func (i *Interactive) assistantMessageSideEffects(m provider.Message) {
3030 if i.cfg.OnAssistant != nil {
3031 i.cfg.OnAssistant(m)
3032 }
3033 if i.telegramBridge != nil && i.telegramBridge.Active() {
3034 var sb strings.Builder
3035 for _, c := range m.Content {
3036 if tb, ok := c.(provider.TextBlock); ok {
3037 if sb.Len() > 0 {
3038 sb.WriteString("\n")
3039 }
3040 sb.WriteString(tb.Text)
3041 }
3042 }
3043 if text := sb.String(); strings.TrimSpace(text) != "" {
3044 go i.telegramBridge.OnAssistantText(text)
3045 }
3046 }
3047}
3048
3049// paintPaceRate is how many runes the streaming pacer releases per
3050// tick. With a 16ms tick, 6 runes/tick is ~375 runes/s — fast enough
3051// that a 500-rune summary finishes in ~1.3s, slow enough to look
3052// like a human typing. Empirically matches the feel of provider
3053// paths that already drip-stream natively.
3054const paintPaceRate = 6
3055
3056// paintPaceInterval is the tick interval for the streaming pacer.
3057// 16ms lines up with the redraw throttle so we never paint faster
3058// than the terminal can keep up.
3059const paintPaceInterval = 16 * time.Millisecond
3060
3061// runStreamPacer drains buffered deltas from streamPending into
3062// streaming a small batch per tick, invalidating after each move.
3063// It stops when the context cancels (tui shutdown).
3064//
3065// Why a pacer: providers differ wildly in how they chunk their
3066// text_delta events. The API-key path on Anthropic emits ~30 drips
3067// for a 400-token summary; the OAuth path can coalesce the same
3068// summary into 3 fat chunks, visually indistinguishable from "the
3069// whole reply just appeared". The pacer normalizes that so every
3070// path looks the same on screen.
3071func (i *Interactive) runStreamPacer(ctx context.Context) {
3072 t := time.NewTicker(paintPaceInterval)
3073 defer t.Stop()
3074 for {
3075 select {
3076 case <-ctx.Done():
3077 return
3078 case <-t.C:
3079 i.mu.Lock()
3080 if len(i.streamPending) == 0 {
3081 // EvAssistantMessage already fired but the pacer
3082 // was still draining a tick ago. Everything is now
3083 // painted; clear the streaming flags so the next
3084 // redraw shows the finalised transcript message
3085 // and hides the streaming overlay.
3086 if i.streamFlushPending {
3087 i.streamFlushPending = false
3088 i.streaming.Reset()
3089 i.streamOn = false
3090 i.mu.Unlock()
3091 i.invalidate()
3092 continue
3093 }
3094 i.mu.Unlock()
3095 continue
3096 }
3097 n := paintPaceRate
3098 if n > len(i.streamPending) {
3099 n = len(i.streamPending)
3100 }
3101 i.streaming.WriteString(string(i.streamPending[:n]))
3102 i.streamPending = i.streamPending[n:]
3103 i.mu.Unlock()
3104 i.invalidate()
3105 }
3106 }
3107}