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