v0.0.66 b29c6e7

interactive.go RawHistoryFolder

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

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