v0.19.0 d7aa01a

interactive.go RawHistoryFolder

1package modes
2
3import (
4	"context"
5	"encoding/json"
6	"fmt"
7	"strings"
8	"sync"
9	"sync/atomic"
10	"time"
11
12	"github.com/bnema/zut/packages/agent/extensions"
13	"github.com/bnema/zut/packages/agent/extproto"
14	"github.com/bnema/zut/packages/agent/internal/orchestration"
15	"github.com/bnema/zut/packages/agent/modes/telegram"
16	"github.com/bnema/zut/packages/agent/skills"
17	"github.com/bnema/zut/packages/agent/subagents"
18	"github.com/bnema/zut/packages/agent/tools"
19	"github.com/bnema/zut/packages/core"
20	"github.com/bnema/zut/packages/provider"
21	"github.com/bnema/zut/packages/provider/auth"
22	"github.com/bnema/zut/packages/tui"
23)
24
25// InteractiveConfig configures the interactive loop.
26type InteractiveConfig struct {
27	Terminal        tui.Terminal
28	Theme           tui.Theme
29	Model           string
30	Provider        string
31	AuthMethod      string // "apikey" | "oauth" — used to tag cost as (sub) in status bar
32	BaseURL         string
33	Reasoning       string
34	SystemPrompt    string
35	WritingGuidance string
36	Tools           core.Registry
37	MaxSteps        int
38	CWD             string
39
40	// Startup resource fields are loaded inputs available to list before the
41	// transcript. They are never sent to the provider or persisted by the view.
42	StartupAgentName      string
43	StartupContextPaths   []string
44	StartupExtensionNames []string
45	StartupSkillNames     []string
46
47	// StartupExtensionErrors are non-fatal extension load failures collected
48	// before the TUI starts. They are display-only and never enter the transcript.
49	StartupExtensionErrors []string
50
51	// ShowInstructionsAtStartup controls whether startup resources are visible.
52	// nil means the default, off.
53	ShowInstructionsAtStartup *bool
54
55	// InlineImagesEnabled overrides terminal image rendering. nil means
56	// auto-detect and render when supported; false disables; true uses
57	// the detected protocol when available.
58	InlineImagesEnabled *bool
59
60	// TerminalAlertsEnabled controls interactive alerts from the main
61	// agent and extensions. nil means enabled; false disables them.
62	TerminalAlertsEnabled *bool
63
64	// TerminalTitleEnabled controls the hidden title request and terminal
65	// title updates. nil means enabled; false disables both.
66	TerminalTitleEnabled *bool
67
68	// AutoSubagentsEnabled mirrors the persisted config flag at startup so
69	// the /settings dialog can render the current state without
70	// re-reading config.json on every open.
71	AutoSubagentsEnabled *bool
72
73	// PonytailEnabled mirrors the persisted default-on coding-guidance
74	// setting at startup. nil/missing means enabled.
75	PonytailEnabled *bool
76
77	// WebSearchEnabled mirrors the persisted default-on web-search setting.
78	// nil/missing means enabled for normal interactive sessions.
79	WebSearchEnabled *bool
80
81	// WebSearchToolAllowed is the immutable invocation-level capability ceiling.
82	// false means --no-tools, --tools, or a packaged PermissionSet excludes it.
83	WebSearchToolAllowed *bool
84
85	// WebSearchInvocationOverride is true when an explicit --tools list includes
86	// web_search. That invocation-level opt-in takes precedence over the
87	// persisted setting, so the settings row is informational for this session.
88	WebSearchInvocationOverride bool
89
90	// AutoSubagentsToolAllowed is nil for normal sessions and false when the
91	// launch-time --no-tools/--tools policy excludes subagent spawning.
92	AutoSubagentsToolAllowed *bool
93
94	// AutoSubagentsStatusToolAllowed is nil for normal sessions and false when
95	// the launch-time --no-tools/--tools policy excludes status queries.
96	AutoSubagentsStatusToolAllowed *bool
97
98	// AutoSubagentsStopToolAllowed and AutoSubagentsResumeToolAllowed are nil
99	// for normal sessions and false when the launch-time tool policy excludes
100	// manager lifecycle actions.
101	AutoSubagentsStopToolAllowed   *bool
102	AutoSubagentsResumeToolAllowed *bool
103
104	// FastMode mirrors the persisted OpenAI fast-mode flag at startup.
105	// nil/missing means disabled. Unsupported providers reject attempts
106	// to enable it and reject requests when it remains enabled.
107	FastMode *bool
108
109	// LSPEnabled controls the main session's built-in lsp tool. nil means
110	// enabled by default.
111	LSPEnabled *bool
112
113	// SubagentLSPEnabled controls whether newly spawned subagent children
114	// receive the lsp tool. nil means enabled by default.
115	SubagentLSPEnabled *bool
116
117	// AutoCompactThreshold is the context-window percentage that triggers
118	// automatic compaction. nil means 85; zero disables percentage-based
119	// triggers while preserving payload-too-large recovery.
120	AutoCompactThreshold *int
121
122	// JailByDefault mirrors the persisted jail_by_default preference.
123	// The current sandbox may differ after a session-scoped /jail or /unjail.
124	JailByDefault *bool
125
126	// RecursiveFileSuggest mirrors the persisted recursive_file_suggest
127	// flag at startup. When true the @-mention picker fuzzy-searches the
128	// whole project tree instead of browsing one directory at a time.
129	RecursiveFileSuggest *bool
130
131	// RespectGitignore mirrors the persisted respect_gitignore flag at
132	// startup. nil means the default (on); when false the @-mention
133	// picker shows files matched by the project's root .gitignore.
134	RespectGitignore *bool
135
136	// ThemeName mirrors the persisted config theme value. Empty means auto.
137	ThemeName string
138
139	// FlatTools renders tool calls without the bordered panel (a quiet
140	// header line plus indented, frameless output). Mirrors the
141	// resolved tool_render config / ZUT_FLAT_TOOLS env at startup.
142	FlatTools bool
143
144	// CompactUser renders sent user messages as a single quiet gutter
145	// line instead of a padded, tinted bubble. Mirrors the resolved
146	// compact_input config / ZUT_COMPACT_INPUT env at startup.
147	CompactUser bool
148
149	// CompactMode mirrors the persisted compact_mode flag at startup.
150	// When true, it enables both flat tool calls and compact user turns.
151	CompactMode *bool
152
153	// TUIInputStyle controls the main input rendering: plain or lines.
154	TUIInputStyle string
155
156	// TUIStatusPosition controls whether the status block renders above
157	// or below the main input.
158	TUIStatusPosition string
159
160	// TUIWorkingPosition controls whether the busy/working spinner renders
161	// above or below the main input.
162	TUIWorkingPosition string
163
164	// QuickModelShortcuts maps slots 1-9 to provider/model pairs. The
165	// shortcuts are Ctrl+1..9. Cmd+1..9 may also work when the terminal
166	// forwards Command/Super keypresses, but Ctrl is the displayed chord.
167	QuickModelShortcuts []QuickModelShortcut
168
169	// ExtensionThemes returns themes bundled with loaded extensions.
170	ExtensionThemes func() []tui.ThemeOption
171
172	// AutoSubagentsSystemAddendum is the strict orchestrator block that gets
173	// appended when the user enables auto-subagents at runtime. Plumbed in from
174	// the cli so this package doesn't have to import agent (cycle).
175	AutoSubagentsSystemAddendum string
176
177	// OnDemandSubagentsSystemAddendum limits delegation to explicit user
178	// requests while auto-subagents is disabled.
179	OnDemandSubagentsSystemAddendum string
180
181	// SubagentsSystemAddendum is the metadata-only [subagents_list]
182	// block available whenever the primary agent can spawn subagents.
183	SubagentsSystemAddendum string
184	SettingsStore           SettingsStore
185
186	// Agent is optional. If nil, zut opens without credentials; the
187	// user must /login before they can prompt.
188	Agent *core.Agent
189
190	// InitialCompactHandoff is the opaque, persisted handoff snapshot for a
191	// resumed interactive session. Invalid data is ignored by this package.
192	InitialCompactHandoff json.RawMessage
193	// PersistCompactHandoff records the current opaque handoff snapshot in the
194	// active session. It must not re-enter Interactive.
195	PersistCompactHandoff func(json.RawMessage) error
196	// CurrentCompactHandoff returns the opaque handoff snapshot for the session
197	// currently owned by the host after a session switch. Invalid data is ignored.
198	CurrentCompactHandoff func() json.RawMessage
199
200	InitialInput string
201
202	// StartupPre is auto-submitted once when the interactive session
203	// opens, before InitialInput is applied. Uses the same path as a
204	// typed Enter submit ("!" → shell escape, otherwise a model turn).
205	StartupPre string
206
207	// OnStartupPreDone runs after StartupPre finishes (shell escape or
208	// model turn), before deferred InitialInput is applied. Hosts use
209	// it to rediscover skills / reload extensions installed by pre.
210	OnStartupPreDone func()
211
212	// RefreshTools re-resolves the live agent registry after a setting
213	// changes the main session's tool availability. Optional for embedders.
214	RefreshTools func() error
215
216	// SetWebSearchAvailable updates session-wide execution and generic-child
217	// ceilings after a live registry commit or fail-closed revocation. It can
218	// run while agentMu and i.mu are held, so callbacks must not re-enter
219	// Interactive or wait on either lock. The CLI callback only updates its
220	// web-search guard and resident child policy.
221	SetWebSearchAvailable func(bool)
222
223	// RefreshPrompt re-resolves the complete live prompt and tool registry
224	// after a prompt-affecting setting changes. Optional for embedders.
225	RefreshPrompt func() error
226
227	// AutoSubmitInitial, when true, auto-submits InitialInput after
228	// StartupPre completes (or immediately when StartupPre is empty).
229	// When false, InitialInput only pre-fills the editor.
230	AutoSubmitInitial bool
231
232	// Auth is required. When the user runs /login, Interactive talks to
233	// AuthManager to open a browser and wait for the callback.
234	AuthManager *auth.Manager
235
236	// LlamaCPPConfig resolves the router URL and optional API key from env or
237	// the credential saved by /login.
238	LlamaCPPConfig func() (baseURL, apiKey string, err error)
239
240	// RefreshLlamaCPPModels synchronizes currently loaded router models into
241	// the catalog before /model opens.
242	RefreshLlamaCPPModels func(context.Context) error
243
244	// BuildAgent is called after a successful login to (re)construct the
245	// agent with the fresh credential. It returns the new agent and
246	// the concrete provider/model in use.
247	BuildAgent func() (*core.Agent, string, string, error)
248
249	// SetKimiCLIFallbackDisabled controls whether zut may fall back to
250	// the official Kimi Code CLI token when zut has no stored Kimi token.
251	SetKimiCLIFallbackDisabled func(disabled bool) error
252
253	// BuildAgentFor rebuilds the agent with an explicit provider/model
254	// override (used by the /model picker when switching providers).
255	// If providerOverride is empty, the current provider is kept.
256	BuildAgentFor func(providerOverride, modelOverride string) (*core.Agent, string, string, error)
257
258	// BuildAgentForRescue rebuilds the agent for the rescue picker that
259	// opens after a recoverable provider failure. Unlike BuildAgentFor,
260	// this builder drops launch-time --api-key and --base-url overrides
261	// because those are usually the reason rescue triggered. Re-resolves
262	// credentials from env vars / auth.json / provider defaults so the
263	// retry has a real chance of succeeding. Falls back to BuildAgentFor
264	// when nil so embedders that don't wire it keep working.
265	BuildAgentForRescue func(providerOverride, modelOverride string) (*core.Agent, string, string, error)
266
267	// LoggedInProviders returns the list of provider names that
268	// currently have credentials. Used by /model to filter the
269	// picker to only show reachable models.
270	LoggedInProviders func() []string
271
272	// ZutHome is zut's global state directory, used by authentication,
273	// themes, extensions, and other shared configuration.
274	ZutHome string
275
276	// SessionsRoot is the root passed to core session operations. It differs
277	// from ZutHome for Zutfile agents, whose sessions are isolated by agent
278	// name. Empty falls back to ZutHome for embedders and tests.
279	SessionsRoot string
280
281	// Version is the binary's current version (from main.version).
282	// Used only for display; the update check itself is done outside
283	// this package to avoid an import cycle.
284	Version string
285
286	// UpdateInfoChan is an optional channel that delivers the result
287	// of the github-release update check. Interactive reads at most
288	// one value, drops it if the check reported nothing, and otherwise
289	// surfaces a yellow "update available" banner at the top of the
290	// chat. Nil channel = no banner, no startup cost.
291	UpdateInfoChan <-chan UpdateInfo
292
293	// Sandbox is the shared sandbox pointer. Toggled by /jail and /unjail.
294	Sandbox *tools.Sandbox
295
296	// LoadSession swaps the current session for the one at path. The
297	// callback returns the new agent message slice so the TUI can invalidate.
298	LoadSession func(path string) error
299
300	// ChangeCWD switches the running zut session's working directory
301	// to path. The host closes the current session, rebuilds the
302	// agent so tools / AGENTS.md / sandbox bind to the new cwd, and
303	// opens a fresh session there. Returns an error if path doesn't
304	// exist, isn't a directory, or the host can't rebuild the agent.
305	//
306	// Optional: not wired by every embedder. When nil the hidden /cd
307	// command surfaces a clear error rather than no-oping.
308	ChangeCWD func(path string) error
309
310	// CurrentSessionPath returns the path of the live session file
311	// on disk (the one every AppendMessage writes to). Used by
312	// /session export so the exporter ships the exact bytes on
313	// disk. Returns an empty string when --no-session is set or
314	// no session is open.
315	CurrentSessionPath func() string
316
317	// FlushSession writes any in-memory agent messages to the
318	// session file that haven't been persisted yet. Called by
319	// /session export right before reading the file so the
320	// exported bytes reflect the full current conversation, not
321	// just the rows the agent happened to write synchronously.
322	// The default WriteNewTranscript-at-exit strategy means most
323	// of a running session lives only in memory until the tui
324	// closes; without a flush hook, /session export writes a
325	// file that only has the meta row.
326	FlushSession func()
327
328	// SessionTransition serializes a state-changing session/model
329	// operation with the host's session load. It is optional for embedders;
330	// the CLI uses it to prevent a slow provider rebuild from being replaced
331	// by a concurrent resume (or vice versa).
332	SessionTransition func(func())
333
334	// PersistModel is called whenever the user switches model or provider.
335	// It should update config.json and (if there's an active session)
336	// write a new meta row so resume picks up the same model.
337	PersistModel func(providerName, model string)
338	// OnReasoningChanged updates host-owned runtime defaults after the setting
339	// has been persisted successfully.
340	OnReasoningChanged func(level string)
341
342	// InitialSessionTitle is the persisted title of the session loaded before
343	// the TUI starts. It is shown in the terminal without another model call.
344	InitialSessionTitle string
345	// InitialSessionTitlePending is true for a newly forked branch that only
346	// contains its copied prefix. The copied user messages must not prevent a
347	// new title after the branch's first real prompt.
348	InitialSessionTitlePending bool
349
350	// CurrentSessionTitle returns the title of the session currently owned by
351	// the host. It is used after /sessions and import switches.
352	CurrentSessionTitle func() string
353	// CurrentSessionTitlePending reports whether the loaded session is a new
354	// branch that has not received a post-fork prompt yet.
355	CurrentSessionTitlePending func() bool
356
357	// PersistTitle stores an automatically generated title without adding a
358	// user or assistant message to the transcript. It returns persistence
359	// errors without affecting the main turn.
360	PersistTitle func(title string) error
361	// OnSessionTitleChanged updates host-side in-memory title bookkeeping
362	// after a manual rename has already been written to disk.
363	OnSessionTitleChanged func(title string)
364
365	// CurrentGoal and PersistGoal expose the autonomous goal attached to the
366	// current session. CurrentGoal must return a copy, not the live session
367	// pointer, so failed persistence cannot mutate in-memory state. The callbacks
368	// follow session switches without coupling the TUI to the session file owner.
369	CurrentGoal        func() *core.SessionGoal
370	CurrentGoalHistory func() []core.SessionGoal
371	EnsureMission      func(objective string) error
372	PersistGoal        func(goal *core.SessionGoal) error
373	// PersistGoalRuntime records execution bookkeeping without adding a mission
374	// transition to goal history.
375	PersistGoalRuntime func(goal *core.SessionGoal) error
376	// GoalMaxTokenBudget is optional. Nil means autonomous goals are unlimited.
377	GoalMaxTokenBudget *uint64
378
379	OnAssistant func(m provider.Message)
380
381	// Extensions, if non-nil, lets users invoke extension-registered
382	// slash commands. Commands declared by extensions are looked up
383	// AFTER the built-in catalog so a built-in name always wins.
384	Extensions *extensions.Manager
385
386	// ResidentManager owns the /subagents runtime and provides bounded journal
387	// pages plus live projections to the child-session UI.
388	ResidentManager *subagents.ResidentManager
389	// SpawnResident resolves the host's live registry/configuration and commits
390	// a new resident child. Keeping that construction callback in agent avoids
391	// leaking provider or credential assembly into modes.
392	SpawnResident     func(context.Context, tools.ResidentSpawnRequest) (string, error)
393	BuildResidentSpec func(context.Context, tools.ResidentSpawnRequest) (subagents.ResidentChildSpec, error)
394
395	// ResolveSubagent validates a named markdown profile for direct
396	// /subagents commands. Auto-subagents uses the equivalent callback on its
397	// tool; keeping this optional preserves lightweight embedders.
398	ResolveSubagent func(name string) (*subagents.Profile, error)
399
400	// SkillSnapshot, if non-nil, returns the current list of
401	// discovered SKILL.md files. Re-invoked each time /skills opens
402	// so the picker reflects edits made during the session.
403	SkillSnapshot func() []*skills.Skill
404
405	// ChangelogChan, if non-nil, delivers release-notes for the
406	// current binary version once at startup. Interactive opens a
407	// dismissible overlay when the channel produces a non-empty
408	// body. Receiver fires at most once.
409	ChangelogChan <-chan ChangelogPayload
410
411	// OnChangelogDismiss, if non-nil, is called once the user
412	// closes the changelog overlay. The cli wires this to a
413	// MarkChangelogShown call so the same version doesn't show
414	// again on the next launch.
415	OnChangelogDismiss func()
416
417	// NoYolo is true when --no-yolo was passed. Interactive opens
418	// a confirmation dialog before every tool call and blocks the
419	// tool until the user picks yes / always-this-tool /
420	// always-all / no. When false (default), tools run freely.
421	NoYolo bool
422
423	// ConfirmGate is the session-scoped gate wrapping this
424	// interactive's Confirmer. When non-nil, /yolo can call
425	// AllowAll() on it to disable confirmation for the rest of the
426	// session. When nil (yolo mode), /yolo reports that there's
427	// nothing to disable.
428	ConfirmGate *core.ConfirmGate
429}
430
431// ChangelogPayload mirrors agent.ChangelogInfo without the import
432// cycle. The cli builds one from the http response, the tui opens
433// the overlay when one arrives.
434type ChangelogPayload struct {
435	Version string
436	Body    string
437	URL     string
438}
439
440type modelRefreshResult struct{ err error }
441
442// Interactive is the TUI chat loop.
443type chatCacheKey struct {
444	cols                 int
445	agentRev             uint64
446	statusOK             string
447	statusErr            string
448	help                 string
449	extNotes             string
450	extStatuses          string
451	extWidgets           string
452	reloadErrors         string
453	updateAvailable      bool
454	updateCurrent        string
455	updateLatest         string
456	updateURL            string
457	welcomeShowVer       bool
458	expandAll            bool
459	tailLimit            int
460	renderedMessageCount int
461	viewCacheRev         uint64
462}
463
464// QuickModelShortcut is one configured quick model switch slot.
465type QuickModelShortcut struct {
466	Provider string
467	Model    string
468}
469
470type extensionStatus struct {
471	Level string
472	Text  string
473}
474
475type extensionWidget struct {
476	Position string
477	Title    string
478	Lines    []string
479}
480
481// SettingsStore persists user-toggleable settings surfaced by /settings.
482type SettingsStore interface {
483	SetQuickModelShortcut(slot int, providerName, model string) error
484	SetInlineImages(enabled bool) error
485	SetAutoSubagents(enabled bool) error
486	SetJailByDefault(enabled bool) error
487	SetRecursiveFileSuggest(enabled bool) error
488	SetRespectGitignore(enabled bool) error
489	SetCompactMode(enabled bool) error
490	SetTUIInputStyle(style string) error
491	SetTUIStatusPosition(position string) error
492	SetTUIWorkingPosition(position string) error
493	SetReasoning(level string) error
494	SetTheme(name string) error
495}
496
497type terminalAlertsSettingsStore interface {
498	SetTerminalAlertsEnabled(enabled bool) error
499}
500
501type terminalTitleSettingsStore interface {
502	SetTerminalTitleEnabled(enabled bool) error
503}
504
505type lspSettingsStore interface {
506	SetLSPEnabled(enabled bool) error
507	SetSubagentLSPEnabled(enabled bool) error
508}
509
510type showInstructionsSettingsStore interface {
511	SetShowInstructionsAtStartup(enabled bool) error
512}
513
514type autoCompactThresholdSettingsStore interface {
515	SetAutoCompactThreshold(percent int) error
516}
517
518type fastModeSettingsStore interface {
519	SetFastMode(enabled bool) error
520}
521
522type ponytailSettingsStore interface {
523	SetPonytailEnabled(enabled bool) error
524}
525
526type webSearchSettingsStore interface {
527	SetWebSearchEnabled(enabled bool) error
528}
529
530type compactContinuationOrigin uint8
531
532type compactContinuationRequest struct {
533	origin    compactContinuationOrigin
534	force     bool
535	lastStop  provider.StopReason
536	turnError error
537}
538
539const (
540	compactOriginManual compactContinuationOrigin = iota
541	compactOriginPreTurnThreshold
542	compactOriginAfterTurnThreshold
543	compactOriginRecovery
544)
545
546type compactContinuationReason uint8
547
548const (
549	compactContinuationNone compactContinuationReason = iota
550	compactContinuationStructuralTail
551	compactContinuationForcedLength
552	compactContinuationStatusRescue
553)
554
555const maxStatusRescueContinuations = 2
556
557const compactHandoffVersion = 1
558
559type compactContinuationState struct {
560	reason         compactContinuationReason
561	rescueAttempts int
562}
563
564type persistedCompactHandoff struct {
565	Version        int    `json:"version"`
566	Reason         string `json:"reason"`
567	RescueAttempts int    `json:"rescue_attempts,omitempty"`
568}
569
570func decodeCompactHandoff(raw json.RawMessage) compactContinuationState {
571	var persisted persistedCompactHandoff
572	if len(raw) == 0 || json.Unmarshal(raw, &persisted) != nil || persisted.Version != compactHandoffVersion {
573		return compactContinuationState{}
574	}
575	switch persisted.Reason {
576	case "structural_tail":
577		if persisted.RescueAttempts == 0 {
578			return compactContinuationState{reason: compactContinuationStructuralTail}
579		}
580	case "forced_length":
581		if persisted.RescueAttempts == 0 {
582			return compactContinuationState{reason: compactContinuationForcedLength}
583		}
584	case "status_rescue":
585		if persisted.RescueAttempts >= 1 && persisted.RescueAttempts <= maxStatusRescueContinuations {
586			return compactContinuationState{reason: compactContinuationStatusRescue, rescueAttempts: persisted.RescueAttempts}
587		}
588	}
589	return compactContinuationState{}
590}
591
592func encodeCompactHandoff(state compactContinuationState) json.RawMessage {
593	var reason string
594	switch state.reason {
595	case compactContinuationStructuralTail:
596		reason = "structural_tail"
597	case compactContinuationForcedLength:
598		reason = "forced_length"
599	case compactContinuationStatusRescue:
600		reason = "status_rescue"
601	default:
602		return nil
603	}
604	encoded, err := json.Marshal(persistedCompactHandoff{
605		Version:        compactHandoffVersion,
606		Reason:         reason,
607		RescueAttempts: state.rescueAttempts,
608	})
609	if err != nil {
610		return nil
611	}
612	return encoded
613}
614
615type Interactive struct {
616	cfg  InteractiveConfig
617	view *tui.View
618	ed   *tui.Editor
619	rend *tui.Renderer
620
621	mu    sync.Mutex
622	agent *core.Agent
623	// agentMu serializes live registry replacement with side-dialog
624	// snapshots, whose copied-agent constructor reads the registry field.
625	agentMu sync.Mutex
626	// webSearchPolicyGeneration invalidates a resolve that began before a
627	// session policy transition. The final registry commit compares its captured
628	// value while agentMu and mu serialize it with live-agent replacement.
629	webSearchPolicyGeneration atomic.Uint64
630	// managedAutoSubagentsAddenda records exact prompt blocks appended by
631	// auto-subagents. Disable only removes these owned occurrences, leaving
632	// identical text that came from the user's base prompt untouched.
633	managedAutoSubagentsAddenda []string
634	streaming                   strings.Builder // what's currently painted on screen
635	streamOn                    bool
636	pendingAlert                *extproto.AlertRequest
637
638	// streamPending is the runes buffered after each EvTextDelta that
639	// haven't yet been promoted into `streaming` for rendering. It
640	// exists because some provider paths (notably Anthropic via the
641	// oauth/subscription channel) coalesce the model's output into a
642	// few fat chunks instead of drip-streaming. Painting those fat
643	// chunks verbatim looks like the summary "just appears". The
644	// paintPace goroutine drains a handful of runes per tick from
645	// this buffer into `streaming`, giving every path the same
646	// typewriter feel regardless of upstream chunk size.
647	streamPending []rune
648	// streamFlushPending is set when EvAssistantMessage fires while
649	// streamPending still has unrendered runes. The ticker flushes
650	// them, then closes out the stream (clearing flags, resetting
651	// buffers) so the final paint matches the on-disk message.
652	streamFlushPending bool
653	toolCalls          map[string]*tui.ToolCallView
654	toolOrder          []string
655	// toolRenderRevision is monotonic for the lifetime of the interactive
656	// view. Per-call counters would let unrelated tools alias the same rendered
657	// cache frame when they reach the same local revision.
658	toolRenderRevision uint64
659	// toolGate records, per tool-call id, how many runes of paced
660	// assistant text must have drained into `streaming` before that
661	// tool block may appear. It exists to make stream ordering
662	// deterministic: a tool call can arrive from the provider while
663	// the prose that logically precedes it is still being typed out
664	// by the pacer. Without gating, the tool block would render
665	// immediately while the intro paragraph keeps filling in below
666	// it. We snapshot the total expected stream length (already
667	// streamed + still pending) at the moment the tool starts, and
668	// hold the block back until the pacer reaches it.
669	toolGate          map[string]int
670	statusErr         string
671	statusOK          string
672	goalStatus        core.GoalStatus
673	goalRun           *goalContinuationRun
674	reloadStatusSeq   uint64
675	extStatuses       map[string]map[string]extensionStatus
676	extWidgets        map[string]map[string]extensionWidget
677	rightBarHidden    bool     // session-only Ctrl+B toggle; zero value keeps the rail visible
678	liveBlock         []string // live streaming/tool progress rendered outside scrollback
679	helpBlock         []string // rendered above the chat when /help was typed
680	cumUsage          provider.Usage
681	lastCtxInput      int // input_tokens of the most recent turn — approximates current context size
682	busy              bool
683	ctrlCExit         bool
684	activity          agentActivity
685	pendingIdleWork   []func()
686	dirty             chan struct{}
687	renderScheduler   atomic.Pointer[latestFrameScheduler]
688	renderRevision    atomic.Uint64
689	renderOutsideLock bool
690	modelRefresh      chan modelRefreshResult
691	modelRefreshing   bool
692	startupPreDone    chan startupPreResult
693	cancelTurn        context.CancelFunc
694	scrollOffset      int // rows from the bottom; 0 = pinned to latest
695	prevScrollOffset  int // last value redraw snapped against; tracks intent
696
697	// prevChatLen and prevChatCols track the chat buffer's size at the
698	// last redraw so that when content grows below the user's viewport
699	// while they're scrolled up reading history, we can bump
700	// scrollOffset by exactly the growth and keep the visible content
701	// pinned. Without this, every streamed line shifts the visible
702	// window down through the buffer (because scrollOffset is measured
703	// from the bottom) and the user's reading position drifts upward
704	// and off the top.
705	prevChatLen     int
706	prevChatCols    int
707	prevChatRows    int
708	prevOverlayOpen bool
709	cursorDimmed    bool
710
711	// chatCache stores the built transcript/status-note rows for idle
712	// frames. Editor typing changes only the bottom input region, so
713	// reusing this cache avoids copying/walking/reassembling a long
714	// session on every keypress.
715	chatCache      []string
716	chatCacheKey   chatCacheKey
717	chatCacheValid bool
718
719	// stableChatCache contains only transcript/startup rows. Live streaming,
720	// tool overlays, and errors are appended separately so spinner/progress
721	// frames can reuse finalized chat while a turn is busy.
722	stableChatCache      []string
723	stableChatCacheKey   chatCacheKey
724	stableChatCacheValid bool
725
726	// Messages typed while a turn is in flight. Each is delivered as
727	// its own follow-up turn once the current one finishes. Rendered
728	// above the status bar as "sliding in: ..." chips.
729	queued []string
730
731	// runCtx is the top-level context passed to Run(). Follow-up turns
732	// drained from `queued` are started against this context so they
733	// survive past the ctx of the key event that enqueued them.
734	runCtx context.Context
735
736	// pendingPostCompactNote is a status_ok message to surface after
737	// a successful auto-compact pass triggered by a 413 or by the
738	// pre-turn fraction guard. Cleared by runCompact once shown.
739	pendingPostCompactNote string
740
741	// A pre-turn compaction must preserve the complete pending request,
742	// including images. Overflow recovery instead continues the user message
743	// already appended to the agent transcript, avoiding a duplicate message.
744	pendingCompactPrompt    string
745	pendingCompactImages    []provider.ImageBlock
746	hasPendingCompactPrompt bool
747	continueAfterCompact    bool
748
749	// compacting is true for both manual and automatic compaction. Prompts
750	// submitted while it is set stay in the host queue because Compact does
751	// not run the agent loop that drains the agent-owned queue.
752	compacting bool
753
754	// autoCompacting is true while a model-triggered compaction is in
755	// flight. Surfaced in the status bar so the user can tell a
756	// condense pass from a regular assistant turn.
757	autoCompacting bool
758
759	// compactContinuation records the private reason and bounded rescue
760	// budget for the live compaction handoff. It is never persisted or
761	// inferred from rendered transcript rows.
762	compactContinuation compactContinuationState
763
764	// updateInfo is the result of the async update check. Zero value
765	// while the check hasn't completed or nothing is available.
766	updateInfo UpdateInfo
767
768	dialog                  *loginDialog
769	modelDialog             *modelDialog
770	llamaDialog             *llamaDialog
771	rescueDialog            *rescueDialog
772	sessionDialog           *sessionDialog
773	residentSubagentsDialog *residentSubagentsDialog
774	residentChildSession    *residentChildSession
775	residentChildMouse      bool
776	jumpDialog              *jumpDialog
777	btwDialog               *btwDialog
778	skillsDialog            *skillsDialog
779	changelogDialog         *changelogDialog
780	confirmDialog           *confirmDialog
781	logoutDialog            *logoutDialog
782	telegramDialog          *telegramDialog
783	settingsDialog          *settingsDialog
784	floatingPane            tui.FloatingPane
785	quickModelAssign        int
786	telegramBridge          *telegram.Bridge
787	sessionOpsDialog        *sessionOpsDialog
788	sessionTreeDialog       *sessionTreeDialog
789	extPanel                *extPanelDialog
790	llamaConfigured         bool
791
792	// completionTracker collects resident child terminal turns for delivery to
793	// the parent orchestration wave.
794	// turnCoordinator seals worker waves at manager-turn boundaries and decides
795	// the next wake without relying on timing or polling.
796	completionTracker         *subagents.CompletionTracker
797	turnCoordinator           *orchestration.Coordinator
798	coordinatorWorkerIDs      map[string][]string
799	coordinatorWorkerSeq      uint64
800	completionDeliveryMu      sync.Mutex
801	completionDeliveryRunning bool
802	completionDeliveryRequest bool
803	completionDeliveryHolds   int
804
805	// pendingFork is true when the user ran /session fork: the next
806	// jump-picker selection should branch off that message instead
807	// of scrolling. Flag resets after the action fires or the dialog
808	// is dismissed, so repeated /jump calls don't turn into forks.
809	pendingFork       bool
810	suggest           *slashSuggester
811	fileSuggest       *fileSuggester
812	spin              *spinner
813	residentAnimating atomic.Bool
814
815	// parkedTurn is the 1-based turn number the viewport is currently
816	// scrolled to by /jump. 0 = not parked, showing the tail as usual.
817	// Rendered as a muted footer at the bottom of the chat so users
818	// don't forget they're looking at history.
819	parkedTurn  int
820	parkedTotal int
821
822	// inputHistoryIndex is -1 when not browsing history. When the
823	// editor is empty, Up/Down can walk previous user prompts without
824	// stealing normal vertical cursor movement in non-empty input.
825	inputHistoryIndex int
826
827	// lastCtrlC is when the user last pressed ctrl+c. The first press
828	// clears the editor / cancels a turn / shows a hint; a second press
829	// within ctrlCExitWindow exits. Mirrors the python-repl convention.
830	lastCtrlC time.Time
831
832	// doubleEscape tracks the optional bare-Escape session-tree gesture.
833	// clock is injectable so the gesture can be tested without sleeping.
834	doubleEscape doubleEscapeTracker
835	clock        func() time.Time
836
837	// welcomeStart is when the interactive run began. The welcome
838	// banner shows the binary version for welcomeVersionDuration
839	// after this point and reverts to plain text after.
840	welcomeStart time.Time
841
842	// interactiveStarted gates session-title generation so tests and
843	// embedders that call Submit before Run do not issue a hidden request.
844	interactiveStarted bool
845	// titleRealPromptSeen prevents a fresh session from generating more than
846	// one title. It is reset only when a fork or a new cwd starts a new branch.
847	titleRealPromptSeen    bool
848	titleGenerationStarted bool
849	firstRealPrompt        string
850	titleVersion           uint64
851	titleCancel            context.CancelFunc
852	sessionTitle           string
853
854	// extNotes are one-shot styled lines pushed by extensions via
855	// Notify / Display. They live above the editor (just below the
856	// transcript) until cleared by /clear or another reset.
857	extNotes []string
858
859	// reloadErrors are host-only extension reload failures. They stay in
860	// the scrolling chat until /clear without entering the agent transcript.
861	reloadErrors []string
862
863	// shellRunning is true while a !command is executing. It shares
864	// i.busy/i.cancelTurn so esc cancels it and no turn or other shell
865	// escape can start while one is in flight.
866	shellRunning bool
867	// shellLive is the accumulating stdout/stderr of the in-flight
868	// shell escape, updated via BashTool progress for live rendering.
869	shellLive string
870
871	// awaitingStartupPre is true while the zutfile entry.pre auto-submit
872	// is in flight. When it clears, deferredInitialInput is applied.
873	awaitingStartupPre   bool
874	deferredInitialInput string
875	autoSubmitDeferred   bool
876
877	// sessionLoading is true while a /sessions selection is being read
878	// on a background goroutine. Keeping this off the input goroutine
879	// lets ctrl+c/exit remain responsive for very large JSONL sessions.
880	sessionLoading bool
881
882	// sessionLoads carries per-entry results for the /sessions picker. The
883	// picker owns the load lifecycle; the interactive loop applies results so
884	// rendering never races with background file reads.
885	sessionLoads <-chan sessionLoadEvent
886
887	// sessionTreeLoads delivers asynchronously-read tree rows. Like the flat
888	// picker, the main loop is the sole owner of dialog mutation and rendering.
889	sessionTreeLoads <-chan sessionTreeLoadEvent
890
891	// pendingRescuePrompt / pendingRescueImages stash the prompt and
892	// images that should be re-run after the user picks a model in
893	// the rescue dialog. Cleared once applyRescueSelection consumes
894	// them (or when the dialog is dismissed via esc).
895	pendingRescuePrompt string
896	pendingRescueImages []provider.ImageBlock
897
898	clipboardImages []clipboardImageAttachment
899}
900
901// welcomeVersionDuration is how long the welcome banner shows the
902// version suffix before reverting to the plain headline. 1.5s is
903// enough to read at a glance and keeps the splash short.
904const welcomeVersionDuration = 1500 * time.Millisecond
905
906// initialResumeTailLimit caps how many messages from a freshly-resumed
907// transcript we render on the first paint. The full transcript is
908// still in memory; older messages are rendered (and their cached
909// lines kept for the lifetime of the View) as soon as the user
910// scrolls past the rendered tail. Picked to comfortably fill the
911// largest realistic terminal viewport while keeping first paint
912// snappy on multi-thousand-message sessions where markdown / syntax
913// highlighting dominates the redraw cost.
914const initialResumeTailLimit = 80
915
916// resumeTailExpandStep is how many additional messages the tail
917// limit grows by each time the user scrolls past the currently
918// rendered top. Pre-rendering this many messages on a single tick
919// keeps scroll-up smooth without falling back to a one-by-one
920// reveal that would feel jerky.
921const resumeTailExpandStep = 80
922
923type startupPreResult struct {
924	deferred   string
925	autoSubmit bool
926}
927
928// NewInteractive constructs an Interactive from cfg.
929func NewInteractive(cfg InteractiveConfig) *Interactive {
930	renderer := tui.NewRenderer(cfg.Terminal)
931	renderer.SetTheme(cfg.Theme)
932	startupAgentName := ""
933	startupContextPaths := []string(nil)
934	startupExtensionNames := []string(nil)
935	startupSkillNames := []string(nil)
936	initialGoalStatus := core.GoalStatus("")
937	if cfg.CurrentGoal != nil {
938		if goal := cfg.CurrentGoal(); goal != nil {
939			initialGoalStatus = goal.Status
940		}
941	}
942	if cfg.ShowInstructionsAtStartup != nil && *cfg.ShowInstructionsAtStartup {
943		startupAgentName = cfg.StartupAgentName
944		startupContextPaths = append(startupContextPaths, cfg.StartupContextPaths...)
945		startupExtensionNames = append(startupExtensionNames, cfg.StartupExtensionNames...)
946		startupSkillNames = append(startupSkillNames, cfg.StartupSkillNames...)
947	}
948	i := &Interactive{
949		cfg: cfg,
950		view: &tui.View{
951			Theme:                 cfg.Theme,
952			ImageProto:            effectiveImageProtocol(cfg.InlineImagesEnabled),
953			FlatTools:             cfg.FlatTools,
954			CompactUser:           cfg.CompactUser,
955			CompactMode:           cfg.CompactMode != nil && *cfg.CompactMode,
956			StartupAgentName:      startupAgentName,
957			StartupContextPaths:   startupContextPaths,
958			StartupExtensionNames: startupExtensionNames,
959			StartupSkillNames:     startupSkillNames,
960		},
961		// Prompt is the standard half-block accent bar used by chat
962		// speaker labels too, so the input gutter matches the rest
963		// of the UI.
964		ed:                      tui.NewEditor(cfg.Theme.AccentBar(cfg.Theme.Accent)),
965		rend:                    renderer,
966		toolCalls:               map[string]*tui.ToolCallView{},
967		toolGate:                map[string]int{},
968		dirty:                   make(chan struct{}, 8),
969		modelRefresh:            make(chan modelRefreshResult, 1),
970		startupPreDone:          make(chan startupPreResult, 1),
971		dialog:                  newLoginDialog(),
972		modelDialog:             newModelDialog(),
973		llamaDialog:             newLlamaDialog(),
974		rescueDialog:            newRescueDialog(),
975		sessionDialog:           newSessionDialog(),
976		residentSubagentsDialog: newResidentSubagentsDialog(),
977		jumpDialog:              newJumpDialog(),
978		btwDialog:               newBtwDialog(),
979		skillsDialog:            newSkillsDialog(),
980		changelogDialog:         newChangelogDialog(),
981		confirmDialog:           newConfirmDialog(),
982		logoutDialog:            newLogoutDialog(),
983		telegramDialog:          newTelegramDialog(),
984		settingsDialog:          newSettingsDialog(),
985		sessionOpsDialog:        newSessionOpsDialog(),
986		sessionTreeDialog:       newSessionTreeDialog(),
987		extPanel:                newExtPanelDialog(),
988		extStatuses:             map[string]map[string]extensionStatus{},
989		extWidgets:              map[string]map[string]extensionWidget{},
990		suggest:                 newSlashSuggester(),
991		fileSuggest:             newFileSuggester(),
992		spin:                    newSpinner(cfg.Theme),
993		inputHistoryIndex:       -1,
994		clock:                   time.Now,
995		goalStatus:              initialGoalStatus,
996		reloadErrors:            append([]string(nil), cfg.StartupExtensionErrors...),
997		compactContinuation:     decodeCompactHandoff(cfg.InitialCompactHandoff),
998	}
999	i.btwDialog.setCloseHook(func() {
1000		i.confirmDialog.CancelChildConfirmations("side chat closed")
1001	})
1002	i.fileSuggest.SetRecursive(cfg.RecursiveFileSuggest != nil && *cfg.RecursiveFileSuggest)
1003	i.fileSuggest.SetRespectGitignore(cfg.RespectGitignore == nil || *cfg.RespectGitignore)
1004	if cfg.LlamaCPPConfig != nil {
1005		baseURL, _, err := cfg.LlamaCPPConfig()
1006		i.llamaConfigured = err == nil && baseURL != ""
1007	}
1008	i.managedAutoSubagentsAddenda = autoSubagentsAddenda(cfg, cfg.AutoSubagentsEnabled != nil && *cfg.AutoSubagentsEnabled)
1009	if cfg.ResidentManager != nil {
1010		// Resident updates arrive from the child control goroutine. The
1011		// renderer reads its immutable live projection on the next throttled
1012		// frame, so this callback must only request that frame.
1013		cfg.ResidentManager.SetUpdateObserver(func(string) { i.invalidate() })
1014		cfg.ResidentManager.SetHistoryUpdateObserver(func(childID string) {
1015			go i.reloadOpenResidentChildSession(childID)
1016		})
1017		cfg.ResidentManager.SetActivityObserver(func(active bool) {
1018			i.residentAnimating.Store(active)
1019		})
1020	}
1021	if cfg.Agent != nil {
1022		i.agent = cfg.Agent
1023		i.view.Messages = filterHiddenTranscriptMessages(cfg.Agent.Messages())
1024		i.cumUsage = cfg.Agent.Cost()
1025		// Rehydrate the "context used" gauge from the last persisted
1026		// turn. Without this the status bar reads 0.0% after a resume
1027		// until the next turn lands a usage event.
1028		if last := cfg.Agent.LastTurnUsage(); last.InputTokens > 0 || last.CacheReadTokens > 0 || last.CacheWriteTokens > 0 {
1029			i.lastCtxInput = last.InputTokens + last.CacheReadTokens + last.CacheWriteTokens
1030		}
1031		// Cap the first paint at the tail of the transcript so
1032		// resuming a multi-thousand-message session doesn't block
1033		// on rendering every prior turn before showing anything.
1034		if len(i.view.Messages) > initialResumeTailLimit {
1035			i.view.TailLimit = initialResumeTailLimit
1036		}
1037	}
1038	i.sessionTitle = core.NormalizeSessionTitle(cfg.InitialSessionTitle)
1039	if cfg.InitialSessionTitlePending {
1040		i.sessionTitle = ""
1041		i.titleRealPromptSeen = false
1042		i.titleGenerationStarted = false
1043	} else {
1044		i.titleRealPromptSeen = i.sessionTitle != "" || hasRealUserPrompt(i.view.Messages)
1045		i.titleGenerationStarted = i.titleRealPromptSeen
1046	}
1047	i.applyAutoSubagentsTool()
1048	i.recoverGoalRun()
1049	return i
1050}
1051
1052// ExitedViaCtrlC reports whether the last Run returned because the user
1053// deliberately exited with Ctrl+C.
1054func (i *Interactive) ExitedViaCtrlC() bool {
1055	i.mu.Lock()
1056	defer i.mu.Unlock()
1057	return i.ctrlCExit
1058}
1059
1060// markCtrlCExit records that the current Run is ending via Ctrl+C.
1061func (i *Interactive) markCtrlCExit() {
1062	i.mu.Lock()
1063	i.ctrlCExit = true
1064	i.mu.Unlock()
1065}
1066
1067// setResidentChildMouseReporting enables mouse reporting only while the
1068// transcript overlay owns scrolling. Normal chat keeps native terminal
1069// selection and wheel scrolling intact.
1070func (i *Interactive) setResidentChildMouseReporting(enabled bool) {
1071	i.mu.Lock()
1072	if i.residentChildMouse == enabled {
1073		i.mu.Unlock()
1074		return
1075	}
1076	i.residentChildMouse = enabled
1077	term, running := i.cfg.Terminal, i.runCtx != nil
1078	i.mu.Unlock()
1079	if term == nil || !running {
1080		return
1081	}
1082	seq := tui.SeqMouseOff
1083	if enabled {
1084		seq = tui.SeqMouseOn
1085	}
1086	_, _ = term.Write([]byte(seq))
1087}
1088
1089// Run blocks until the user quits.
1090func (i *Interactive) Run(ctx context.Context) error {
1091	i.mu.Lock()
1092	i.runCtx = ctx
1093	i.mu.Unlock()
1094	term := i.cfg.Terminal
1095	restore, err := term.EnterRaw()
1096	if err != nil {
1097		return err
1098	}
1099	defer restore()
1100	i.markInteractiveStarted()
1101	defer i.cancelSessionTitle()
1102	defer i.sessionDialog.Close()
1103	defer func() {
1104		if i.telegramBridge != nil {
1105			i.telegramBridge.Stop()
1106		}
1107	}()
1108
1109	// Enabling mouse reporting steals click-drag selection from the
1110	// host terminal (VS Code, Ghostty, iTerm). The user prefers native
1111	// selection over the wheel-speed boost, so we no longer turn it
1112	// on automatically. Wheel events fall through to the terminal's
1113	// own scrollback handler.
1114	// Keep zut on the terminal's main screen. We intentionally do not
1115	// enter the alternate-screen buffer (CSI ?1049h). The renderer emits
1116	// chat as normal terminal flow/scrollback and redraws only the live
1117	// input/status block on normal typing.
1118	_, _ = term.Write([]byte(tui.SeqBracketedPasteOn + tui.SeqEnhancedKeyboardOn + tui.SeqResetScrollRegion + tui.SeqDeleteKittyImages + tui.SeqClearScreenNoHome + tui.SeqClearScrollback + tui.MoveTo(1, 1)))
1119	// Tell the terminal our working directory (OSC 7) so "new tab /
1120	// split here" opens in the launch cwd instead of inheriting a stale
1121	// directory from an extension subprocess (see issue #38). Harmless
1122	// on terminals that ignore it.
1123	if seq := tui.ReportCWD(i.cfg.CWD); seq != "" {
1124		_, _ = term.Write([]byte(seq))
1125	}
1126	// Erase the live frame and place the cursor deterministically before any
1127	// exit summary or shell prompt is written. Do not erase scrollback: users
1128	// should still be able to review the session after closing zut.
1129	defer term.Write([]byte(tui.SeqResetScrollRegion + tui.SeqDeleteKittyImages + tui.SeqMouseOff + tui.SeqEnhancedKeyboardOff + tui.SeqBracketedPasteOff + tui.ResetCursorColor() + tui.ResetCursorShape() + tui.SeqClearScreenNoHome + tui.MoveTo(1, 1) + tui.SeqShowCursor))
1130	i.applyInputCursorColor()
1131
1132	// Streaming pacer: drains buffered text deltas at a steady rate
1133	// so typewriter feel is identical across providers regardless of
1134	// upstream chunk size. Starts here so it lives for the whole
1135	// session and exits with ctx.
1136	go i.runStreamPacer(ctx)
1137
1138	cols, rows := term.Size()
1139	i.rend.Resize(cols, rows)
1140	renderScheduler := newLatestFrameScheduler()
1141	i.renderScheduler.Store(renderScheduler)
1142	go renderScheduler.run(func(req renderRequest) {
1143		c, r := term.Size()
1144		i.rend.Resize(c, r)
1145		if req.theme != nil {
1146			i.rend.SetTheme(*req.theme)
1147		}
1148		if req.clear {
1149			i.rend.Clear()
1150		}
1151		if req.invalidate {
1152			i.rend.Invalidate()
1153		}
1154		i.redraw()
1155	})
1156	defer renderScheduler.stop()
1157	term.OnResize(func() {
1158		// Resize and redraw share the renderer owner. The owner reads the
1159		// latest terminal size just before its next frame.
1160		i.renderRevision.Add(1)
1161		renderScheduler.request(false, false)
1162	})
1163
1164	if i.cfg.StartupPre != "" {
1165		i.deferredInitialInput = i.cfg.InitialInput
1166		i.autoSubmitDeferred = i.cfg.AutoSubmitInitial
1167		i.awaitingStartupPre = true
1168		i.Submit(i.cfg.StartupPre)
1169	} else if i.cfg.AutoSubmitInitial && i.cfg.InitialInput != "" {
1170		i.Submit(i.cfg.InitialInput)
1171	} else {
1172		if i.cfg.InitialInput != "" {
1173			i.ed.SetValue(i.cfg.InitialInput)
1174		}
1175		i.startRestoredCompactHandoff(ctx)
1176	}
1177
1178	// Stamp the welcome time and schedule a one-shot redraw at the
1179	// expiry so the version suffix disappears on its own even if the
1180	// user hasn't typed anything yet.
1181	i.welcomeStart = time.Now()
1182	time.AfterFunc(welcomeVersionDuration, i.invalidate)
1183
1184	// If the agent was constructed with a pre-loaded transcript
1185	// (--continue, --resume, --session) pin the viewport at the
1186	// bottom so the most recent reply (and any prompt the user just
1187	// typed) is fully visible. Earlier behaviour parked the view at
1188	// the last user turn, which could leave the latest message clipped
1189	// off the bottom of the page on long sessions.
1190	if i.agent != nil {
1191		if msgs := i.agent.Messages(); len(msgs) > 0 {
1192			i.scrollToBottom()
1193		}
1194	}
1195
1196	// No credential at startup? Auto-open the login dialog, and mark
1197	// the status line. The user can Esc out of the dialog if they
1198	// want to dismiss it (e.g. to check /help or /exit first).
1199	if i.agent == nil {
1200		i.statusErr = "not logged in. pick a login method below or press esc to dismiss."
1201		i.dialog.Open(i.cfg.ZutHome)
1202	}
1203
1204	// Input goroutine. Buffered generously so a drag-drop that the
1205	// terminal delivers as a burst of single-character key events
1206	// (no bracketed paste) can be drained in one main-loop pass
1207	// instead of triggering a redraw per character.
1208	keys := make(chan tui.Key, 256)
1209	go func() {
1210		reader := tui.NewReaderWithPeek(term.ReadByte, term.PeekByteTimeout)
1211		for {
1212			k, err := reader.Read()
1213			if err != nil {
1214				return
1215			}
1216			keys <- k
1217		}
1218	}()
1219
1220	// Subscribe to auth events.
1221	var authEvents <-chan auth.Event
1222	if i.cfg.AuthManager != nil {
1223		authEvents = i.cfg.AuthManager.Events()
1224	}
1225
1226	// Animation ticker: drives spinner and dialog-related redraws when
1227	// nothing else changed. 120ms is slow enough that highlighting a huge
1228	// transcript doesn't spin the cpu.
1229	tick := time.NewTicker(120 * time.Millisecond)
1230	defer tick.Stop()
1231
1232	// Redraw throttle: coalesce bursts of invalidate() calls so we paint
1233	// at most once every redrawMinInterval. Huge tool-result dumps can
1234	// fire hundreds of invalidations while the user is typing; without
1235	// this, the input goroutine never gets CPU and keystrokes lag.
1236	const redrawMinInterval = 16 * time.Millisecond
1237	var lastRedraw time.Time
1238	var pendingRedraw bool
1239	var pendingTimer *time.Timer
1240
1241	drainPending := func() {
1242		if pendingTimer != nil {
1243			pendingTimer.Stop()
1244			pendingTimer = nil
1245		}
1246		if pendingRedraw {
1247			pendingRedraw = false
1248			lastRedraw = time.Now()
1249			renderScheduler.request(false, false)
1250		}
1251	}
1252
1253	requestRedraw := func() {
1254		since := time.Since(lastRedraw)
1255		if since >= redrawMinInterval {
1256			// Redrawing right now subsumes any pending redraw, so clear
1257			// the throttle state. Without this, a pending flag stays
1258			// stuck at true and subsequent invalidate() calls within
1259			// redrawMinInterval get dropped — which is exactly how the
1260			// final "turn finished" frame went missing until the user
1261			// nudged the ui by typing or scrolling.
1262			if pendingTimer != nil {
1263				pendingTimer.Stop()
1264			}
1265			pendingRedraw = false
1266			lastRedraw = time.Now()
1267			renderScheduler.request(false, false)
1268			return
1269		}
1270		if pendingRedraw {
1271			return // already scheduled
1272		}
1273		pendingRedraw = true
1274		wait := redrawMinInterval - since
1275		if pendingTimer == nil {
1276			pendingTimer = time.AfterFunc(wait, func() {
1277				// Poke the dirty channel so the main loop wakes and
1278				// drains the pending redraw on its own goroutine. We
1279				// can't call drainPending here directly — it touches
1280				// closure state shared with the main loop.
1281				i.invalidate()
1282			})
1283		} else {
1284			pendingTimer.Reset(wait)
1285		}
1286	}
1287
1288	i.invalidate()
1289
1290	updates := i.cfg.UpdateInfoChan  // nil-safe; nil channel blocks forever in select
1291	changelog := i.cfg.ChangelogChan // single-shot, see case below
1292
1293	for {
1294		select {
1295		case <-ctx.Done():
1296			return ctx.Err()
1297		case k := <-keys:
1298			if done := i.handleKey(ctx, k); done {
1299				return nil
1300			}
1301			// Drain any keystrokes that arrived during this iteration.
1302			// VS Code (and other terminals that don't bracket drops as
1303			// paste) deliver a path one rune at a time — without this
1304			// loop the editor would render between every rune and a
1305			// long path on a heavy transcript would visibly type in.
1306		drain:
1307			for {
1308				select {
1309				case k2 := <-keys:
1310					if done := i.handleKey(ctx, k2); done {
1311						return nil
1312					}
1313				default:
1314					break drain
1315				}
1316			}
1317			i.invalidate()
1318		case ev := <-authEvents:
1319			i.handleAuthEvent(ev)
1320			i.invalidate()
1321		case result := <-i.modelRefresh:
1322			i.mu.Lock()
1323			i.modelRefreshing = false
1324			i.mu.Unlock()
1325			i.openModelPickerAfterRefresh(result.err)
1326			i.invalidate()
1327		case result := <-i.startupPreDone:
1328			i.applyStartupPreResult(result)
1329			i.invalidate()
1330		case info, ok := <-updates:
1331			if ok && info.Available {
1332				i.mu.Lock()
1333				i.updateInfo = info
1334				i.mu.Unlock()
1335				i.invalidate()
1336			}
1337			updates = nil // single-shot; subsequent iterations skip this case
1338		case cl, ok := <-changelog:
1339			if ok && cl.Body != "" {
1340				i.changelogDialog.Open(cl.Version, cl.URL, cl.Body)
1341				i.invalidate()
1342			}
1343			changelog = nil // single-shot
1344		case event, ok := <-i.sessionLoads:
1345			i.mu.Lock()
1346			if !ok {
1347				i.sessionLoads = nil
1348				i.sessionDialog.ApplyLoadClosed()
1349				i.mu.Unlock()
1350				i.invalidate()
1351				break
1352			}
1353			i.sessionDialog.ApplyLoad(event)
1354			i.mu.Unlock()
1355			i.invalidate()
1356		case event, ok := <-i.sessionTreeLoads:
1357			i.mu.Lock()
1358			if !ok {
1359				i.sessionTreeLoads = nil
1360				i.sessionTreeDialog.ApplyLoadClosed()
1361				i.mu.Unlock()
1362				i.invalidate()
1363				break
1364			}
1365			if err := i.sessionTreeDialog.ApplyLoad(event); err != nil {
1366				i.sessionTreeLoads = nil
1367				i.statusErr = "tree: no readable session family"
1368				i.statusOK = ""
1369			}
1370			i.mu.Unlock()
1371			i.invalidate()
1372		case <-i.dirty:
1373			requestRedraw()
1374		case <-tick.C:
1375			// Always drain a pending redraw on the tick. This is the
1376			// safety net that catches the case where the dirty channel
1377			// was saturated when the final "turn finished" invalidate
1378			// fired, or where the throttle scheduled a deferred redraw
1379			// and the AfterFunc-driven invalidate got dropped on a
1380			// full channel.
1381			drainPending()
1382			// Only force a periodic redraw when something is actually
1383			// animating (the main spinner during a busy turn, or the
1384			// btw side-chat spinner while it's awaiting a response).
1385			// Static pickers (model, completed session, jump, etc.) don't
1386			// need the tick and firing it cancels the terminal's cursor
1387			// blink inside dialogs that host their own editor (btw),
1388			// because each frame re-emits hide-cursor + show-cursor.
1389			// A session picker that is still loading is an exception so
1390			// its dialog-local spinner can advance.
1391			//
1392			i.mu.Lock()
1393			busy := i.busy
1394			sessionLoading := i.sessionDialog.Loading()
1395			i.mu.Unlock()
1396			if busy || sessionLoading || i.btwDialog.Loading() || i.residentAnimating.Load() {
1397				requestRedraw()
1398			}
1399		}
1400	}
1401}
1402
1403const maxExtensionWidgetRows = 12
1404const maxExtensionStatusRows = 6
1405
1406// maxNarrowExtensionChromeRows bounds right-bar widgets when they fall back
1407// above the input, leaving one row for the truncation marker.
1408const maxNarrowExtensionChromeRows = 6
1409
1410// sessionsRoot returns the session namespace for this run.
1411
1412// lastCols returns the current terminal width in columns.
1413
1414// chatPage returns the number of chat rows currently visible, used
1415// as the page size for PageUp/PageDown.
1416
1417// scrollBy adjusts the scroll offset. Positive = up (into history).
1418// Clearing the parked-turn label when we're back at the bottom means
1419// the "viewing turn N" footer goes away automatically as soon as you
1420// scroll back to the live tail.
1421
1422// anchorScrollOffset keeps the user's reading position pinned when the
1423// chat buffer grows/shrinks or the viewport height changes between two
1424// redraws while they're scrolled up.
1425//
1426// scrollOffset is measured from the bottom of the chat buffer, so the
1427// top visible row is start = chatLen - scrollOffset - chatRows. To hold
1428// `start` constant we adjust the offset by the buffer-length delta minus
1429// the viewport-height delta. The result is clamped to [0, newLen] so a
1430// shrinking buffer can't push it negative.
1431
1432// scrollToBottom pins the view to the latest content.
1433
1434// snapViewportStartToImageBlock treats inline images as atomic blocks for
1435// scrolling. Terminal image protocols draw from a single escape row into a
1436// separate graphics layer; the following blank rows are only zut's reserved
1437// footprint. If the viewport starts on one of those blank rows, there is no
1438// correct partial-image state to render. Snap back to the escape row instead
1439// so the image is either shown from its beginning or skipped entirely.
1440
1441const (
1442	hiddenOpenAIImageMirrorPrefix = "Tool output included the following image content:"
1443	autoCompactContinueMetaKey    = "auto_compact_continue"
1444	shellEscapeMetaKey            = "shell_escape"
1445)
1446
1447// isBoxBlankLine reports whether line is visually empty after
1448// stripping ANSI escape sequences, surrounding whitespace, and the
1449// vertical box edges drawn by the tool-box renderer. Used by
1450// clipBottomClippedImages so an image's reservation rows still count
1451// as blank when those rows are wrapped in "│  ...  │" inside a tool box.
1452
1453// stripANSIBytes removes ANSI CSI escape sequences (ESC '[' ... final
1454// byte) from s without pulling in the regexp package. Mirrors the
1455// internal helper in package tui; the duplicated copy avoids exporting
1456// it just for one caller.
1457
1458// truncateLine shortens s so it fits within n display cells, with an
1459// ellipsis if trimmed. Used by the "sliding in" chips so a pasted
1460// novel doesn't blow past the status line.
1461
1462// ctrlCExitWindow is how long after a ctrl+c press a *second* press
1463// will exit instead of just clearing input. Long enough to be
1464// deliberate (rules out accidental key chord), short enough that the
1465// hint stays meaningful.
1466const ctrlCExitWindow = 2 * time.Second
1467
1468// armCtrlCExit records the timestamp of the current ctrl+c so the next
1469// one within ctrlCExitWindow exits.
1470
1471// ctrlCExitArmed reports whether a previous ctrl+c was recent enough
1472// that another press should now exit.
1473
1474// clearFileSuggestQuery strips the filter the user typed after the
1475// last "@", leaving the bare "@" so the picker stays open. Called when
1476// navigating between directory levels (Right/Left): the filter applied
1477// to the level the user was on, not the one being entered, so carrying
1478// it forward would wrongly hide the new directory's contents.
1479
1480// setToolExpansion updates long tool result expansion and replays the
1481// transcript so already-emitted rows reflect the new state.
1482
1483// confirmChildActive reports whether an interaction opened from slash input
1484// currently owns the keyboard while a tool confirmation remains pending.
1485
1486// restoreConfirmFocus returns input to confirmation after slash input is
1487// cleared or a child interaction closes. A non-empty editor keeps command
1488// input focused, and an active child continues to own its keys.
1489
1490// invokeExtensionCommand fires an extension-registered slash command
1491// in a background goroutine, awaits the response, and applies the
1492// requested action (prompt / insert / display / noop). Errors and
1493// timeouts surface as a status_err line.
1494
1495// appendExtensionNote renders an extension-originated note in the
1496// chat. Levels: "info" (muted), "warn" (warning), "error" (error),
1497// "success" (tool/ok green).
1498
1499// HostHooks implementation for the extension manager. The manager
1500// holds an interface, not a concrete *Interactive, so these methods
1501// are the only thing the manager sees.
1502
1503// ApplySessionAgent swaps the live agent after a validated session resume.
1504// Unlike ApplyChangedCWD it does not mutate cwd-scoped resources or startup
1505// context; the session loader is changing the transcript/provider only.
1506
1507// SetSubagentSessionScope redraws after a host session transition. Resident
1508// children retain their explicit parent session in their durable journal.
1509
1510// ApplyChangedCWD is called by hosts after a successful /cd hook that do
1511// not provide startup context metadata.
1512
1513// ApplyChangedCWDWithStartupContext swaps a rebuilt agent and its display-only
1514// startup context into the running TUI after a successful /cd hook.
1515
1516// SubmitSlash runs text as a slash command in the TUI as if the user
1517// had typed it. text must start with '/' — callers that hand it
1518// plain prose silently get a no-op so a misbehaving extension can't
1519// run a stray prompt through this path. Read-only commands run in
1520// place; commands that would mutate the transcript or replace the
1521// agent cancel the active turn first via the same path the editor
1522// uses for typed slash commands.
1523
1524// SubmitOrQueue runs text immediately if the agent is idle, or
1525// appends it to the pending queue if a turn is already in flight.
1526// Used by the telegram bridge (and by the editor submit path) so
1527// both input sources share the same "queue behind an active turn"
1528// semantics. Images are ignored for now — only the text prompt is
1529// forwarded — because the queued-prompt path is text-only; a
1530// follow-up can expand the queue entry to carry images.
1531
1532// CancelTurn aborts the active turn if one is running. Used by the
1533// telegram bridge when the paired user sends /stop.
1534// ChangelogVersion returns the version string of the changelog
1535// currently shown (or last shown). Used by the dismiss callback
1536// to store the correct version for dev builds.
1537
1538// Insert places text at the cursor in the editor.
1539
1540// Display appends a styled note from extName to the chat without a
1541// model call.
1542
1543// ReportError surfaces a host-side error in the interactive status area.
1544
1545// SetStatus replaces one persistent status item owned by an extension.
1546
1547// SetWidget replaces one persistent widget owned by an extension.
1548
1549// ClearWidget removes one persistent widget owned by an extension.
1550
1551// ClearExtensionChrome removes every persistent UI item owned by an
1552// extension that has exited. This keeps crashes, disable/reload operations,
1553// and startup failures from leaving stale widgets beside the transcript.
1554
1555const modalBackdropDimPercent = 50
1556
1557// setInputCursorDimmed updates the terminal-owned cursor only when its layer
1558// changes. Reapplying cursor controls on every redraw can reset its blink
1559// timing before the terminal completes a normal blink cycle.
1560
1561// stripWebSearchTool removes the callable web_search entry from the live
1562// registry without asking the resolver to run again. It is the fail-closed
1563// fallback when persistence rollback fails after a refresh failure.
1564
1565// buildStudyPrompt returns the canned prompt the /study command
1566// submits to the agent.
1567//
1568// With no argument, /study targets the current directory — the
1569// historical behaviour. With an argument, /study targets that path
1570// instead; either a directory ("read every file in here") or a
1571// single file ("read this file"). The argument can be:
1572//
1573//   - a relative path (resolved against cwd)
1574//   - an absolute path
1575//   - an @-picker chip, which has already been expanded to an
1576//     absolute path by expandFileChips before runSlash sees it
1577//
1578// The path is stat'd to pick the right wording ("directory" vs
1579// "file"). If the path doesn't exist, we still build a sensible
1580// prompt rather than erroring — the agent will surface the
1581// missing-file failure itself when it tries to read it, which is
1582// more useful than a refusal here.
1583
1584// tryPathTabCompleteEditor looks at ed's current value, finds the
1585// path-like token immediately before the cursor (the cursor is always
1586// at the end of the buffer after a keystroke, so "before the cursor"
1587// is the trailing non-whitespace run), and rewrites it to its shell-
1588// style completion against the filesystem.
1589//
1590// Returns true when it consumed the Tab keystroke (token recognised,
1591// completion attempted — even if no candidates matched, the keystroke
1592// is still consumed so it doesn't insert a literal tab character).
1593// Returns false when the token doesn't look like a path; callers then
1594// let Tab fall through to its normal no-op.
1595//
1596// Recognised path shapes:
1597//   - ~ or ~/foo                  expanded via os.UserHomeDir()
1598//   - /abs/path or /abs/path/foo  absolute
1599//   - ./foo, ../foo, foo/bar      relative to cwd
1600//
1601// A bare word like "hello" is not treated as a path so plain text
1602// keeps Tab as a literal no-op.
1603//
1604// Free function (not a method) so the same logic runs against the
1605// editor instances owned by local dialogs without each
1606// dialog needing its own copy.
1607
1608// tryPathTabComplete is the Interactive-bound convenience wrapper.
1609// It calls the free helper against the main editor and invalidates
1610// the frame on a successful rewrite.
1611
1612// looksLikePathToken reports whether tok is shaped like a filesystem
1613// path. Paths must either start with ~, /, ./, ../ or contain a /.
1614// Plain words are excluded so Tab on "hello" stays a no-op.
1615
1616// resolvePathTabToken splits tok into (absolute parent dir, basename
1617// prefix to match, display-form parent the user typed). ok is false
1618// when the parent dir can't be resolved (e.g. ~ with no $HOME).
1619
1620// splitDirBase is like filepath.Split but preserves the trailing
1621// slash convention: "foo" => (".", "foo"); "foo/" => ("foo", "");
1622// "a/b" => ("a/", "b"); "/" => ("/", ""). Returned dir always has
1623// the trailing separator when non-empty so callers can rebuild paths
1624// by concatenation.
1625
1626// openLogoutDialog shows the provider picker for `/logout` with no
1627// argument. Only providers the user is currently logged into are
1628// listed, plus an "all" entry when more than one is present. If
1629// nothing's logged in, writes a status line instead of opening an
1630// empty dialog.
1631
1632// doLogout clears credentials for the given provider (or all providers)
1633// from auth.json. If the active agent was using those credentials, it
1634// is torn down so the user is forced through /login before their next
1635// prompt.
1636//
1637// target: "anthropic" | "openai" | "kimi" | "github-copilot" | "all"
1638
1639// applyModelSelection switches the active model (and provider, if the
1640// new model belongs to a different one). It rebuilds the underlying
1641// client when needed so the provider wire-protocol matches.
1642// cancelAndWaitForIdle cancels the active turn (if any) and blocks
1643// briefly until the turn goroutine has updated i.busy = false. Used
1644// before destructive slash commands so transcript-mutating work
1645// (/clear, /compact, /logout, /login completion, cross-provider
1646// /model swap) doesn't race with the still-running stream.
1647//
1648// The wait is bounded; if the turn doesn't release within the timeout
1649// we proceed anyway. Worst case is a brief overlap that the agent's
1650// own mutex protects against.
1651
1652// openBtwDialog opens the side-chat overlay with a frozen snapshot
1653// of the current main session. The optional argument is auto-
1654// submitted as the first question, so '/btw does X work?' fires the
1655// model call immediately instead of just opening an empty dialog.
1656
1657// submitOrQueuePrompt submits a slash command's expanded prompt immediately,
1658// or queues it behind the active turn using the normal text-only queue.
1659
1660// openSkillsDialog opens the skill inspector. The picker reflects
1661// whatever SkillSnapshot returns at call time, so edits to a
1662// SKILL.md made during a session show up on the next /skills.
1663
1664// openJumpDialog builds a /jump picker from the current transcript.
1665// If the user typed "/jump foo" with a filter and it matches exactly
1666// one turn, jump there directly without showing the dialog.
1667
1668// applyJumpSelection scrolls the chat viewport so the user message at
1669// msgIdx is visible at (or near) the top of the chat area. Uses the
1670// anchor slice returned by view.BuildWithAnchors so the mapping from
1671// message index to row is exact, regardless of variable-height tool
1672// blocks above the target.
1673
1674// totalTurnsLocked counts user messages in the transcript. Caller is
1675// assumed to hold i.mu (the name is a mild reminder; this function
1676// itself doesn't touch shared state beyond the slice it's handed).
1677
1678// applySessionSelection loads the given session via the cli-provided
1679// callback and snaps the viewport to the bottom (the latest message)
1680// so the user lands at the live tail of the resumed conversation.
1681
1682// applyRescueModelSelection is like applyModelSelection but routes
1683// through BuildAgentForRescue so launch-time --api-key / --base-url
1684// overrides are dropped before the new agent is built. Falls back to
1685// the regular builder when the host doesn't wire a rescue builder.
1686
1687// swapModel applies a /model selection (or a rescue selection) using
1688// the supplied builder. rescue=true tags the success message so the
1689// user can see that launch-time overrides were ignored.
1690
1691// clearPendingCompactTurnLocked drops work that only makes sense after the
1692// current compaction. The caller must hold i.mu.
1693
1694// compactHandoffLocked returns a self-contained persistence snapshot. The
1695// caller must hold i.mu.
1696
1697// setCompactContinuationLocked updates the private handoff state and returns
1698// its persistence snapshot plus whether persistence is needed. The caller must
1699// hold i.mu.
1700
1701// resetCompactContinuationLocked clears the private handoff state and returns
1702// its persistence snapshot plus whether persistence is needed. The caller must
1703// hold i.mu.
1704
1705// autoCompactContinuationPrompt is an interactive-only compact-handoff
1706// instruction. Its completion criteria must stay separate from Ponytail so
1707// toggling the optional coding-style addendum never changes recovery behavior.
1708const autoCompactContinuationPrompt = `Context was compacted while work was in progress. Continue the user's most recent active request now; do not wait for them to type "continue". Inspect the context summary and kept recent messages, treating active constraints and preferences there as still in force, including delegation/subagent instructions. If a newer request supersedes earlier plans in the summary, follow the newer request. A progress report, plan update, or statement of future work is not completion: if required work remains, take the next concrete action now. Only finish when the request is actually complete or when a specific user decision is required. If nothing remains, give a brief truthful completion; do not invent work or force a tool call.`
1709
1710type compactHandoffResume uint8
1711
1712const (
1713	compactHandoffDiscard compactHandoffResume = iota
1714	compactHandoffContinueExisting
1715	compactHandoffAppendPrompt
1716)
1717
1718// classifyCompactHandoffResume validates that the persisted checkpoint still
1719// describes the effective transcript. A normal assistant reply or a newer
1720// explicit user message supersedes the checkpoint; tool activity remains an
1721// unfinished existing turn. No hidden prompt means the process stopped after
1722// recording the handoff but before appending its context message.
1723
1724// startRestoredCompactHandoff resumes a handoff checkpoint restored from the
1725// active session. When its hidden context message was already persisted, the
1726// agent continues that existing turn rather than appending it again.
1727
1728// startAutoCompactContinuation adds an internal user turn that tells the
1729// model to resume the task after threshold compaction. Provider requests
1730// cannot continue from an assistant tail on every supported API, so the
1731// continuation must be represented as a user message. It is hidden from
1732// the rendered transcript but remains in the persisted/model context.
1733
1734// runCompact invokes core.Agent.Compact and reflects the progress in
1735// the tui. It runs in a goroutine so the ui stays responsive; esc/ctrl+c
1736// cancel via the same cancelTurn channel used for normal turns.
1737//
1738// When auto is true the spinner message is pinned to "condensing
1739// history" and the status bar surfaces "(auto)" next to the context
1740// percentage so it's obvious the system triggered this, not the user.
1741// request.force tells the post-compact hand-off to resume even if the
1742// transcript tail has visible assistant text, for example after StopLength.
1743
1744// shellEscapeCommand reports whether text is a "!command" shell
1745// escape and, if so, returns the command with the leading '!' (and
1746// surrounding whitespace) stripped. A bare "!" with no command is
1747// treated as not an escape so it falls through to the normal prompt
1748// path rather than running an empty shell.
1749
1750// ShellEscapeCommand reports whether text is a "!command" shell
1751// escape and, if so, returns the command with the leading '!' (and
1752// surrounding whitespace) stripped. A bare "!" with no command is
1753// treated as not an escape so it falls through to the normal prompt
1754// path rather than running an empty shell.
1755const ShellEscapeTimeoutSeconds = 600
1756
1757// startShellEscape runs a "!command" in the same shell the bash tool
1758// uses, in the session working directory, honoring the /jail sandbox.
1759// It shares the busy/cancel state with the agent: esc cancels it, and
1760// it refuses to start while a turn or another shell escape is already
1761// in flight. Its terminal-log output is appended to the transcript as
1762// user context without automatically starting a model turn.
1763
1764// startTurnRequest starts a new prompt or continues an existing user turn.
1765// continueExisting selects Agent.Continue so callers can retry a transcript
1766// message without appending it twice. overflowRecoveryAttempted suppresses
1767// the pre-turn threshold guard and the one-shot overflow recovery path; a
1768// normal post-compaction continuation leaves it false so a still-too-large
1769// rebuilt context can recover once more.
1770
1771// openRescueDialog surfaces the rescue model picker after a recoverable
1772// provider failure. The pending prompt + images are stashed on the
1773// Interactive so a later applyRescueSelection can re-run the same turn
1774// against the freshly-picked model. activeProvider/failedProvider are
1775// usually the same, but some clients embed different prefixes in their
1776// errors than the configured provider id, so we accept both.
1777
1778// applyRescueSelection switches model (cross-provider if needed) and
1779// re-runs the same prompt+images that just failed. Mirrors
1780// applyModelSelection's transcript-carry logic so the user keeps full
1781// session continuity across the swap.
1782
1783// autoCompactNoteLine returns a styled chat-area note for the
1784// inline auto-compact heads-up. Lives in extNotes so it survives
1785// the busy-spinner overwrite of the status row.
1786
1787// NormalizeAutoCompactThreshold applies the persisted auto-compaction
1788// setting's supported values and default. It is exported so non-interactive
1789// hosts can share the interactive mode's exact configuration semantics.
1790
1791// ShouldAutoCompact reports whether the latest request context reached the
1792// configured percentage of the model's advertised context window.
1793
1794// classifyCompactionContinuation chooses a private handoff reason from the
1795// successful turn tail. Structural unfinished-tail handling is independent of
1796// the status matcher. A status rescue is admitted only for an after-turn
1797// threshold compaction or an already-active status handoff, and only after a
1798// normal successful end.
1799
1800// structuralCompactionContinuation preserves the pre-existing unfinished-tail
1801// behavior without consulting the status matcher.
1802
1803// likelyForwardWorkStatus is deliberately narrow. It recognizes only clear
1804// first-person future-work commitments and never treats generic plan prose as
1805// a host control signal.
1806
1807// shouldAutoCompactLocked reports whether the last turn pushed context
1808// usage past the auto-compact threshold. Must be called with i.mu
1809// held; it reads lastCtxInput and the current model's context window.
1810
1811// WebSearchPolicyGeneration returns the generation a resolver must present at
1812// its final interactive commit. Policy transitions advance it before changing
1813// the gate or generic-child ceiling.
1814
1815// ApplyAgentPromptConfig commits a resolved prompt and tool registry only if
1816// ag is still the live interactive agent. Callers without a long-running
1817// resolve use the current policy generation.
1818
1819// ApplyAgentPromptConfigAtWebSearchGeneration additionally rejects a registry
1820// resolved before a web-search policy transition. This final check is made in
1821// the same critical section as live-agent replacement and the core prompt swap.
1822
1823// prepareReplacementAgentLocked applies session-wide capability policy before
1824// ag becomes visible to prompt submission. The caller holds agentMu and i.mu.
1825
1826// DeferUntilIdle runs work immediately when the interactive agent is idle,
1827// or after the current turn/compaction/shell operation releases the busy
1828// state. Callbacks run outside i.mu.
1829
1830// Agent returns the current agent, if any. Used by cli.go to flush the
1831// final transcript to the session file.
1832
1833// silence unused import in some build configs
1834var _ = fmt.Sprintf
1835
1836// runReloadExt triggers a live reload of every extension (discovered
1837// + explicit). Runs on a goroutine so the TUI stays responsive; the
1838// Manager.Reload takes a couple of hundred ms to shut down subprocs
1839// and respawn them. Shows a temporary status line throughout.
1840
1841// Confirm implements core.Confirmer. The agent goroutine calls
1842// this synchronously before every tool invocation when --no-yolo is
1843// active. We push the request onto the confirmDialog queue, trigger
1844// a redraw, and block the caller until the user answers.
1845//
1846// If the session is cancelled or the TUI exits mid-prompt, any
1847// pending request is refused via CancelAll so the agent doesn't
1848// deadlock.
1849
1850// ConfirmToolCall attaches a side-effect-free preview to the matching live
1851// tool panel, then blocks until the user approves or refuses the call.
1852
1853// openTelegramDialog shows the picker for `/telegram` with no arg.
1854// Items depend on current state: disconnect + status when running,
1855// connect + status when stopped.
1856
1857// telegramMenuItems builds the dialog entries for the current
1858// bridge state. Returns empty when no bot.json exists so the
1859// caller can show a helpful status line instead of an empty menu.
1860
1861// doTelegram dispatches one of the three explicit actions. Called
1862// from /telegram <action> or after the picker selects a row.
1863
1864// telegramConnect starts the bridge. Refuses if it's already
1865// running or if the on-disk bot.json is missing a token.
1866
1867// telegramDisconnect stops the bridge. No-op when already stopped.
1868
1869// refreshToolsAfterTelegram restores normal tools only through a successful
1870// resolver refresh. Failure removes Telegram-only tools but leaves web_search
1871// revoked in the live registry, stale snapshots, and generic-child policy.
1872
1873// telegramSenderAdapter wraps the bridge so the tools package can
1874// drive it without importing telegram directly. The Active() check
1875// is forwarded to the bridge so the tool can fail clearly with a
1876// model-readable error when the user disconnected mid-turn.
1877type telegramSenderAdapter struct {
1878	bridge *telegram.Bridge
1879}
1880
1881// TrackResidentSubagent reserves completion delivery after the manager has
1882// durably accepted a resident child prompt and before it is scheduled.
1883
1884// ReportResidentSubagent delivers a typed resident terminal outcome through
1885// the same coordinator path used by legacy worker completions.
1886
1887// registerCoordinatorWorker associates a tracker registration with the open
1888// manager wave. Direct embedders that register a worker outside startTurn get
1889// a one-worker sealed wave, retaining the exported tracker API's old behavior.
1890
1891// requestCompletionDelivery starts at most one waiter for the current active
1892// set. A request arriving while that waiter is formatting or submitting is
1893// picked up before the waiter exits, so a later worker cannot be lost in the
1894// handoff between batches.
1895
1896// beginCompletionDeliveryHold keeps all completions observed during one
1897// parent model turn together. Tool calls are executed sequentially inside the
1898// core agent, so the release point is the owning registration boundary for
1899// same-parent-turn batching rather than a timing-based debounce.
1900
1901// autoSubagentsAddenda returns the prompt blocks owned by subagent prompting,
1902// in the same order Resolve appends them to a new agent. The profile manifest
1903// is independent of strict orchestration and remains available in on-demand
1904// mode whenever the primary agent can spawn a worker.
1905
1906// removeLastAutoSubagentsAddendum removes one occurrence of a block known to
1907// have been appended by auto-subagents. Resolve appends owned blocks at the
1908// end, so removing the last occurrence preserves an identical base block.
1909
1910// applyAutoSubagentsSystemPrompt swaps the prompt blocks owned by subagent
1911// prompting on the running agent. Toggling strict orchestration changes the
1912// delegation guidance while retaining the profile manifest when usable.
1913
1914// applyAutoSubagentsTool registers the canonical subagent tools whenever
1915// launch-time policy permits them. Auto-subagents controls prompt behavior,
1916// while the tools remain available for explicit user-requested delegation.
1917// Mirrors applyTelegramTools' snapshot+mutate pattern so extension tools and
1918// /reload-ext additions survive a settings change.
1919
1920// applyTelegramTools registers (active=true) or removes (active=false)
1921// the telegram_send_image and telegram_send_file tools on the running
1922// agent so the model only sees them while the bridge is connected.
1923// Snapshots and mutates the live tool registry so any extension or
1924// /reload-ext additions made while Telegram is connected survive a
1925// later /telegram disconnect. The two Telegram entries are always replaced;
1926// web_search is additionally stripped only while the external bridge is active.
1927
1928// telegramStatus writes a one-liner describing the bridge state.
1929// Reports on both the in-tui bridge and the background daemon so
1930// the user isn't confused when the daemon owns the poll loop.
1931
1932// telegramHost adapts *Interactive to telegram.Host so the bridge
1933// can call back into the TUI without importing modes directly.
1934type telegramHost struct{ iv *Interactive }
1935
1936// openSessionOpsDialog shows the picker for `/session` with no arg.
1937// Always offers export, import, fork, tree; the handlers bail with
1938// a clear status message when the precondition isn't met (empty
1939// transcript on fork; no parent/siblings on tree).
1940
1941// doSessionOp dispatches export, import, fork, or tree. arg is the
1942// optional positional argument from e.g. /session export <path>
1943// or /session import <path>; fork and tree ignore it.
1944
1945// doSessionExport writes the live session file to destination path
1946// dst. When dst is empty we default to ~/Downloads (falling back to
1947// the user's home directory if it doesn't exist). The helper
1948// expands a leading `~` and creates any missing parent directories.
1949
1950// doSessionImport copies the .zutsession file at src into the
1951// running cwd's sessions directory and loads it as the active
1952// session, same as `/sessions` -> pick. When src is empty we ask
1953// the user to pass a path (no usable default here).
1954
1955// defaultExportDir returns ~/Downloads when it exists, or ~ as a
1956// fallback, or /tmp on exotic machines with no home dir.
1957
1958// expandTilde turns a leading ~ into the user's home directory.
1959// Returns the input unchanged when there's no tilde or no home.
1960
1961// unquotePath strips a matching pair of surrounding single or
1962// double quotes. Drag-drop paste in the tui auto-quotes dropped
1963// file paths so the shell-like `/session import 'foo bar.zs'`
1964// stays well-formed; when the TUI's own slash handler consumes
1965// the arg, we want the raw path back.
1966
1967// friendlyPath collapses the user's home directory to a leading ~
1968// so status messages read cleanly. Falls back to the raw path when
1969// the home dir is unknown.
1970
1971// doSessionFork opens the /jump turn picker in "fork mode". The
1972// next selection branches the current session at that user turn
1973// instead of scrolling the viewport to it.
1974
1975// doSessionTree opens the current session family after the shared
1976// fail-closed gate succeeds. It intentionally does not fall back to the
1977// in-memory transcript: a tree that cannot be persisted and reloaded cannot
1978// safely create a navigation branch.
1979
1980// applySessionTreeMessageSelection keeps the old scalar integration
1981// source-compatible for package consumers. New dialog selections use the
1982// structured sessionTreeTarget path below.
1983
1984// applySessionTreeTarget checks out a structured dialog target. The target's
1985// source and effective indices come from the same preflight snapshot the
1986// dialog rendered, while the live read below preserves compatibility with
1987// the existing LoadSession(path) error callback.
1988
1989// applyForkSelection branches the current session at msgIdx+1 (so
1990// the selected user message and everything before it is included
1991// in the new branch), then switches the running agent to the new
1992// file. Called from the jump-dialog handler when pendingFork=true.
1993
1994// formatInt is a tiny strconv.Itoa shim; keeps the handler above
1995// from needing a strconv import just for one call.
1996
1997// assistantText returns the concatenated text of every TextBlock in
1998// m. Used by the streaming-view dedupe guard to tell when a live
1999// streamed reply has already been promoted into the transcript.
2000
2001// resetTranscriptRenderLocked invalidates every render cache that assumes
2002// the previous transcript remains structurally intact. Compaction is a
2003// replacement, not an append: the flow renderer must repaint from the new
2004// transcript rather than diff it against scrollback rows from the old one.
2005// Must be called with i.mu held.
2006
2007// resetStreamingStateLocked clears every piece of streaming state
2008// in one shot. Used by abort paths (turn cancel, compact hand-off,
2009// queue drain) so the pacer doesn't keep draining stale runes from
2010// a prior turn. Must be called with i.mu held.
2011
2012// openAllToolGatesLocked drops every pending tool gate so that any
2013// tool registered during this turn renders unconditionally from now
2014// on. Called when streaming finalizes (the paced text has fully
2015// drained and `streaming` is about to reset to length 0): without
2016// this, the gate comparison against a freshly-reset streaming buffer
2017// would wrongly re-hide tools that had already cleared their gate.
2018// Must be called with i.mu held.
2019
2020// gateToolLocked records the stream position at which a tool call may
2021// become visible. The gate is the total length the streaming buffer
2022// will reach once the pacer has drained everything currently queued
2023// (already painted + still pending). Holding the tool block back
2024// until the pacer crosses that mark guarantees the prose emitted
2025// before the tool call finishes typing out above it, instead of the
2026// tool block snapping in while the paragraph is still filling in.
2027//
2028// We only gate while text is actively streaming. If no stream is in
2029// flight (gate 0), the tool shows immediately, which is the correct
2030// behaviour for tool-only turns and replayed sessions. First
2031// registration wins so a later EvToolCall can't move an existing
2032// gate. Must be called with i.mu held.
2033
2034// toolGateOpenLocked reports whether the gated tool block may render
2035// yet, i.e. the pacer has drained enough text to reach the position
2036// recorded when the tool call arrived. Must be called with i.mu held.
2037
2038// assistantMessageSideEffects runs the non-visual hooks attached to
2039// EvAssistantMessage: the host-provided OnAssistant callback and the
2040// telegram-bridge mirror. Called with i.mu held.
2041//
2042// Factored out of handleEvent because the streaming pacer may defer
2043// visual reset until after the last buffered rune has painted, but
2044// the callbacks themselves must fire on message arrival so
2045// downstream observers (session persistence, telegram, cost panels)
2046// don't wait on a UI animation to catch up.
2047
2048// paintPaceRate is how many runes the streaming pacer releases per
2049// tick. With a 16ms tick, 6 runes/tick is ~375 runes/s — fast enough
2050// that a 500-rune summary finishes in ~1.3s, slow enough to look
2051// like a human typing. Empirically matches the feel of provider
2052// paths that already drip-stream natively.
2053const paintPaceRate = 6
2054
2055// paintPaceInterval is the tick interval for the streaming pacer.
2056// 16ms lines up with the redraw throttle so we never paint faster
2057// than the terminal can keep up.
2058const paintPaceInterval = 16 * time.Millisecond
2059
2060// runStreamPacer drains buffered deltas from streamPending into
2061// streaming a small batch per tick, invalidating after each move.
2062// It stops when the context cancels (tui shutdown).
2063//
2064// Why a pacer: providers differ wildly in how they chunk their
2065// text_delta events. The API-key path on Anthropic emits ~30 drips
2066// for a 400-token summary; the OAuth path can coalesce the same
2067// summary into 3 fat chunks, visually indistinguishable from "the
2068// whole reply just appeared". The pacer normalizes that so every
2069// path looks the same on screen.

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