v0.1.47 5a64f87

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

Keyboard shortcuts

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

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

Branches 1

Tags 477

↑↓ moveenter openesc close