v0.1.35 0a670c0

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

Keyboard shortcuts

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

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

Branches 1

Tags 476

↑↓ moveenter openesc close