v0.1.11 353da72

interactive.go RawHistoryFolder

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.
1658func (i *Interactive) CancelTurn() {
1659	i.mu.Lock()
1660	cancel := i.cancelTurn
1661	i.mu.Unlock()
1662	if cancel != nil {
1663		cancel()
1664	}
1665}
1666
1667// Insert places text at the cursor in the editor.
1668func (i *Interactive) Insert(text string) {
1669	i.ed.Insert(text)
1670	i.invalidate()
1671}
1672
1673// Display appends a styled note from extName to the chat without a
1674// model call.
1675func (i *Interactive) Display(extName, text string) {
1676	i.appendExtensionNote(extName, text, "info")
1677	i.invalidate()
1678}
1679
1680func (i *Interactive) OpenPanel(extName string, spec extproto.PanelSpec) {
1681	i.mu.Lock()
1682	defer i.mu.Unlock()
1683	i.extPanel.Open(extName, spec.ID, spec.Title, spec.Lines, spec.Footer)
1684	if i.cfg.Extensions != nil {
1685		cols, rows := i.cfg.Terminal.Size()
1686		_ = cols
1687		_ = rows
1688	}
1689	i.invalidate()
1690}
1691
1692func (i *Interactive) UpdatePanel(extName, panelID, title string, lines []string, footer string) {
1693	i.mu.Lock()
1694	defer i.mu.Unlock()
1695	if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
1696		i.extPanel.Update(title, lines, footer)
1697		i.invalidate()
1698	}
1699}
1700
1701func (i *Interactive) ClosePanel(extName, panelID string) {
1702	i.mu.Lock()
1703	defer i.mu.Unlock()
1704	if i.extPanel.Active() && i.extPanel.ext == extName && i.extPanel.id == panelID {
1705		i.extPanel.Close()
1706		i.invalidate()
1707	}
1708}
1709
1710func (i *Interactive) runSlash(ctx context.Context, cmd string) (done bool) {
1711	parts := strings.Fields(cmd)
1712	switch parts[0] {
1713	case "/exit":
1714		return true
1715	case "/clear":
1716		if i.agent != nil {
1717			i.agent.SetMessages(nil)
1718		}
1719		i.mu.Lock()
1720		i.toolCalls = map[string]*tui.ToolCallView{}
1721		i.toolOrder = nil
1722		i.statusErr = ""
1723		i.statusOK = ""
1724		i.helpBlock = nil
1725		i.parkedTurn = 0
1726		i.parkedTotal = 0
1727		i.scrollOffset = 0
1728		i.extNotes = nil
1729		i.view.InvalidateRenderCache()
1730		i.mu.Unlock()
1731	case "/help":
1732		i.mu.Lock()
1733		i.helpBlock = renderHelpBlock(i.cfg.Theme, i.lastCols())
1734		i.statusErr = ""
1735		i.statusOK = ""
1736		// Pin the viewport to the newest content so the help block,
1737		// which we just appended to the end of the transcript, is
1738		// what the user actually sees.
1739		i.scrollOffset = 0
1740		i.mu.Unlock()
1741	case "/login":
1742		i.dialog.Open(i.cfg.ZotHome)
1743	case "/logout":
1744		if len(parts) >= 2 {
1745			// Explicit target: /logout anthropic | openai | all
1746			i.doLogout(parts[1])
1747			break
1748		}
1749		// No arg: open the picker over whichever providers are
1750		// currently logged in. If nothing's logged in, bail with a
1751		// status line.
1752		i.openLogoutDialog()
1753	case "/model":
1754		if len(parts) >= 2 {
1755			i.applyModelSelection("", parts[1])
1756		} else {
1757			i.modelDialog.Open(i.cfg.Model)
1758		}
1759	case "/sessions":
1760		i.sessionDialog.Open(i.cfg.ZotHome, i.cfg.CWD)
1761	case "/jump":
1762		i.openJumpDialog(parts[1:])
1763	case "/btw":
1764		i.openBtwDialog(parts[1:])
1765	case "/skills":
1766		i.openSkillsDialog()
1767	case "/compact":
1768		i.runCompact(ctx, false)
1769	case "/study":
1770		// Canned prompt that tells the agent to read every file
1771		// in the current directory so its later turns have the
1772		// whole project in context. Dispatched through the normal
1773		// queue-or-start path so it behaves identically to
1774		// typing the prompt by hand.
1775		const studyPrompt = "Read and understand everything in the current directory."
1776		i.mu.Lock()
1777		if i.busy {
1778			i.queued = append(i.queued, studyPrompt)
1779			i.mu.Unlock()
1780			i.invalidate()
1781			break
1782		}
1783		i.mu.Unlock()
1784		i.startTurn(ctx, studyPrompt)
1785	case "/jail":
1786		if i.cfg.Sandbox == nil {
1787			i.mu.Lock()
1788			i.statusErr = "sandbox not available in this build"
1789			i.mu.Unlock()
1790			break
1791		}
1792		i.cfg.Sandbox.Lock()
1793		i.mu.Lock()
1794		i.statusOK = "jailed to " + i.cfg.CWD + " (tools cannot touch paths outside this directory)"
1795		i.statusErr = ""
1796		i.mu.Unlock()
1797	case "/unjail":
1798		if i.cfg.Sandbox == nil {
1799			i.mu.Lock()
1800			i.statusErr = "sandbox not available in this build"
1801			i.mu.Unlock()
1802			break
1803		}
1804		i.cfg.Sandbox.Unlock()
1805		i.mu.Lock()
1806		i.statusOK = "unjailed"
1807		i.statusErr = ""
1808		i.mu.Unlock()
1809	case "/reload-ext":
1810		i.runReloadExt(ctx)
1811	case "/yolo":
1812		i.runYoloOn()
1813	case "/telegram", "/tg":
1814		if len(parts) >= 2 {
1815			i.doTelegram(parts[1])
1816			break
1817		}
1818		i.openTelegramDialog()
1819	case "/session":
1820		if len(parts) >= 2 {
1821			action := parts[1]
1822			arg := ""
1823			if len(parts) >= 3 {
1824				arg = strings.Join(parts[2:], " ")
1825			}
1826			i.doSessionOp(action, arg)
1827			break
1828		}
1829		i.openSessionOpsDialog()
1830	default:
1831		// Last-resort fallback: try the extension manager. Built-in
1832		// cases above always win; this branch only fires for slash
1833		// commands the extension manager registered. Same routing as
1834		// the editor's submit-handler dispatch path so the autocomplete
1835		// "enter on highlighted suggestion" flow also works.
1836		extName := strings.TrimPrefix(parts[0], "/")
1837		if i.cfg.Extensions != nil && i.cfg.Extensions.HasCommand(extName) {
1838			rest := ""
1839			if len(parts) > 1 {
1840				rest = strings.Join(parts[1:], " ")
1841			}
1842			go i.invokeExtensionCommand(ctx, extName, rest)
1843			return false
1844		}
1845		i.mu.Lock()
1846		i.statusErr = "unknown command: " + parts[0]
1847		i.mu.Unlock()
1848	}
1849	return false
1850}
1851
1852// openLogoutDialog shows the provider picker for `/logout` with no
1853// argument. Only providers the user is currently logged into are
1854// listed, plus an "all" entry when more than one is present. If
1855// nothing's logged in, writes a status line instead of opening an
1856// empty dialog.
1857func (i *Interactive) openLogoutDialog() {
1858	if i.cfg.AuthManager == nil {
1859		i.mu.Lock()
1860		i.statusErr = "no auth manager configured"
1861		i.mu.Unlock()
1862		i.invalidate()
1863		return
1864	}
1865	store := i.cfg.AuthManager.Store()
1866	if store == nil {
1867		i.mu.Lock()
1868		i.statusErr = "auth store is not available"
1869		i.mu.Unlock()
1870		i.invalidate()
1871		return
1872	}
1873	creds, err := store.Load()
1874	if err != nil {
1875		i.mu.Lock()
1876		i.statusErr = "read auth store: " + err.Error()
1877		i.mu.Unlock()
1878		i.invalidate()
1879		return
1880	}
1881
1882	var items []logoutItem
1883	for _, p := range []string{"anthropic", "openai"} {
1884		if creds.Has(p) {
1885			items = append(items, logoutItem{
1886				label:  p,
1887				target: p,
1888				method: creds.Method(p),
1889			})
1890		}
1891	}
1892	if len(items) == 0 {
1893		i.mu.Lock()
1894		i.statusOK = "no credentials stored; already logged out"
1895		i.statusErr = ""
1896		i.mu.Unlock()
1897		i.invalidate()
1898		return
1899	}
1900	if len(items) > 1 {
1901		items = append(items, logoutItem{label: "all", target: "all"})
1902	}
1903
1904	i.logoutDialog.Open(items)
1905	i.invalidate()
1906}
1907
1908// doLogout clears credentials for the given provider (or all providers)
1909// from auth.json. If the active agent was using those credentials, it
1910// is torn down so the user is forced through /login before their next
1911// prompt.
1912//
1913// target: "anthropic" | "openai" | "all"
1914func (i *Interactive) doLogout(target string) {
1915	if i.cfg.AuthManager == nil {
1916		i.mu.Lock()
1917		i.statusErr = "no auth manager configured"
1918		i.mu.Unlock()
1919		return
1920	}
1921	store := i.cfg.AuthManager.Store()
1922	if store == nil {
1923		i.mu.Lock()
1924		i.statusErr = "auth store is not available"
1925		i.mu.Unlock()
1926		return
1927	}
1928
1929	var providers []string
1930	switch target {
1931	case "", "all":
1932		providers = []string{"anthropic", "openai"}
1933	case "anthropic", "openai":
1934		providers = []string{target}
1935	default:
1936		i.mu.Lock()
1937		i.statusErr = "unknown provider: " + target + " (use anthropic, openai, or all)"
1938		i.mu.Unlock()
1939		return
1940	}
1941
1942	var errs []string
1943	clearedCurrent := false
1944	for _, p := range providers {
1945		if err := store.Clear(p); err != nil {
1946			errs = append(errs, p+": "+err.Error())
1947			continue
1948		}
1949		if p == i.cfg.Provider {
1950			clearedCurrent = true
1951		}
1952	}
1953
1954	i.mu.Lock()
1955	defer i.mu.Unlock()
1956	if len(errs) > 0 {
1957		i.statusErr = "logout errors: " + strings.Join(errs, "; ")
1958		return
1959	}
1960	i.statusErr = ""
1961	if clearedCurrent {
1962		// The running agent was using a credential we just wiped. Drop
1963		// it so prompts can't go out with the stale client, and hint at
1964		// /login.
1965		i.agent = nil
1966		i.statusOK = "logged out of " + strings.Join(providers, ", ") + ". type /login to sign back in."
1967	} else {
1968		i.statusOK = "logged out of " + strings.Join(providers, ", ")
1969	}
1970}
1971
1972func (i *Interactive) startAPIKeyFlow(provider string) {
1973	url, err := i.cfg.AuthManager.StartAPIKey(provider)
1974	if err != nil {
1975		i.dialog.ShowResult(false, err.Error())
1976		return
1977	}
1978	i.dialog.ShowWaiting(url)
1979}
1980
1981func (i *Interactive) startOAuthFlow(provider string) {
1982	// Always run the manual/copy-code flow in parallel with the local
1983	// callback server so headless environments (docker, SSH) can paste
1984	// the authorization code directly without first pressing 'p'.
1985	_, err := i.cfg.AuthManager.StartOAuth(provider)
1986	if err != nil {
1987		i.dialog.ShowResult(false, err.Error())
1988		return
1989	}
1990	manualURL, mErr := i.cfg.AuthManager.StartManualOAuth(provider)
1991	if mErr == nil {
1992		i.dialog.ShowWaiting(manualURL)
1993	} else {
1994		i.dialog.ShowResult(false, mErr.Error())
1995	}
1996}
1997
1998func (i *Interactive) startManualOAuthFlow(provider string) {
1999	if i.cfg.AuthManager == nil {
2000		return
2001	}
2002	i.cfg.AuthManager.CancelOAuth()
2003	url, err := i.cfg.AuthManager.StartManualOAuth(provider)
2004	if err != nil {
2005		i.dialog.ShowResult(false, err.Error())
2006		return
2007	}
2008	i.dialog.url = url
2009	i.invalidate()
2010}
2011
2012func (i *Interactive) submitManualOAuthCode(code string) {
2013	if i.cfg.AuthManager == nil {
2014		return
2015	}
2016	go func() {
2017		if err := i.cfg.AuthManager.CompleteManualOAuth(i.runCtx, code); err != nil {
2018			i.dialog.ShowResult(false, err.Error())
2019			i.invalidate()
2020		}
2021	}()
2022}
2023
2024// applyModelSelection switches the active model (and provider, if the
2025// new model belongs to a different one). It rebuilds the underlying
2026// client when needed so the provider wire-protocol matches.
2027// cancelAndWaitForIdle cancels the active turn (if any) and blocks
2028// briefly until the turn goroutine has updated i.busy = false. Used
2029// before destructive slash commands so transcript-mutating work
2030// (/clear, /compact, /logout, /login completion, cross-provider
2031// /model swap) doesn't race with the still-running stream.
2032//
2033// The wait is bounded; if the turn doesn't release within the timeout
2034// we proceed anyway. Worst case is a brief overlap that the agent's
2035// own mutex protects against.
2036func (i *Interactive) cancelAndWaitForIdle() {
2037	i.mu.Lock()
2038	busy := i.busy
2039	cancel := i.cancelTurn
2040	i.mu.Unlock()
2041	if !busy {
2042		return
2043	}
2044	if cancel != nil {
2045		cancel()
2046	}
2047	deadline := time.Now().Add(2 * time.Second)
2048	for time.Now().Before(deadline) {
2049		i.mu.Lock()
2050		done := !i.busy
2051		i.mu.Unlock()
2052		if done {
2053			return
2054		}
2055		time.Sleep(10 * time.Millisecond)
2056	}
2057}
2058
2059// openBtwDialog opens the side-chat overlay with a frozen snapshot
2060// of the current main session. The optional argument is auto-
2061// submitted as the first question, so '/btw does X work?' fires the
2062// model call immediately instead of just opening an empty dialog.
2063func (i *Interactive) openBtwDialog(args []string) {
2064	if i.agent == nil {
2065		i.mu.Lock()
2066		i.statusErr = "not logged in. type /login first."
2067		i.mu.Unlock()
2068		return
2069	}
2070	seed := strings.TrimSpace(strings.Join(args, " "))
2071	i.btwDialog.Open(i.cfg.Theme, i.agent, i.agent.System, i.cfg.Model, seed, i.invalidate)
2072	i.invalidate()
2073}
2074
2075// openSkillsDialog opens the skill inspector. The picker reflects
2076// whatever SkillSnapshot returns at call time, so edits to a
2077// SKILL.md made during a session show up on the next /skills.
2078func (i *Interactive) openSkillsDialog() {
2079	var list []*skills.Skill
2080	if i.cfg.SkillSnapshot != nil {
2081		list = i.cfg.SkillSnapshot()
2082	}
2083	i.skillsDialog.Open(list)
2084	i.invalidate()
2085}
2086
2087// openJumpDialog builds a /jump picker from the current transcript.
2088// If the user typed "/jump foo" with a filter and it matches exactly
2089// one turn, jump there directly without showing the dialog.
2090func (i *Interactive) openJumpDialog(args []string) {
2091	if i.view == nil || len(i.view.Messages) == 0 {
2092		i.mu.Lock()
2093		i.statusErr = "nothing to jump to \u2014 the session is empty"
2094		i.mu.Unlock()
2095		return
2096	}
2097	filter := strings.TrimSpace(strings.Join(args, " "))
2098	i.jumpDialog.Open(i.view.Messages, filter)
2099	// Shortcut: with a filter argument that matches exactly one turn,
2100	// jump immediately and skip the picker.
2101	if filter != "" {
2102		if tgts := i.jumpDialog.Targets(); len(tgts) == 1 {
2103			t := tgts[0]
2104			i.jumpDialog.Close()
2105			i.applyJumpSelection(t.MessageIdx, t.TurnNo)
2106		}
2107	}
2108}
2109
2110// applyJumpSelection scrolls the chat viewport so the user message at
2111// msgIdx is visible at (or near) the top of the chat area. Uses the
2112// anchor slice returned by view.BuildWithAnchors so the mapping from
2113// message index to row is exact, regardless of variable-height tool
2114// blocks above the target.
2115func (i *Interactive) applyJumpSelection(msgIdx, turnNo int) {
2116	cols := i.lastCols()
2117	chat, anchors := i.view.BuildWithAnchors(cols)
2118	var row int
2119	found := false
2120	for _, a := range anchors {
2121		if a.MessageIdx == msgIdx {
2122			row = a.Row
2123			found = true
2124			break
2125		}
2126	}
2127	if !found {
2128		i.mu.Lock()
2129		i.statusErr = "could not resolve jump target"
2130		i.mu.Unlock()
2131		return
2132	}
2133
2134	chatLen := len(chat)
2135	page := i.chatPage()
2136	if page < 1 {
2137		page = 1
2138	}
2139	// scrollOffset is measured from the bottom of the chat slice, so
2140	// to place `row` at the top of the viewport we want:
2141	//     chatLen - scrollOffset - page == row
2142	// Solve for scrollOffset and clamp to [0, chatLen-page].
2143	offset := chatLen - (row + page)
2144	if offset < 0 {
2145		offset = 0
2146	}
2147	maxOffset := chatLen - page
2148	if maxOffset < 0 {
2149		maxOffset = 0
2150	}
2151	if offset > maxOffset {
2152		offset = maxOffset
2153	}
2154
2155	i.mu.Lock()
2156	i.scrollOffset = offset
2157	i.parkedTurn = turnNo
2158	i.parkedTotal = totalTurnsLocked(i.view.Messages)
2159	i.statusOK = fmt.Sprintf("jumped to turn %d", turnNo)
2160	i.statusErr = ""
2161	i.mu.Unlock()
2162}
2163
2164// totalTurnsLocked counts user messages in the transcript. Caller is
2165// assumed to hold i.mu (the name is a mild reminder; this function
2166// itself doesn't touch shared state beyond the slice it's handed).
2167func totalTurnsLocked(msgs []provider.Message) int {
2168	n := 0
2169	for _, m := range msgs {
2170		if m.Role == provider.RoleUser {
2171			n++
2172		}
2173	}
2174	return n
2175}
2176
2177// applySessionSelection loads the given session via the cli-provided
2178// callback and parks the viewport on the last turn so the user lands
2179// looking at where the conversation left off (their last prompt at the
2180// top of the chat, the assistant's last reply right below). Older
2181// history is one scroll up; pgdn or end snaps to the current tail.
2182//
2183// Without this, scrollOffset stayed at 0 (pinned to the live tail),
2184// which on a long resumed session showed only the last few rows of
2185// the final assistant message — the user read that as "only one liner
2186// happened, the resume didn't work".
2187func (i *Interactive) applySessionSelection(path string) {
2188	if i.cfg.LoadSession == nil {
2189		i.mu.Lock()
2190		i.statusErr = "session loading is not wired in this build"
2191		i.mu.Unlock()
2192		return
2193	}
2194	if err := i.cfg.LoadSession(path); err != nil {
2195		i.mu.Lock()
2196		i.statusErr = err.Error()
2197		i.mu.Unlock()
2198		return
2199	}
2200
2201	i.mu.Lock()
2202	i.statusOK = "resumed session: " + path
2203	i.statusErr = ""
2204	i.parkedTurn = 0
2205	i.parkedTotal = 0
2206	i.view.InvalidateRenderCache()
2207	// Pull the freshly-loaded transcript into the view so the anchor
2208	// math below sees the post-resume messages, not the empty pre-load
2209	// state. redraw() does the same on its next pass; we just front-run
2210	// it here to compute the scroll target.
2211	if i.agent != nil {
2212		i.view.Messages = i.agent.Messages()
2213	}
2214	msgs := i.view.Messages
2215	i.mu.Unlock()
2216
2217	i.scrollToLastTurn(msgs)
2218}
2219
2220// scrollToLastTurn parks the viewport at the most recent user turn,
2221// or at the top if the transcript has no user messages. Used after
2222// resume so the user lands looking at where they left off.
2223func (i *Interactive) scrollToLastTurn(msgs []provider.Message) {
2224	if len(msgs) == 0 {
2225		i.mu.Lock()
2226		i.scrollOffset = 0
2227		i.mu.Unlock()
2228		return
2229	}
2230	// Find the last user message index.
2231	lastUser := -1
2232	turnNo, totalTurns := 0, 0
2233	for idx, m := range msgs {
2234		if m.Role == provider.RoleUser {
2235			totalTurns++
2236			lastUser = idx
2237		}
2238	}
2239	if lastUser < 0 {
2240		i.mu.Lock()
2241		i.scrollOffset = 0
2242		i.mu.Unlock()
2243		return
2244	}
2245	turnNo = totalTurns
2246
2247	cols := i.lastCols()
2248	chat, anchors := i.view.BuildWithAnchors(cols)
2249	var row int
2250	found := false
2251	for _, a := range anchors {
2252		if a.MessageIdx == lastUser {
2253			row = a.Row
2254			found = true
2255			break
2256		}
2257	}
2258	if !found {
2259		i.mu.Lock()
2260		i.scrollOffset = 0
2261		i.mu.Unlock()
2262		return
2263	}
2264
2265	chatLen := len(chat)
2266	page := i.chatPage()
2267	if page < 1 {
2268		page = 1
2269	}
2270	offset := chatLen - (row + page)
2271	if offset < 0 {
2272		offset = 0
2273	}
2274	maxOffset := chatLen - page
2275	if maxOffset < 0 {
2276		maxOffset = 0
2277	}
2278	if offset > maxOffset {
2279		offset = maxOffset
2280	}
2281
2282	i.mu.Lock()
2283	i.scrollOffset = offset
2284	// Mark the parked-turn footer so the user sees "viewing turn N of
2285	// M - pgdn to catch up" — same affordance as /jump. Tells them at
2286	// a glance that they're looking at history, not the live tail.
2287	if offset > 0 {
2288		i.parkedTurn = turnNo
2289		i.parkedTotal = totalTurns
2290	}
2291	i.mu.Unlock()
2292	i.invalidate()
2293}
2294
2295func (i *Interactive) applyModelSelection(prov, model string) {
2296	if model == "" {
2297		return
2298	}
2299	m, err := provider.FindModel(prov, model)
2300	if err != nil {
2301		i.mu.Lock()
2302		i.statusErr = err.Error()
2303		i.mu.Unlock()
2304		return
2305	}
2306	// Same provider? Just swap the model on the existing agent.
2307	if i.agent != nil && m.Provider == i.cfg.Provider {
2308		i.mu.Lock()
2309		i.cfg.Model = m.ID
2310		i.agent.Model = m.ID
2311		i.statusOK = "model: " + m.ID
2312		i.statusErr = ""
2313		i.mu.Unlock()
2314		if i.cfg.PersistModel != nil {
2315			i.cfg.PersistModel(i.cfg.Provider, m.ID)
2316		}
2317		return
2318	}
2319	// Different provider: rebuild agent (needs credentials for target provider).
2320	if i.cfg.BuildAgentFor == nil {
2321		i.mu.Lock()
2322		i.statusErr = "cannot switch provider: no builder configured"
2323		i.mu.Unlock()
2324		return
2325	}
2326	// Snapshot the current transcript and cumulative usage BEFORE we
2327	// build the replacement agent so we can hand them off. Without
2328	// this the user perceives the entire session as wiped on a
2329	// cross-provider /model swap.
2330	var carryMsgs []provider.Message
2331	var carryCost provider.Usage
2332	if i.agent != nil {
2333		carryMsgs = i.agent.Messages()
2334		carryCost = i.agent.Cost()
2335	}
2336
2337	ag, p, md, err := i.cfg.BuildAgentFor(m.Provider, m.ID)
2338	if err != nil {
2339		i.mu.Lock()
2340		i.statusErr = err.Error()
2341		i.mu.Unlock()
2342		return
2343	}
2344
2345	// Replay the transcript and seed the cost on the freshly-built
2346	// agent. Messages travel cleanly between providers because they
2347	// use the same provider.Message shape; tool-call ids are local
2348	// to a turn so cross-provider continuation never confuses the
2349	// new model (it just sees the assistant's reply, no orphan
2350	// tool_use blocks because /model swaps are gated to idle state).
2351	if len(carryMsgs) > 0 {
2352		ag.SetMessages(carryMsgs)
2353	}
2354	ag.SeedCost(carryCost)
2355
2356	i.mu.Lock()
2357	i.agent = ag
2358	i.cfg.Provider = p
2359	i.cfg.Model = md
2360	i.statusOK = "switched to " + p + " / " + md
2361	i.statusErr = ""
2362	// Render cache keys are width+content based, so the new agent's
2363	// identical messages will reuse the existing entries. Nothing
2364	// to invalidate.
2365	i.mu.Unlock()
2366	if i.cfg.PersistModel != nil {
2367		i.cfg.PersistModel(p, md)
2368	}
2369}
2370
2371func (i *Interactive) handleAuthEvent(ev auth.Event) {
2372	switch ev.Kind {
2373	case "started":
2374		i.dialog.ShowWaiting(ev.URL)
2375	case "browser_open":
2376		// no-op
2377	case "error":
2378		i.dialog.ShowResult(false, ev.Message)
2379	case "success":
2380		// Rebuild the agent with the fresh credential.
2381		ag, prov, model, err := i.cfg.BuildAgent()
2382		if err != nil {
2383			i.dialog.ShowResult(false, err.Error())
2384			return
2385		}
2386		i.mu.Lock()
2387		i.agent = ag
2388		i.cfg.Provider = prov
2389		i.cfg.Model = model
2390		i.statusErr = ""
2391		i.statusOK = "logged in to " + ev.Provider + " via " + ev.Method
2392		i.mu.Unlock()
2393		i.dialog.ShowResult(true, "")
2394	}
2395}
2396
2397// runCompact invokes core.Agent.Compact and reflects the progress in
2398// the tui. It runs in a goroutine so the ui stays responsive; esc/ctrl+c
2399// cancel via the same cancelTurn channel used for normal turns.
2400//
2401// When auto is true the spinner message is pinned to "condensing
2402// history" and the status bar surfaces "(auto)" next to the context
2403// percentage so it's obvious the system triggered this, not the user.
2404func (i *Interactive) runCompact(parent context.Context, auto bool) {
2405	if i.agent == nil {
2406		i.mu.Lock()
2407		i.statusErr = "not logged in. type /login first."
2408		i.mu.Unlock()
2409		return
2410	}
2411	ctx, cancel := context.WithCancel(parent)
2412	i.mu.Lock()
2413	i.busy = true
2414	if auto {
2415		i.spin.StartFixed("condensing history")
2416		i.autoCompacting = true
2417	} else {
2418		i.spin.StartFixed("compacting")
2419	}
2420	i.cancelTurn = cancel
2421	i.statusErr = ""
2422	i.statusOK = ""
2423	// Do NOT set streamOn: the summary text should not be visible
2424	// in the chat while compacting. The user just sees the spinner
2425	// and can keep typing / queue prompts.
2426	i.scrollOffset = 0
2427	i.helpBlock = nil
2428	i.mu.Unlock()
2429	i.invalidate()
2430
2431	go func() {
2432		// Sink discards deltas — we don't stream the summary to the UI.
2433		sink := func(delta string) {}
2434		summary, err := i.agent.Compact(ctx, 4, sink)
2435		_ = summary
2436		i.mu.Lock()
2437		i.busy = false
2438		i.resetStreamingStateLocked()
2439		i.cancelTurn = nil
2440		i.autoCompacting = false
2441
2442		// Drain the queue: if the user typed a prompt while compacting,
2443		// fire it now that the transcript is clean.
2444		var next string
2445		var hasNext bool
2446
2447		switch {
2448		case err != nil && ctx.Err() != nil:
2449			i.statusErr = ""
2450			if auto {
2451				i.statusOK = "auto-condense cancelled"
2452			} else {
2453				i.statusOK = "compaction cancelled"
2454			}
2455			i.queued = nil // drop queue on cancel
2456		case err != nil:
2457			i.statusErr = "compaction failed: " + err.Error()
2458			i.statusOK = ""
2459			i.queued = nil // drop queue on error
2460		default:
2461			i.statusErr = ""
2462			// Read token count from the compaction message meta.
2463			tokens := ""
2464			msgs := i.agent.Messages()
2465			if len(msgs) > 0 && msgs[0].Meta["compaction"] == "true" {
2466				tokens = msgs[0].Meta["tokens_before"]
2467			}
2468			if tokens != "" {
2469				i.statusOK = fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens)
2470			} else {
2471				i.statusOK = "compacted (ctrl+o to expand)"
2472			}
2473			i.lastCtxInput = 0
2474			i.toolCalls = map[string]*tui.ToolCallView{}
2475			i.toolOrder = nil
2476			i.view.InvalidateRenderCache()
2477			// Pop queued prompt if any.
2478			if len(i.queued) > 0 {
2479				next, i.queued = i.queued[0], i.queued[1:]
2480				hasNext = true
2481			}
2482		}
2483		i.mu.Unlock()
2484		i.invalidate()
2485
2486		if hasNext {
2487			p := i.runCtx
2488			if p == nil {
2489				p = context.Background()
2490			}
2491			i.startTurn(p, next)
2492		}
2493	}()
2494}
2495
2496func (i *Interactive) startTurn(parent context.Context, prompt string) {
2497	if i.agent == nil {
2498		return
2499	}
2500	ctx, cancel := context.WithCancel(parent)
2501	i.mu.Lock()
2502	i.busy = true
2503	i.spin.Start()
2504	i.cancelTurn = cancel
2505	i.statusErr = ""
2506	i.statusOK = ""
2507	i.streaming.Reset()
2508	i.streamOn = true
2509	i.toolCalls = map[string]*tui.ToolCallView{}
2510	i.toolOrder = nil
2511	i.scrollOffset = 0 // jump back to the bottom on new turn
2512	i.parkedTurn = 0   // starting a turn clears the /jump parked state
2513	i.parkedTotal = 0
2514	i.helpBlock = nil // hide the help block once the user asks something
2515	i.mu.Unlock()
2516	i.invalidate()
2517
2518	sink := func(ev core.AgentEvent) {
2519		i.handleEvent(ev)
2520		i.invalidate()
2521	}
2522
2523	go func() {
2524		err := i.agent.Prompt(ctx, prompt, nil, sink)
2525		i.mu.Lock()
2526		i.busy = false
2527		// Don't touch streamPending / streamFlushPending here — the
2528		// pacer may still be draining the final deltas and needs to
2529		// paint them even though Prompt has returned. It will reset
2530		// streamOn on its own once the buffer empties.
2531		if len(i.streamPending) == 0 {
2532			i.streamOn = false
2533		}
2534		i.cancelTurn = nil
2535		if err != nil && ctx.Err() == nil {
2536			i.statusErr = err.Error()
2537		}
2538		// Persist the assistant's reply (and every tool row before
2539		// it) to the session file while the turn memory is hot.
2540		// Without this, WriteNewTranscript only fires at zot exit,
2541		// meaning a crash or ungraceful kill drops the whole
2542		// conversation. FlushSession is idempotent (it advances the
2543		// baseline so subsequent flushes only write new rows).
2544		flush := i.cfg.FlushSession
2545		i.mu.Unlock()
2546		if flush != nil {
2547			flush()
2548		}
2549		i.mu.Lock()
2550		// Pop the next queued message, if any, and relaunch.
2551		var next string
2552		var hasNext bool
2553		if len(i.queued) > 0 && ctx.Err() == nil && err == nil {
2554			next, i.queued = i.queued[0], i.queued[1:]
2555			hasNext = true
2556		}
2557		// If the turn was cancelled or errored, drop the queue so the
2558		// user isn't bombarded with stale messages after an interrupt.
2559		if ctx.Err() != nil || err != nil {
2560			i.queued = nil
2561		}
2562		// Decide whether the next thing to do is an auto-compaction.
2563		// Only fires when the turn completed cleanly AND the queue is
2564		// empty (otherwise a queued message would race the condense).
2565		shouldAutoCompact := !hasNext && err == nil && ctx.Err() == nil && i.shouldAutoCompactLocked()
2566		i.mu.Unlock()
2567		i.invalidate()
2568		parent := i.runCtx
2569		if parent == nil {
2570			parent = context.Background()
2571		}
2572		switch {
2573		case hasNext:
2574			i.startTurn(parent, next)
2575		case shouldAutoCompact:
2576			i.runCompact(parent, true)
2577		}
2578	}()
2579}
2580
2581// autoCompactThreshold is the context-window fraction at which the
2582// agent will auto-compact after a turn ends. 0.85 leaves enough
2583// headroom for one more user prompt + response before we bump the
2584// hard limit.
2585const autoCompactThreshold = 0.85
2586
2587// shouldAutoCompactLocked reports whether the last turn pushed context
2588// usage past the auto-compact threshold. Must be called with i.mu
2589// held; it reads lastCtxInput and the current model's context window.
2590func (i *Interactive) shouldAutoCompactLocked() bool {
2591	if i.agent == nil {
2592		return false
2593	}
2594	if i.autoCompacting {
2595		return false
2596	}
2597	m, err := provider.FindModel(i.cfg.Provider, i.cfg.Model)
2598	if err != nil || m.ContextWindow <= 0 {
2599		return false
2600	}
2601	if i.lastCtxInput <= 0 {
2602		return false
2603	}
2604	return float64(i.lastCtxInput)/float64(m.ContextWindow) >= autoCompactThreshold
2605}
2606
2607func (i *Interactive) handleEvent(ev core.AgentEvent) {
2608	i.mu.Lock()
2609	defer i.mu.Unlock()
2610	switch e := ev.(type) {
2611	case core.EvAssistantStart:
2612		// Fires at the top of every oneTurn, including follow-up
2613		// turns after tool use. Without this, the streaming buffer
2614		// is still marked off from the previous assistant message
2615		// and the final summary text pops in all at once instead
2616		// of typewriter-streaming delta by delta.
2617		i.streaming.Reset()
2618		i.streamPending = i.streamPending[:0]
2619		i.streamFlushPending = false
2620		i.streamOn = true
2621		// Clear the live tool-call overlay. Any tools from the
2622		// previous round are now fully folded into the transcript
2623		// (assistant tool_use block + tool role message with the
2624		// result), so keeping them in the overlay would duplicate
2625		// them in the view — once inside the finalised transcript
2626		// and once below the streaming block, with the streaming
2627		// summary sandwiched in between. The next EvToolUseStart
2628		// will populate fresh entries for this turn's tools.
2629		i.toolCalls = map[string]*tui.ToolCallView{}
2630		i.toolOrder = nil
2631	case core.EvTextDelta:
2632		// Buffer into streamPending; the paintPace ticker drains
2633		// it into i.streaming a few runes at a time for a smooth
2634		// typewriter effect independent of upstream chunk size.
2635		i.streamPending = append(i.streamPending, []rune(e.Delta)...)
2636		i.streamOn = true
2637	case core.EvAssistantMessage:
2638		// OnAssistant + telegram mirroring always fire on message
2639		// arrival — they read the FINAL message content, which is
2640		// complete regardless of what's still in the pacer.
2641		i.assistantMessageSideEffects(e.Message)
2642		// If the pacer still has characters to drain, keep streamOn
2643		// true and mark flush pending; the paintPace ticker will
2644		// drain the remainder and reset streaming state when done.
2645		// Otherwise (rare: full-replay sessions, abort paths) clear
2646		// synchronously so a later render doesn't show stale text.
2647		if len(i.streamPending) > 0 {
2648			i.streamFlushPending = true
2649			return
2650		}
2651		i.resetStreamingStateLocked()
2652		// Force full repaint: assistant text committed, layout shifts.
2653		if i.rend != nil {
2654			i.rend.Invalidate()
2655		}
2656	case core.EvToolUseStart:
2657		// Live streaming: pre-create the view so the user sees the
2658		// tool call being composed in real time. Any subsequent
2659		// EvToolCall for the same ID updates the same struct (the
2660		// final parsed args + name are already known here).
2661		if _, exists := i.toolCalls[e.ID]; !exists {
2662			i.toolCalls[e.ID] = &tui.ToolCallView{
2663				ID:        e.ID,
2664				Name:      e.Name,
2665				Streaming: true,
2666			}
2667			i.toolOrder = append(i.toolOrder, e.ID)
2668		}
2669	case core.EvToolUseArgs:
2670		if tc, ok := i.toolCalls[e.ID]; ok {
2671			tc.RawJSONBuf += e.Delta
2672			// Refresh the live path as soon as it parses; used in
2673			// the header (write /Users/pat/Desktop/demo.ts)
2674			// while the content is still streaming.
2675			if p, pok, _ := tui.ExtractPartialStringField(tc.RawJSONBuf, "path"); pok {
2676				tc.LivePath = p
2677			} else if p, pok, _ := tui.ExtractPartialStringField(tc.RawJSONBuf, "file_path"); pok {
2678				tc.LivePath = p
2679			}
2680		}
2681	case core.EvToolUseEnd:
2682		if tc, ok := i.toolCalls[e.ID]; ok {
2683			tc.Streaming = false
2684		}
2685	case core.EvToolCall:
2686		// If we already pre-created the view during streaming, just
2687		// refresh the final Args summary. Otherwise create a new one
2688		// (non-streaming providers or legacy paths).
2689		if tc, ok := i.toolCalls[e.ID]; ok {
2690			tc.Args = tui.ShortArgs(e.Name, e.Args)
2691			tc.Streaming = false
2692		} else {
2693			i.toolCalls[e.ID] = &tui.ToolCallView{
2694				ID:   e.ID,
2695				Name: e.Name,
2696				Args: tui.ShortArgs(e.Name, e.Args),
2697			}
2698			i.toolOrder = append(i.toolOrder, e.ID)
2699		}
2700	case core.EvToolResult:
2701		if tc, ok := i.toolCalls[e.ID]; ok {
2702			tc.Done = true
2703			tc.Error = e.Result.IsError
2704			var text strings.Builder
2705			for _, c := range e.Result.Content {
2706				if tb, ok := c.(provider.TextBlock); ok {
2707					if text.Len() > 0 {
2708						text.WriteString("\n")
2709					}
2710					text.WriteString(tb.Text)
2711				}
2712			}
2713			tc.Result = text.String()
2714		}
2715		// Force full repaint: tool completion shifts the layout
2716		// (collapsed body replaces streaming) and the diff renderer
2717		// may leave stale code fragments on status bar rows.
2718		if i.rend != nil {
2719			i.rend.Invalidate()
2720		}
2721		if i.cfg.OnToolResult != nil {
2722			i.cfg.OnToolResult(e.ID, e.Result)
2723		}
2724	case core.EvUsage:
2725		i.cumUsage = e.Cumulative
2726		if e.Usage.InputTokens > 0 {
2727			i.lastCtxInput = e.Usage.InputTokens + e.Usage.CacheReadTokens + e.Usage.CacheWriteTokens
2728		}
2729	case core.EvTurnEnd:
2730		// Force full repaint: the turn ending shifts layout (streaming
2731		// buffer flushed, status bar updates) and the diff renderer
2732		// may leave stale content on reused rows.
2733		if i.rend != nil {
2734			i.rend.Invalidate()
2735		}
2736		if e.Stop == provider.StopAborted {
2737			i.resetStreamingStateLocked()
2738			i.statusErr = ""
2739			i.statusOK = "cancelled"
2740			return
2741		}
2742		if e.Err != nil && !strings.Contains(e.Err.Error(), "context canceled") {
2743			i.statusErr = e.Err.Error()
2744		}
2745	}
2746}
2747
2748// Agent returns the current agent, if any. Used by cli.go to flush the
2749// final transcript to the session file.
2750func (i *Interactive) Agent() *core.Agent {
2751	i.mu.Lock()
2752	defer i.mu.Unlock()
2753	return i.agent
2754}
2755
2756// silence unused import in some build configs
2757var _ = fmt.Sprintf
2758
2759// runReloadExt triggers a live reload of every extension (discovered
2760// + explicit). Runs on a goroutine so the TUI stays responsive; the
2761// Manager.Reload takes a couple of hundred ms to shut down subprocs
2762// and respawn them. Shows a status line throughout.
2763func (i *Interactive) runReloadExt(ctx context.Context) {
2764	if i.cfg.Extensions == nil {
2765		i.mu.Lock()
2766		i.statusErr = "no extension manager in this build"
2767		i.mu.Unlock()
2768		i.invalidate()
2769		return
2770	}
2771	i.mu.Lock()
2772	i.statusOK = "reloading extensions…"
2773	i.statusErr = ""
2774	i.mu.Unlock()
2775	i.invalidate()
2776
2777	go func() {
2778		stats := i.cfg.Extensions.Reload(ctx, 2*time.Second)
2779		msg := fmt.Sprintf("reloaded: %d stopped, %d loaded (%d ready)", stats.Stopped, stats.Loaded, stats.Ready)
2780		if len(stats.Errors) > 0 {
2781			msg += fmt.Sprintf(", %d error(s)", len(stats.Errors))
2782		}
2783		i.mu.Lock()
2784		i.statusOK = msg
2785		i.statusErr = ""
2786		i.mu.Unlock()
2787		i.invalidate()
2788	}()
2789}
2790
2791// Confirm implements core.Confirmer. The agent goroutine calls
2792// this synchronously before every tool invocation when --no-yolo is
2793// active. We push the request onto the confirmDialog queue, trigger
2794// a redraw, and block the caller until the user answers.
2795//
2796// If the session is cancelled or the TUI exits mid-prompt, any
2797// pending request is refused via CancelAll so the agent doesn't
2798// deadlock.
2799func (i *Interactive) Confirm(toolName string, preview string) core.ConfirmDecision {
2800	resp := make(chan core.ConfirmDecision, 1)
2801	i.confirmDialog.Enqueue(&confirmRequest{
2802		toolName: toolName,
2803		preview:  preview,
2804		resp:     resp,
2805	})
2806	i.invalidate()
2807	return <-resp
2808}
2809
2810// runYoloOn disables --no-yolo for the rest of the session. Tool
2811// calls run without prompting after this; there's intentionally no
2812// way to re-enable gating mid-session, if the user wants that back
2813// they can exit and restart with --no-yolo.
2814func (i *Interactive) runYoloOn() {
2815	if i.cfg.ConfirmGate == nil {
2816		i.mu.Lock()
2817		i.statusOK = "yolo mode is already on (no --no-yolo in this session)"
2818		i.statusErr = ""
2819		i.mu.Unlock()
2820		i.invalidate()
2821		return
2822	}
2823	i.cfg.ConfirmGate.AllowAll()
2824	// Also auto-allow any currently pending confirmation so the
2825	// agent doesn't deadlock if /yolo is typed while a prompt is
2826	// open.
2827	i.confirmDialog.AllowAllPending()
2828	i.mu.Lock()
2829	i.statusOK = "yolo engaged: no more tool-call confirmations this session"
2830	i.statusErr = ""
2831	i.mu.Unlock()
2832	i.invalidate()
2833}
2834
2835// openTelegramDialog shows the picker for `/telegram` with no arg.
2836// Items depend on current state: disconnect + status when running,
2837// connect + status when stopped.
2838func (i *Interactive) openTelegramDialog() {
2839	items := i.telegramMenuItems()
2840	if len(items) == 0 {
2841		i.mu.Lock()
2842		i.statusErr = "telegram not configured. run `zot telegram-bot setup` first."
2843		i.mu.Unlock()
2844		i.invalidate()
2845		return
2846	}
2847	i.telegramDialog.Open(items)
2848	i.invalidate()
2849}
2850
2851// telegramMenuItems builds the dialog entries for the current
2852// bridge state. Returns empty when no bot.json exists so the
2853// caller can show a helpful status line instead of an empty menu.
2854func (i *Interactive) telegramMenuItems() []telegramItem {
2855	cfg, err := telegram.LoadConfig(i.cfg.ZotHome)
2856	if err != nil || cfg.BotToken == "" {
2857		return nil
2858	}
2859	var items []telegramItem
2860	if i.telegramBridge != nil && i.telegramBridge.Active() {
2861		items = append(items, telegramItem{label: "disconnect", action: "disconnect", hint: "stop mirroring"})
2862		st := i.telegramBridge.State()
2863		hint := "active"
2864		if st.Username != "" {
2865			hint += " as @" + st.Username
2866		}
2867		items = append(items, telegramItem{label: "status", action: "status", hint: hint})
2868	} else {
2869		label := "connect"
2870		hint := "start mirroring dms into this session"
2871		if cfg.AllowedUserID == 0 {
2872			hint = "awaiting pairing (send /start to the bot once connected)"
2873		}
2874		items = append(items, telegramItem{label: label, action: "connect", hint: hint})
2875		items = append(items, telegramItem{label: "status", action: "status", hint: "disconnected"})
2876	}
2877	return items
2878}
2879
2880// doTelegram dispatches one of the three explicit actions. Called
2881// from /telegram <action> or after the picker selects a row.
2882func (i *Interactive) doTelegram(action string) {
2883	switch action {
2884	case "connect":
2885		i.telegramConnect()
2886	case "disconnect":
2887		i.telegramDisconnect()
2888	case "status":
2889		i.telegramStatus()
2890	default:
2891		i.mu.Lock()
2892		i.statusErr = "unknown telegram action: " + action + " (use connect, disconnect, or status)"
2893		i.mu.Unlock()
2894		i.invalidate()
2895	}
2896}
2897
2898// telegramConnect starts the bridge. Refuses if it's already
2899// running or if the on-disk bot.json is missing a token.
2900func (i *Interactive) telegramConnect() {
2901	if i.telegramBridge != nil && i.telegramBridge.Active() {
2902		i.mu.Lock()
2903		i.statusOK = "telegram already connected"
2904		i.statusErr = ""
2905		i.mu.Unlock()
2906		i.invalidate()
2907		return
2908	}
2909	cfg, err := telegram.LoadConfig(i.cfg.ZotHome)
2910	if err != nil {
2911		i.mu.Lock()
2912		i.statusErr = "telegram: " + err.Error()
2913		i.mu.Unlock()
2914		i.invalidate()
2915		return
2916	}
2917	if cfg.BotToken == "" {
2918		i.mu.Lock()
2919		i.statusErr = "telegram: no bot token configured. run `zot telegram-bot setup` first."
2920		i.mu.Unlock()
2921		i.invalidate()
2922		return
2923	}
2924	// Refuse to start when a background daemon is already polling
2925	// the same bot. Two concurrent long-poll consumers race each
2926	// update and one always loses, so DMs get half-delivered. The
2927	// user can `zot telegram-bot stop` first, then /telegram connect.
2928	if pid, alive, _ := telegram.IsRunning(i.cfg.ZotHome); alive && pid > 0 {
2929		i.mu.Lock()
2930		i.statusErr = fmt.Sprintf("telegram: bot daemon already running (pid %d). stop it with `zot telegram-bot stop` first.", pid)
2931		i.mu.Unlock()
2932		i.invalidate()
2933		return
2934	}
2935	i.telegramBridge = &telegram.Bridge{
2936		Client: telegram.NewClient(cfg.BotToken),
2937		Config: cfg,
2938		Save: func(next telegram.Config) error {
2939			return telegram.SaveConfig(i.cfg.ZotHome, next)
2940		},
2941		Host: &telegramHost{iv: i},
2942	}
2943	if err := i.telegramBridge.Start(i.runCtx); err != nil {
2944		i.telegramBridge = nil
2945		i.mu.Lock()
2946		i.statusErr = "telegram connect failed: " + err.Error()
2947		i.mu.Unlock()
2948		i.invalidate()
2949		return
2950	}
2951	state := i.telegramBridge.State()
2952	label := "telegram connected"
2953	if state.Username != "" {
2954		label += " as @" + state.Username
2955	}
2956	if state.PairedID == 0 {
2957		label += " — send /start to the bot from your phone to claim it"
2958	}
2959	i.mu.Lock()
2960	i.statusOK = label
2961	i.statusErr = ""
2962	i.mu.Unlock()
2963	i.invalidate()
2964}
2965
2966// telegramDisconnect stops the bridge. No-op when already stopped.
2967func (i *Interactive) telegramDisconnect() {
2968	if i.telegramBridge == nil || !i.telegramBridge.Active() {
2969		i.mu.Lock()
2970		i.statusOK = "telegram already disconnected"
2971		i.statusErr = ""
2972		i.mu.Unlock()
2973		i.invalidate()
2974		return
2975	}
2976	i.telegramBridge.Stop()
2977	i.mu.Lock()
2978	i.statusOK = "telegram disconnected"
2979	i.statusErr = ""
2980	i.mu.Unlock()
2981	i.invalidate()
2982}
2983
2984// telegramStatus writes a one-liner describing the bridge state.
2985// Reports on both the in-tui bridge and the background daemon so
2986// the user isn't confused when the daemon owns the poll loop.
2987func (i *Interactive) telegramStatus() {
2988	var msg string
2989	if i.telegramBridge != nil && i.telegramBridge.Active() {
2990		s := i.telegramBridge.State()
2991		msg = "telegram: connected (tui bridge)"
2992		if s.Username != "" {
2993			msg += " as @" + s.Username
2994		}
2995		if s.PairedID != 0 {
2996			msg += fmt.Sprintf(" - paired with user %d", s.PairedID)
2997		} else {
2998			msg += " - awaiting pairing"
2999		}
3000	} else if pid, alive, _ := telegram.IsRunning(i.cfg.ZotHome); alive && pid > 0 {
3001		msg = fmt.Sprintf("telegram: background daemon running (pid %d) - /telegram connect won't work until you stop it", pid)
3002	} else {
3003		cfg, _ := telegram.LoadConfig(i.cfg.ZotHome)
3004		if cfg.BotToken == "" {
3005			msg = "telegram: not configured. run `zot telegram-bot setup` first."
3006		} else {
3007			msg = "telegram: disconnected"
3008			if cfg.BotUsername != "" {
3009				msg += " (@" + cfg.BotUsername + " ready to connect)"
3010			}
3011		}
3012	}
3013	i.mu.Lock()
3014	i.statusOK = msg
3015	i.statusErr = ""
3016	i.mu.Unlock()
3017	i.invalidate()
3018}
3019
3020// telegramHost adapts *Interactive to telegram.Host so the bridge
3021// can call back into the TUI without importing modes directly.
3022type telegramHost struct{ iv *Interactive }
3023
3024func (h *telegramHost) SubmitOrQueue(prompt string, images []provider.ImageBlock) {
3025	h.iv.SubmitOrQueue(prompt, images)
3026}
3027
3028func (h *telegramHost) CancelTurn() { h.iv.CancelTurn() }
3029
3030func (h *telegramHost) Notify(level, message string) {
3031	h.iv.mu.Lock()
3032	switch level {
3033	case "error", "warn":
3034		h.iv.statusErr = message
3035		h.iv.statusOK = ""
3036	default:
3037		h.iv.statusOK = message
3038		h.iv.statusErr = ""
3039	}
3040	h.iv.mu.Unlock()
3041	h.iv.invalidate()
3042}
3043
3044// openSessionOpsDialog shows the picker for `/session` with no arg.
3045// Always offers export, import, fork, tree; the handlers bail with
3046// a clear status message when the precondition isn't met (empty
3047// transcript on fork; no parent/siblings on tree).
3048func (i *Interactive) openSessionOpsDialog() {
3049	items := []sessionOpsItem{
3050		{label: "export", action: "export", hint: "write the current session to a .zotsession file"},
3051		{label: "import", action: "import", hint: "load a .zotsession file into this directory"},
3052		{label: "fork", action: "fork", hint: "branch from a past user message into a new session"},
3053		{label: "tree", action: "tree", hint: "switch between branches in this directory"},
3054	}
3055	i.sessionOpsDialog.Open(items)
3056	i.invalidate()
3057}
3058
3059// doSessionOp dispatches export, import, fork, or tree. arg is the
3060// optional positional argument from e.g. /session export <path>
3061// or /session import <path>; fork and tree ignore it.
3062func (i *Interactive) doSessionOp(action, arg string) {
3063	switch action {
3064	case "export":
3065		i.doSessionExport(arg)
3066	case "import":
3067		i.doSessionImport(arg)
3068	case "fork":
3069		i.doSessionFork()
3070	case "tree":
3071		i.doSessionTree()
3072	default:
3073		i.mu.Lock()
3074		i.statusErr = "unknown /session action: " + action + " (use export, import, fork, or tree)"
3075		i.mu.Unlock()
3076		i.invalidate()
3077	}
3078}
3079
3080// doSessionExport writes the live session file to destination path
3081// dst. When dst is empty we default to ~/Downloads (falling back to
3082// the user's home directory if it doesn't exist). The helper
3083// expands a leading `~` and creates any missing parent directories.
3084func (i *Interactive) doSessionExport(dst string) {
3085	if i.cfg.CurrentSessionPath == nil {
3086		i.mu.Lock()
3087		i.statusErr = "export: no session is active (running with --no-session?)"
3088		i.mu.Unlock()
3089		i.invalidate()
3090		return
3091	}
3092	src := i.cfg.CurrentSessionPath()
3093	if src == "" {
3094		i.mu.Lock()
3095		i.statusErr = "export: no session is active (running with --no-session?)"
3096		i.mu.Unlock()
3097		i.invalidate()
3098		return
3099	}
3100	// Persist any in-memory agent messages to the session file so
3101	// the export carries the full conversation. Without this, the
3102	// default lazy-flush-at-exit strategy leaves most of a running
3103	// session unwritten and the export ends up with only the meta.
3104	if i.cfg.FlushSession != nil {
3105		i.cfg.FlushSession()
3106	}
3107	dst = unquotePath(dst)
3108	if dst == "" {
3109		dst = defaultExportDir()
3110	} else {
3111		dst = expandTilde(dst)
3112	}
3113	out, err := core.ExportSession(src, dst)
3114	if err != nil {
3115		i.mu.Lock()
3116		i.statusErr = "export: " + err.Error()
3117		i.mu.Unlock()
3118		i.invalidate()
3119		return
3120	}
3121	i.mu.Lock()
3122	i.statusOK = "exported session to " + friendlyPath(out)
3123	i.statusErr = ""
3124	i.mu.Unlock()
3125	i.invalidate()
3126}
3127
3128// doSessionImport copies the .zotsession file at src into the
3129// running cwd's sessions directory and loads it as the active
3130// session, same as `/sessions` -> pick. When src is empty we ask
3131// the user to pass a path (no usable default here).
3132func (i *Interactive) doSessionImport(src string) {
3133	src = unquotePath(src)
3134	if src == "" {
3135		i.mu.Lock()
3136		i.statusErr = "import: pass a path — e.g. /session import ~/Downloads/work.zotsession"
3137		i.mu.Unlock()
3138		i.invalidate()
3139		return
3140	}
3141	src = expandTilde(src)
3142	if _, err := os.Stat(src); err != nil {
3143		i.mu.Lock()
3144		i.statusErr = "import: " + err.Error()
3145		i.mu.Unlock()
3146		i.invalidate()
3147		return
3148	}
3149	newPath, err := core.ImportSession(src, i.cfg.ZotHome, i.cfg.CWD, i.cfg.Version)
3150	if err != nil {
3151		i.mu.Lock()
3152		i.statusErr = "import: " + err.Error()
3153		i.mu.Unlock()
3154		i.invalidate()
3155		return
3156	}
3157	if i.cfg.LoadSession == nil {
3158		i.mu.Lock()
3159		i.statusOK = "imported session at " + friendlyPath(newPath) + " (run /sessions to resume it)"
3160		i.statusErr = ""
3161		i.mu.Unlock()
3162		i.invalidate()
3163		return
3164	}
3165	if err := i.cfg.LoadSession(newPath); err != nil {
3166		i.mu.Lock()
3167		i.statusErr = "import: load failed: " + err.Error()
3168		i.mu.Unlock()
3169		i.invalidate()
3170		return
3171	}
3172	i.mu.Lock()
3173	i.statusOK = "imported and switched to session " + friendlyPath(newPath)
3174	i.statusErr = ""
3175	i.mu.Unlock()
3176	i.invalidate()
3177}
3178
3179// defaultExportDir returns ~/Downloads when it exists, or ~ as a
3180// fallback, or /tmp on exotic machines with no home dir.
3181func defaultExportDir() string {
3182	home, err := os.UserHomeDir()
3183	if err != nil || home == "" {
3184		return os.TempDir()
3185	}
3186	downloads := filepath.Join(home, "Downloads")
3187	if fi, err := os.Stat(downloads); err == nil && fi.IsDir() {
3188		return downloads
3189	}
3190	return home
3191}
3192
3193// expandTilde turns a leading ~ into the user's home directory.
3194// Returns the input unchanged when there's no tilde or no home.
3195func expandTilde(p string) string {
3196	if p == "" || p[0] != '~' {
3197		return p
3198	}
3199	home, err := os.UserHomeDir()
3200	if err != nil || home == "" {
3201		return p
3202	}
3203	if len(p) == 1 {
3204		return home
3205	}
3206	if p[1] == '/' || p[1] == filepath.Separator {
3207		return filepath.Join(home, p[2:])
3208	}
3209	return p
3210}
3211
3212// unquotePath strips a matching pair of surrounding single or
3213// double quotes. Drag-drop paste in the tui auto-quotes dropped
3214// file paths so the shell-like `/session import 'foo bar.zs'`
3215// stays well-formed; when the TUI's own slash handler consumes
3216// the arg, we want the raw path back.
3217func unquotePath(p string) string {
3218	p = strings.TrimSpace(p)
3219	if len(p) >= 2 {
3220		first := p[0]
3221		last := p[len(p)-1]
3222		if (first == '\'' && last == '\'') || (first == '"' && last == '"') {
3223			p = p[1 : len(p)-1]
3224		}
3225	}
3226	return p
3227}
3228
3229// friendlyPath collapses the user's home directory to a leading ~
3230// so status messages read cleanly. Falls back to the raw path when
3231// the home dir is unknown.
3232func friendlyPath(p string) string {
3233	home, err := os.UserHomeDir()
3234	if err != nil || home == "" {
3235		return p
3236	}
3237	if strings.HasPrefix(p, home+string(filepath.Separator)) {
3238		return "~" + p[len(home):]
3239	}
3240	return p
3241}
3242
3243// doSessionFork opens the /jump turn picker in "fork mode". The
3244// next selection branches the current session at that user turn
3245// instead of scrolling the viewport to it.
3246func (i *Interactive) doSessionFork() {
3247	if i.cfg.CurrentSessionPath == nil || i.cfg.CurrentSessionPath() == "" {
3248		i.mu.Lock()
3249		i.statusErr = "fork: no session is active (running with --no-session?)"
3250		i.mu.Unlock()
3251		i.invalidate()
3252		return
3253	}
3254	msgs := []provider.Message{}
3255	if i.agent != nil {
3256		msgs = i.agent.Messages()
3257	}
3258	if len(msgs) == 0 {
3259		i.mu.Lock()
3260		i.statusErr = "fork: transcript is empty; nothing to fork from"
3261		i.mu.Unlock()
3262		i.invalidate()
3263		return
3264	}
3265	i.pendingFork = true
3266	i.jumpDialog.Open(msgs, "")
3267	i.invalidate()
3268}
3269
3270// doSessionTree shows the branch topology picker for this cwd.
3271// Pick an entry to switch into it (same semantics as /sessions
3272// picking a past session, but with the parent/child indentation).
3273func (i *Interactive) doSessionTree() {
3274	if i.cfg.ZotHome == "" || i.cfg.CWD == "" {
3275		i.mu.Lock()
3276		i.statusErr = "tree: session storage not configured"
3277		i.mu.Unlock()
3278		i.invalidate()
3279		return
3280	}
3281	// Flush the running agent's transcript first so its message
3282	// count + latest preview are accurate in the tree.
3283	if i.cfg.FlushSession != nil {
3284		i.cfg.FlushSession()
3285	}
3286	roots := core.BuildSessionTree(i.cfg.ZotHome, i.cfg.CWD)
3287	if len(roots) == 0 {
3288		i.mu.Lock()
3289		i.statusErr = "tree: no sessions in this directory yet"
3290		i.mu.Unlock()
3291		i.invalidate()
3292		return
3293	}
3294	current := ""
3295	if i.cfg.CurrentSessionPath != nil {
3296		current = i.cfg.CurrentSessionPath()
3297	}
3298	if !i.sessionTreeDialog.Open(roots, current) {
3299		i.mu.Lock()
3300		i.statusErr = "tree: no branches to show"
3301		i.mu.Unlock()
3302	}
3303	i.invalidate()
3304}
3305
3306// applySessionTreeSelection switches the running agent to the
3307// session file at path. Thin wrapper around LoadSession that also
3308// writes a status line.
3309func (i *Interactive) applySessionTreeSelection(path string) {
3310	if i.cfg.LoadSession == nil {
3311		i.mu.Lock()
3312		i.statusErr = "tree: session swap not available in this build"
3313		i.mu.Unlock()
3314		i.invalidate()
3315		return
3316	}
3317	if err := i.cfg.LoadSession(path); err != nil {
3318		i.mu.Lock()
3319		i.statusErr = "tree: load failed: " + err.Error()
3320		i.mu.Unlock()
3321		i.invalidate()
3322		return
3323	}
3324	i.mu.Lock()
3325	i.statusOK = "switched to branch " + friendlyPath(path)
3326	i.statusErr = ""
3327	i.mu.Unlock()
3328	i.invalidate()
3329}
3330
3331// applyForkSelection branches the current session at msgIdx+1 (so
3332// the selected user message and everything before it is included
3333// in the new branch), then switches the running agent to the new
3334// file. Called from the jump-dialog handler when pendingFork=true.
3335func (i *Interactive) applyForkSelection(msgIdx int) {
3336	i.pendingFork = false
3337	if i.cfg.CurrentSessionPath == nil {
3338		i.mu.Lock()
3339		i.statusErr = "fork: no session is active"
3340		i.mu.Unlock()
3341		i.invalidate()
3342		return
3343	}
3344	src := i.cfg.CurrentSessionPath()
3345	if src == "" {
3346		i.mu.Lock()
3347		i.statusErr = "fork: no session is active"
3348		i.mu.Unlock()
3349		i.invalidate()
3350		return
3351	}
3352	if i.cfg.FlushSession != nil {
3353		i.cfg.FlushSession()
3354	}
3355	// msgIdx is 0-indexed message position; copy msgIdx+1 rows so
3356	// the selected user message is included.
3357	upTo := msgIdx + 1
3358	newPath, err := core.BranchSession(src, i.cfg.ZotHome, i.cfg.CWD, i.cfg.Version, upTo)
3359	if err != nil {
3360		i.mu.Lock()
3361		i.statusErr = "fork: " + err.Error()
3362		i.mu.Unlock()
3363		i.invalidate()
3364		return
3365	}
3366	if i.cfg.LoadSession == nil {
3367		i.mu.Lock()
3368		i.statusOK = "forked at message " + formatInt(upTo) + " (run /sessions to resume)"
3369		i.statusErr = ""
3370		i.mu.Unlock()
3371		i.invalidate()
3372		return
3373	}
3374	if err := i.cfg.LoadSession(newPath); err != nil {
3375		i.mu.Lock()
3376		i.statusErr = "fork: switch failed: " + err.Error()
3377		i.mu.Unlock()
3378		i.invalidate()
3379		return
3380	}
3381	i.mu.Lock()
3382	i.statusOK = "forked and switched to new branch at " + friendlyPath(newPath)
3383	i.statusErr = ""
3384	i.mu.Unlock()
3385	i.invalidate()
3386}
3387
3388// formatInt is a tiny strconv.Itoa shim; keeps the handler above
3389// from needing a strconv import just for one call.
3390func formatInt(n int) string {
3391	return fmt.Sprintf("%d", n)
3392}
3393
3394// assistantText returns the concatenated text of every TextBlock in
3395// m. Used by the streaming-view dedupe guard to tell when a live
3396// streamed reply has already been promoted into the transcript.
3397func assistantText(m provider.Message) string {
3398	var sb strings.Builder
3399	for _, c := range m.Content {
3400		if tb, ok := c.(provider.TextBlock); ok {
3401			if sb.Len() > 0 {
3402				sb.WriteByte('\n')
3403			}
3404			sb.WriteString(tb.Text)
3405		}
3406	}
3407	return sb.String()
3408}
3409
3410// resetStreamingStateLocked clears every piece of streaming state
3411// in one shot. Used by abort paths (turn cancel, compact finish,
3412// queue drain) so the pacer doesn't keep draining stale runes from
3413// a prior turn. Must be called with i.mu held.
3414func (i *Interactive) resetStreamingStateLocked() {
3415	i.streaming.Reset()
3416	i.streamPending = i.streamPending[:0]
3417	i.streamFlushPending = false
3418	i.streamOn = false
3419}
3420
3421// assistantMessageSideEffects runs the non-visual hooks attached to
3422// EvAssistantMessage: the host-provided OnAssistant callback and the
3423// telegram-bridge mirror. Called with i.mu held.
3424//
3425// Factored out of handleEvent because the streaming pacer may defer
3426// visual reset until after the last buffered rune has painted, but
3427// the callbacks themselves must fire on message arrival so
3428// downstream observers (session persistence, telegram, cost panels)
3429// don't wait on a UI animation to catch up.
3430func (i *Interactive) assistantMessageSideEffects(m provider.Message) {
3431	if i.cfg.OnAssistant != nil {
3432		i.cfg.OnAssistant(m)
3433	}
3434	if i.telegramBridge != nil && i.telegramBridge.Active() {
3435		var sb strings.Builder
3436		for _, c := range m.Content {
3437			if tb, ok := c.(provider.TextBlock); ok {
3438				if sb.Len() > 0 {
3439					sb.WriteString("\n")
3440				}
3441				sb.WriteString(tb.Text)
3442			}
3443		}
3444		if text := sb.String(); strings.TrimSpace(text) != "" {
3445			go i.telegramBridge.OnAssistantText(text)
3446		}
3447	}
3448}
3449
3450// paintPaceRate is how many runes the streaming pacer releases per
3451// tick. With a 16ms tick, 6 runes/tick is ~375 runes/s — fast enough
3452// that a 500-rune summary finishes in ~1.3s, slow enough to look
3453// like a human typing. Empirically matches the feel of provider
3454// paths that already drip-stream natively.
3455const paintPaceRate = 6
3456
3457// paintPaceInterval is the tick interval for the streaming pacer.
3458// 16ms lines up with the redraw throttle so we never paint faster
3459// than the terminal can keep up.
3460const paintPaceInterval = 16 * time.Millisecond
3461
3462// runStreamPacer drains buffered deltas from streamPending into
3463// streaming a small batch per tick, invalidating after each move.
3464// It stops when the context cancels (tui shutdown).
3465//
3466// Why a pacer: providers differ wildly in how they chunk their
3467// text_delta events. The API-key path on Anthropic emits ~30 drips
3468// for a 400-token summary; the OAuth path can coalesce the same
3469// summary into 3 fat chunks, visually indistinguishable from "the
3470// whole reply just appeared". The pacer normalizes that so every
3471// path looks the same on screen.
3472func (i *Interactive) runStreamPacer(ctx context.Context) {
3473	t := time.NewTicker(paintPaceInterval)
3474	defer t.Stop()
3475	for {
3476		select {
3477		case <-ctx.Done():
3478			return
3479		case <-t.C:
3480			i.mu.Lock()
3481			if len(i.streamPending) == 0 {
3482				// EvAssistantMessage already fired but the pacer
3483				// was still draining a tick ago. Everything is now
3484				// painted; clear the streaming flags so the next
3485				// redraw shows the finalised transcript message
3486				// and hides the streaming overlay.
3487				if i.streamFlushPending {
3488					i.streamFlushPending = false
3489					i.streaming.Reset()
3490					i.streamOn = false
3491					i.mu.Unlock()
3492					i.invalidate()
3493					continue
3494				}
3495				i.mu.Unlock()
3496				continue
3497			}
3498			n := paintPaceRate
3499			if n > len(i.streamPending) {
3500				n = len(i.streamPending)
3501			}
3502			i.streaming.WriteString(string(i.streamPending[:n]))
3503			i.streamPending = i.streamPending[n:]
3504			i.mu.Unlock()
3505			i.invalidate()
3506		}
3507	}
3508}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close