v0.0.86 43aca0b

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

Keyboard shortcuts

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

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

Branches 1

Tags 477

↑↓ moveenter openesc close