v0.0.64 676b5d7

interactive.go RawHistoryFolder

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

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