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