v0.1.46 6ba41f2

interactive.go RawHistoryFolder

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

Keyboard shortcuts

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

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

Branches 1

Tags 476

↑↓ moveenter openesc close