v0.1.10 8a38171

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

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