v0.1.36 38717f5

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

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