v0.0.82 6019404

interactive.go RawHistoryFolder

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

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