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