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