v0.1.42 42173ed

interactive.go RawHistoryFolder

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

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