v0.1.48 2eab133

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

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