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