v0.1.34 cead9fd

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

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 477

↑↓ moveenter openesc close