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