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