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