v0.1.31 853a089

interactive.go RawHistoryFolder

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

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