返回 DeepSeek-Reasonix
chat_tui.go
根目录 / internal / cli / chat_tui.go
1 package cli
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "regexp"
10 "runtime"
11 "strconv"
12 "strings"
13 "time"
14 "unicode/utf8"
15
16 "charm.land/bubbles/v2/key"
17 "charm.land/bubbles/v2/spinner"
18 "charm.land/bubbles/v2/textarea"
19 "charm.land/bubbles/v2/viewport"
20 tea "charm.land/bubbletea/v2"
21 "charm.land/lipgloss/v2"
22 "github.com/charmbracelet/x/ansi"
23
24 "reasonix/internal/agent"
25 "reasonix/internal/billing"
26 "reasonix/internal/boot"
27 "reasonix/internal/command"
28 "reasonix/internal/config"
29 "reasonix/internal/control"
30 "reasonix/internal/event"
31 "reasonix/internal/gitcmd"
32 "reasonix/internal/i18n"
33 "reasonix/internal/memory"
34 "reasonix/internal/migration"
35 "reasonix/internal/outputstyle"
36 "reasonix/internal/plugin"
37 "reasonix/internal/provider"
38 "reasonix/internal/recovery"
39 "reasonix/internal/sandbox"
40 "reasonix/internal/sessioninbox"
41 "reasonix/internal/skill"
42 "reasonix/internal/tool"
43 )
44
45 // chatTUI is a bubbletea Model that normally owns the terminal with an
46 // alt-screen transcript viewport. Termux is the exception: it stays in the
47 // normal buffer and commits finalized output to native scrollback via
48 // tea.Println so taps can still focus the soft keyboard.
49 type chatTUI struct {
50 turnSettingsIntent *controllerTurnIntent
51 ctrl control.SessionAPI
52 shutdownErr error // final save's failure; reported after terminal release
53 label string
54 missing string // missing-key warning surfaced once in the banner, "" when ready
55 webHandoffState
56 // diagnostics is the process-owned TUI log/watchdog started before terminal
57 // takeover. Nil in unit tests that construct chatTUI without chatREPL.
58 diagnostics *tuiDiagnostics
59 firstFrameLogged bool
60
61 width int
62 height int
63 glyphs *glyphFit // console-measured stand-ins for runes drawn wider than counted
64 // themeSweep freezes the frame while a /theme switch wipes across it.
65 themeSweep *themeSweep
66 // nativeScrollback keeps Termux out of alt-screen mode so taps still focus
67 // the textarea and raise the soft keyboard.
68 nativeScrollback bool
69 // mouseCaptureOff releases mouse ownership back to the terminal (View() sets
70 // tea.MouseModeNone instead of MouseModeCellMotion) so its native
71 // click-drag selection and right-click context menu work again. Toggled by
72 // "/mouse" or REASONIX_DISABLE_MOUSE at startup; trades away in-app
73 // drag-select, the transcript scrollbar, and wheel-scroll while it's on,
74 // since the terminal no longer forwards those events to Reasonix.
75 mouseCaptureOff bool
76
77 input textarea.Model
78 composerSel composerSelection
79 composerMap composerLayoutCache
80 pinnedScroll pinnedPanelScroll
81 // composerScrollOffset is an independent view offset used after the user
82 // wheels inside an overflowing composer. The textarea keeps ownership of the
83 // real insertion cursor; a subsequent edit or cursor key reattaches the view
84 // to that cursor without the wheel having moved it.
85 composerScrollOffset int
86 composerScrollDetached bool
87 spinner spinner.Model
88
89 submittedInputs []string
90 submittedInputCursor int
91 submittedInputDraft string
92 pastedBlocks []pastedBlock
93 nextPasteID int
94 usedPasteIDs map[int]struct{}
95
96 state tuiState
97 // maintenance is the active controller-owned compaction lifecycle. It is
98 // deliberately separate from state: maintenance keeps the composer usable
99 // for durable queueing and must not start ordinary turn timers or metrics.
100 maintenance *event.SessionOperationInfo
101 maintenanceTranscriptID string
102 maintenanceTranscriptIdx int
103 maintenanceTerminal map[string]struct{}
104 maintenanceLatest map[string]event.SessionOperationInfo
105 compactCompatibilityPending bool
106 compactLifecycleObserved bool
107 runStart time.Time
108 elapsed int
109 elapsedTickGeneration uint64
110 // Recovery state is cleared by progress or completion.
111 retryAttempt int
112 retryMax int
113 recovery *event.RecoveryStatus
114 // Host turn phase, cleared on TurnDone.
115 turnPhase string
116 readStatusState
117 // turnTokens accumulates this turn's output tokens (summed from per-step Usage
118 // events) for the live "↓N" readout in the running status line.
119 turnTokens int
120 // showTurnUsage controls whether completed per-request token/cost receipts are
121 // retained in transcript scrollback. Usage accounting remains active either way.
122 showTurnUsage bool
123 // sessionCostQuote is the incrementally aggregated canonical quote seen on
124 // Usage events. It powers the persistent footer without re-running pricing.
125 sessionCostQuote *billing.CostQuote
126
127 // balance is the last-fetched wallet-balance readout (e.g. "¥110.00"), "" when
128 // the provider declares no balance_url or a fetch failed. Refreshed async on
129 // startup and after each turn so the status line stays roughly current without
130 // blocking the event loop.
131 balance string
132
133 // todos is copied only from a successful semantic todo result. The separate
134 // dismissal bit is a mounted-view preference and never changes host state.
135 // Both reset at the host's real turn_started boundary.
136 todos []event.Todo
137 todosDismissed bool
138 searchSources []provider.ServerSearchHit // post-answer footnotes; cleared when the turn settles
139
140 // marker rides in outgoing user messages so the cache-stable prompt prefix is
141 // left untouched.
142 planMode bool
143 // yoloRestoreToolApprovalMode remembers the safe permission preset that
144 // Ctrl+Y should restore after toggling the canonical danger-full-access
145 // preset under the user-facing YOLO label.
146 yoloRestoreToolApprovalMode string
147 // legacyScrollClear keeps the per-offset ClearScreen workaround only for Warp.
148 legacyScrollClear bool
149 // sessionSwitch suppresses that workaround during a transcript rebuild (#5441).
150 sessionSwitch bool
151 // inboxSelectedID is the currently highlighted durable inbox item while
152 // browsing the queue in tuiRunning. Empty means "not browsing". Full bodies
153 // are never cached here — only the selected ID and the snapshot metadata.
154 inboxSelectedID string
155 // queueEditCursor tracks which queued message the user is currently
156 // browsing/editing via ↑/↓ during tuiRunning. -1 means "not browsing".
157 queueEditCursor int
158 // queueEditDraft saves the in-progress input text when the user first
159 // presses ↑ to browse the queue, so it can be restored when the cursor
160 // moves past the end.
161 queueEditDraft string
162 // queueConfirmDelete, when true, the next 'd' confirms deletion of the
163 // selected inbox item.
164 queueConfirmDelete bool
165
166 // history is a resumed session's messages, committed to scrollback once on
167 // the first WindowSizeMsg so a reopened chat shows its prior transcript.
168 history []provider.Message
169
170 // reasoning accumulates the in-progress thinking stream (dim); pending
171 // accumulates the in-progress answer (raw markdown). They are committed to
172 // scrollback (reasoning collapsed by default, answer markdown-rendered) when they
173 // finalize — at a tool/usage boundary or turn end — not previewed live, so
174 // the bottom region stays a stable height. pendingCommit queues finalized
175 // lines so a single Update emits exactly one ordered tea.Println.
176 reasoning *strings.Builder
177 pending *strings.Builder
178 pendingCommit *[]string
179 showReasoning bool // Ctrl+O / /verbose: show raw thinking text in the CLI
180 cfg *config.Config
181 // reasoningLineIdx is the transcript index of the live "▎ thinking…" marker
182 // while a reasoning block streams; it's rewritten to "▎ thought for Ns" when
183 // the block closes. -1 when no block is open. transcriptDirty forces a
184 // viewport re-feed after that in-place rewrite (length is unchanged).
185 reasoningLineIdx int
186 // reasoningTextIdx is the transcript index of the live reasoning text block
187 // (the block right after the marker), streamed in as the model thinks and
188 // removed when the block collapses (kept only in verbose mode). -1 when none.
189 reasoningTextIdx int
190 // reasoningView is a bounded trailing window (≤ reasoningViewMax bytes) of the
191 // streaming thought, rendered live; the full text stays in reasoning for verbose.
192 reasoningView []byte
193 // reasoningNative is the Termux/native-scrollback path: reasoning is buffered
194 // without a live transcript block, then appended once as a final summary.
195 reasoningNative bool
196 thinkStart time.Time
197 // answerIdx is the transcript index of the streaming answer block (rewritten in
198 // place as completed paragraphs arrive); -1 when none is open. answerFlushed is
199 // how many bytes of pending have already been rendered into it, so a Text packet
200 // that doesn't close a new paragraph re-renders nothing.
201 answerIdx int
202 answerFlushed int
203 // toolStreamIdx is the transcript index of a running tool's live-output block
204 // (streamed via ToolProgress under the tool card); -1 when none. toolStreamID
205 // is the call ID it belongs to. Only a bounded tail is kept — the last few
206 // complete lines (toolTail) plus the in-progress one (toolPartial) — so a
207 // high-output command can't balloon memory or cost O(n²) re-splitting;
208 // toolLineCount feeds the collapse summary.
209 toolStreamIdx int
210 toolStreamID string
211 toolTail []string
212 toolPartial string
213 toolLineCount int
214 // shellOutputs stores the full accumulated output of each shell command
215 // (tool IDs with "shell-" prefix), so the first 10 lines can be shown after
216 // collapse and Ctrl+B can toggle the complete output.
217 shellOutputs map[string]string
218 shellExpanded map[string]bool
219 // shellTranscriptIdx maps a shell tool ID to the transcript index of its
220 // collapsed output block, so Ctrl+B can rewrite it in place.
221 shellTranscriptIdx map[string]int
222 // toolLineCountByID keeps a switched-away tool's last line count so a late
223 // ToolResult can still render "⎿ N lines" (shellOutputs only tracks "shell-" ids).
224 toolLineCountByID map[string]int
225 // toolStreamStart / toolStreamFrame drive the "⎿ working · Ns" line shown
226 // under a dispatched tool that hasn't produced output yet, so a slow tool
227 // reads as making progress rather than frozen.
228 toolStreamStart time.Time
229 toolStreamFrame int
230 // Sub-agent progress previews (reserved ToolProgress channels) render per
231 // child into their own fixed transcript slot, keyed by the namespaced call
232 // ID — independent of the single live toolStreamID. subagentProgress keeps
233 // the bounded live state (phase, elapsed, recent activity, verbose tails).
234 subagentProgressIdx map[string]int
235 subagentProgress map[string]*cliSubagentProgress
236 transcriptDirty bool
237 // forceGotoBottom is set by replayActiveBranch and resetFreshContextView to
238 // pin the viewport to the bottom after a session / branch / clear switch
239 // regardless of the previous wasAtBottom state (#4584).
240 forceGotoBottom bool
241 // scrollMode is the explicit followTail / userScrolled state machine.
242 // Prefer this over a raw wasAtBottom snapshot so modal height changes
243 // (approval, chooser, pickers) never silently disable tail-follow (#6430).
244 scrollMode scrollFollowMode
245 eventCh chan event.Event
246 started bool // banner + resumed history committed once
247
248 // transcript holds every finalized line commitLine emits; the viewport
249 // renders a scrollable window of it (alt-screen owns the grid, so there's no
250 // native terminal scrollback). sel is the live left-drag text selection.
251 transcript []string
252 // transcriptSources runs parallel to transcript and retains raw, semantic
253 // content for blocks whose layout depends on terminal width. Fixed blocks
254 // keep their already-rendered text; markdown, user bubbles, reasoning, tool
255 // cards, and replay bundles are regenerated after a resize.
256 transcriptSources []transcriptSource
257 // wrappedLines is the viewport line cache; wrapBlockLines / wrapWidth /
258 // wrapBlockCount support append-only updates without re-wrapping the full
259 // history on every streaming commit (#6978).
260 wrappedLines []string
261 wrapBlockLines [][]string
262 wrapWidth int
263 wrapBlockCount int
264 // lastMouseReenable rate-limits ConPTY mouse re-enable sequences (#7583).
265 // mouseReenablePending + timer cover trailing-edge fires after a resize storm.
266 lastMouseReenable time.Time
267 mouseReenablePending bool
268 mouseReenableTimerArmed bool
269 // wantMouseReenable is set by TurnDone (and similar settle points) and
270 // consumed once in Update so the raw enable sequence is batched with the
271 // frame that paints the settled state.
272 wantMouseReenable bool
273 viewport viewport.Model
274 sel selection
275 // autoScroll drives edge-drag scrolling: -1 up, +1 down, 0 off. dragX is the
276 // column the drag is held at, so the ticker can extend the selection head.
277 autoScroll int
278 dragX int
279 // scrollbarDrag owns left-button drags that start on the transcript scrollbar
280 // column. It is separate from text selection so the visual thumb is not a
281 // dead target and dragging it never leaves a transcript selection behind.
282 scrollbarDrag bool
283 scrollbarGrabOffset int
284 // copyNoticeText is a transient "copied to clipboard" hint shown on the status
285 // line after a mouse-drag, right-click, or Ctrl+C selection copy; "" when none
286 // is showing. copyNoticeSeq guards its expiry tick so an older copy's timer
287 // can't clear a newer notice — each copy bumps the sequence and only a tick
288 // carrying the current sequence clears the text.
289 copyNoticeText string
290 copyNoticeSeq int
291 // clipboardImagePending keeps the footer honest while the platform clipboard
292 // is being decoded. clipboardImageRequests counts shortcuts coalesced into the
293 // probe: an image attaches once, while a text fallback preserves every press.
294 clipboardImagePending bool
295 clipboardImageRequests int
296
297 // terminalPasteSeq counts bracketed pastes delivered by the terminal.
298 // clipboardImageTerminalPasteSeq snapshots it when an image probe starts, so a
299 // terminal that pastes text itself is never pasted into twice.
300 terminalPasteSeq uint64
301 clipboardImageTerminalPasteSeq uint64
302
303 // The user bubble is echoed to scrollback immediately on Enter (bubbleStartIdx
304 // marks where in the transcript it landed). It stays "un-sendable" until the
305 // first response packet arrives: pressing Esc/Ctrl+C before then pops those
306 // lines back off the transcript and restores the text to the input box, leaving
307 // no trace. bubblePending is true from startTurn until the first packet confirms
308 // the send or it's un-sent; turnDiscarded then swallows the turn's
309 // already-buffered events until its TurnDone settles.
310 pendingRestore string
311 pendingPastes []string
312 bubbleStartIdx int
313 bubblePending bool
314 turnDiscarded bool
315
316 // pendingApproval holds the tool-call approval currently shown in the banner
317 // (nil when none). While set, the controller's run goroutine is blocked
318 // awaiting ctrl.Approve and key input is captured to answer it.
319 pendingApproval *event.Approval
320 approvalSelection int
321
322 // chooser holds the `ask` tool's question card (nil when none). While set, the
323 // run goroutine is blocked awaiting ctrl.AnswerQuestion and keys drive the card.
324 chooser *chooser
325 // elicit holds the pending MCP elicitation card (nil when none).
326 elicit *elicitCard
327
328 // rewind holds the Esc-Esc / "/rewind" picker (nil when closed); while set,
329 // keys drive it and it renders as an overlay. lastEsc times the double-Esc
330 // gesture that opens it on an empty composer.
331 rewind *rewindPicker
332 // resumePick is the interactive "/resume" session picker overlay. Non-nil
333 // while the user browses saved sessions with ↑/↓ and confirms with Enter.
334 resumePick *resumePicker
335 // reclaimState groups the flags a remote take-back sets and clears together.
336 reclaimState
337 // pendingTakeoverPath remembers the last /resume target refused because a
338 // resident serve on this machine holds its lease; "/takeover" force-takes
339 // that session back.
340 pendingTakeoverPath string
341 // quickPick owns searchable single-choice overlays such as /model and
342 // /provider. It never invokes a raw-mode prompt inside Bubble Tea.
343 quickPick *quickPicker
344 setup *connectionSetup
345 copyPick *copyPicker
346 lastEsc time.Time
347
348 // mcp is the interactive "/mcp" manager overlay. mcpDisabled tracks servers
349 // turned off only for this chat session, matching the desktop connector
350 // toggle's non-persistent semantics.
351 mcp *mcpManager
352 mcpDisabled map[string]bool
353 // mcpConnecting holds servers whose connect runs off the UI loop. It lives
354 // here, not on the manager, so closing and reopening /mcp cannot start a
355 // second handshake for the same server.
356 mcpConnecting map[string]bool
357
358 // clearConfirm is the destructive "/clear" confirmation overlay. It is separate
359 // from /new because /clear discards the current transcript instead of saving it.
360 clearConfirm *clearConfirm
361
362 // lastCtrlCAt records when Ctrl+C was pressed while idle on an empty
363 // composer, enabling a "press again to quit" confirmation pattern (1.5s
364 // window). Reset when Ctrl+C clears non-empty input instead.
365 lastCtrlCAt time.Time
366
367 // mcpImport holds the interactive cc-switch MCP import picker (nil when
368 // closed). It writes selected servers to config and hot-connects the ones that
369 // can start successfully.
370 mcpImport *mcpImportPicker
371
372 // host is the running MCP servers (nil when no plugins). The TUI reads
373 // prompts (slash commands), resources (@-references), and server status
374 // (/mcp) from it.
375 host *plugin.Host
376
377 // commands are custom slash commands loaded from .reasonix/commands; each renders
378 // its template with the typed args and sends the result as a turn.
379 commands []command.Command
380
381 // skills are the discoverable skills (built-in + user/project); each is offered
382 // in the slash menu as "/<name>" and managed via /skills.
383 skills []skill.Skill
384
385 // slashCache holds the immutable slash catalog and the arg-completion data
386 // snapshot, rebuilt only on explicit invalidation — never on keystrokes
387 // (#6417, #7090, #9503).
388 slashCache *slashCompletionCache
389
390 // skillPick is the interactive skill picker overlay for /skills. nil when closed.
391 skillPick *skillPicker
392
393 // buildController builds a fresh controller for a model choice, carrying
394 // prior history across and pinning auto-save to resumePath so the continued
395 // conversation stays in one file (set by chatREPL; it must NOT touch this
396 // model — the swap happens on the running copy). nil disables runtime
397 // rebuild commands. modelRef is the active "provider/model" ref, marked
398 // current in the picker. oldCtrl is the
399 // outgoing controller, passed through so the replacement can carry forward
400 // same-session tool grants and Plan-mode read-only command trust that
401 // don't travel through carry/resumePath (see Controller.RestoreSessionAuthorizations).
402 buildController func(spec controllerBuildSpec, carry []provider.Message, resumePath string, oldCtrl control.SessionAPI) (*control.Controller, error)
403 // rebuildRuntime builds the /reload replacement through boot.Rebuild:
404 // same model/profile/effort, but tools, skills, commands, hooks, MCP
405 // servers, and providers are discovered fresh and the session state
406 // migrates inside the boot layer. Set by chatREPL (it must NOT touch
407 // this model — the swap happens on the running copy); nil disables
408 // /reload.
409 rebuildRuntime runtimeRebuilder
410 lastBuildResult *boot.BuildResult
411 // pendingReload coalesces /reload requests made while a turn or a runtime
412 // switch is in flight; the TurnDone drain runs it once the TUI is idle.
413 pendingReload bool
414 modelRef string
415 effortLevel string // "" when the current provider/model has no configurable effort
416
417 // leases owns the session lease guarding the TUI's active session file (set
418 // by chatREPL; nil in tests and when persistence is disabled). Every in-TUI
419 // operation that rebinds the controller to another session file must move
420 // the lease first — see rebindSessionLease / followSessionLease.
421 leases *control.SessionLeaseKeeper
422 // takeover mirrors a session acquired from a resident Serve and blocks
423 // admission while that Serve is reclaiming it.
424 takeover *cliTakeoverManager
425
426 // outputStyle is the active output-style name (config agent.output_style),
427 // shown as the current entry in the /output-style listing. "" = default.
428 outputStyle string
429
430 // diffMaxLines controls the max lines shown in a diff view. 0 = show all;
431 // non-zero = fold at that many lines. Toggled by /diff-fold.
432 diffMaxLines int
433
434 // statuslineCmd is the user's custom status-line command (config
435 // [statusline].command); "" disables it. statuslineOut caches its latest
436 // one-line stdout, refreshed at startup and after each turn and rendered in
437 // place of the built-in data row.
438 statuslineCmd string
439 statuslineOut string
440 gitStatus gitStatus
441
442 // statusLineCount is the number of terminal rows the status block occupies
443 // (wrapped working line + wrapped status line + wrapped data line). Updated
444 // each frame via computeStatusLineCount so bottomRows can reserve the correct
445 // height; starts at 2 (unwrapped) until first render.
446 statusLineCount int
447
448 // modelSwitchPending is true while any async controller rebuild is in flight.
449 modelSwitchPending bool
450 // pendingModelSwitch holds the tea.Cmd that triggers the async build. The
451 // historical field name is retained because model, effort, skill refresh,
452 // and work-mode changes all share the same atomic swap path.
453 pendingModelSwitch tea.Cmd
454 // oldControllers accumulates controllers retired by runtime switches.
455 // They cannot be closed during the switch (Close runs SessionEnd hooks
456 // and kills plugin subprocesses, both of which corrupt the terminal's
457 // raw mode). Instead they are closed at process exit when the terminal
458 // is already being restored.
459 oldControllers []control.SessionAPI
460
461 // completion is the live autocomplete menu (slash commands; @-refs later).
462 completion completion
463 // fileSearchCache memoizes fileref.Search by query so the bounded walk runs
464 // once per @token fragment, not on every keystroke that re-renders the menu.
465 fileSearchCache map[string][]string
466 }
467
468 type tuiState int
469
470 const (
471 tuiIdle tuiState = iota
472 tuiRunning
473 )
474
475 type controllerBuildSpec struct {
476 ModelRef string
477 ToolApprovalMode string
478 PlanMode bool
479 EffortOverride *string
480 }
481
482 func (m *chatTUI) runtimeSwitchBusy() bool {
483 if m == nil || m.ctrl == nil {
484 return false
485 }
486 status := m.ctrl.RuntimeStatus()
487 return status.Running || status.PendingPrompt || status.BackgroundJobs > 0 || m.pendingApproval != nil || m.chooser != nil
488 }
489
490 func (m *chatTUI) modelReplacementBusy() bool {
491 if m == nil {
492 return false
493 }
494 return control.ModelReplacementBlocked(m.ctrl) || m.pendingApproval != nil || m.chooser != nil
495 }
496
497 // agentEventMsg is one typed event from the agent's run loop.
498 type agentEventMsg event.Event
499
500 // maxEventDrain caps how many buffered events one Update coalesces before
501 // yielding to render, so a sustained output flood still shows live progress.
502 const maxEventDrain = 512
503
504 const resetMouseTracking = ansi.ResetModeMouseX10 +
505 ansi.ResetModeMouseNormal +
506 ansi.ResetModeMouseHighlight +
507 ansi.ResetModeMouseButtonEvent +
508 ansi.ResetModeMouseAnyEvent +
509 ansi.ResetModeMouseExtSgr +
510 ansi.ResetModeMouseExtUtf8 +
511 ansi.ResetModeMouseExtUrxvt +
512 ansi.ResetModeMouseExtSgrPixel
513
514 // compactDoneMsg is the compatibility completion for controllers that do not
515 // support registered management submissions. SessionOperation owns the normal
516 // lifecycle and persistence path.
517 type compactDoneMsg struct{ err error }
518
519 // tuiShutdownMsg asks the live TUI model to persist its current controller and
520 // quit. It is injected from the signal handler so shutdown does not snapshot a
521 // stale controller captured before an in-TUI rebuild.
522 type tuiShutdownMsg struct {
523 completion *tuiShutdownCompletion
524 userInitiated bool
525 }
526
527 // shutdownNow is the tea.Cmd every in-TUI quit gesture returns instead of
528 // tea.Quit. Routing through tuiShutdownMsg gives all exits the same
529 // finalization (Snapshot + lease follow); quitting directly would drop
530 // whatever the controller holds beyond the last snapshot (#5879).
531 func shutdownNow() tea.Msg { return tuiShutdownMsg{userInitiated: true} }
532
533 // elapsedTickMsg fires once a second while a turn runs, driving the "thinking
534 // Ns" counter in the status line. generation rejects a prior turn's timer.
535 type elapsedTickMsg struct{ generation uint64 }
536
537 // balanceMsg carries the result of an async wallet-balance fetch; text is the
538 // formatted readout ("" when none/failed).
539 type balanceMsg struct{ text string }
540
541 // gitStatusMsg carries the latest lightweight git readout for the built-in
542 // status line. Empty means "not a git worktree" or "git unavailable".
543 type gitStatusMsg struct{ status gitStatus }
544
545 func (m chatTUI) refreshGitStatus() tea.Cmd {
546 if m.statuslineCmd != "" {
547 return nil
548 }
549 return fetchGitStatus(sessionWorkspaceRepo(m.ctrl))
550 }
551
552 // sessionWorkspaceRepo is the git identity ctrl's session opened with; a
553 // controller that carries none has no status line to read.
554 func sessionWorkspaceRepo(ctrl control.SessionAPI) gitcmd.Repo {
555 if c, ok := ctrl.(interface{ WorkspaceRepo() gitcmd.Repo }); ok {
556 return c.WorkspaceRepo()
557 }
558 return gitcmd.Repo{}
559 }
560
561 // modelSwitchMsg carries the result of an async /model switch. A nil err means
562 // the new controller is ready in ctrl; label/commands/skills/host mirror the
563 // fields that runModelSubcommand used to set synchronously. oldCtrl is the
564 // previous controller that must be closed after the switch — its cleanup
565 // (SessionEnd hooks, plugin subprocess kill) is deferred to a tea.Cmd so it
566 // runs after the render completes, avoiding corruption of the terminal's raw
567 // mode that would occur if Close() were called from the build goroutine.
568 type modelSwitchMsg struct {
569 resumeTurn *controllerTurnIntent
570 ref string
571 ctrl control.SessionAPI
572 oldCtrl control.SessionAPI
573 label string
574 commands []command.Command
575 skills []skill.Skill
576 host *plugin.Host
577 failurePrefix string
578 successNotice string
579 err error
580 }
581
582 // fetchBalance queries the provider's wallet balance off the event loop. It's a
583 // no-op readout ("") when the provider declares no balance_url or the fetch
584 // fails, so the status line stays quiet rather than surfacing an error.
585 // Wallets are displayed in their original currencies; no conversion or sum is
586 // attempted when more than one currency is returned.
587 func fetchBalance(ctrl control.Status) tea.Cmd {
588 return func() tea.Msg {
589 b, err := ctrl.Balance(context.Background())
590 if err != nil || b == nil {
591 return balanceMsg{}
592 }
593 displayCurrency := ""
594 if cfg, err := config.LoadForRootReadOnly("."); err == nil && cfg != nil {
595 displayCurrency = cfg.ExplicitDisplayCurrency()
596 }
597 return balanceMsg{text: b.DisplayForCurrency(displayCurrency)}
598 }
599 }
600
601 // promptResolvedMsg carries the result of fetching an MCP prompt (an async
602 // prompts/get). display is the command line echoed as the user bubble; sent is
603 // the rendered prompt text that becomes the model turn.
604 type promptResolvedMsg struct {
605 display string
606 sent string
607 err error
608 }
609
610 // extensionActionMsg carries the result of invoking one extension UI action
611 // (an async extension/ui/action round-trip to the sidecar). The extension's
612 // (already redacted) message surfaces as a transcript notice.
613 type extensionActionMsg struct {
614 message string
615 err error
616 }
617
618 // refsResolvedMsg carries the result of resolving the @references in a
619 // submitted line (async file reads / MCP resources/read).
620 type refsResolvedMsg struct {
621 sent string
622 display string
623 restore string
624 block string
625 errs []string
626 }
627
628 type clipboardImageMsg struct {
629 path string
630 err error
631 }
632
633 // newChatTUI assembles the initial model. The controller has already been wired
634 // with an event sink that feeds eventCh; the TUI issues commands to it and
635 // renders the events it emits. Model identity, label, history, host, and commands
636 // are read from the controller, so explicit selections and resumed sessions stay
637 // authoritative.
638 func newChatTUI(ctrl control.SessionAPI, missing string, eventCh chan event.Event, termW int) chatTUI {
639 ti := textarea.New()
640 configureChatTextarea(&ti)
641
642 sp := spinner.New()
643 sp.Spinner = spinner.Dot
644 sp.Style = themeStyle(activeCLITheme.accent)
645
646 commitBuf := []string{}
647 nativeScrollback := detectTermuxTerminal()
648 history := chatUIDisplayHistory(ctrl)
649 nextPasteID, usedPasteIDs := pasteIDStateForHistory(history)
650 return chatTUI{
651 ctrl: ctrl,
652 label: ctrl.Label(),
653 modelRef: ctrl.ModelRef(),
654 missing: missing,
655 nativeScrollback: nativeScrollback,
656 legacyScrollClear: useLegacyViewportScrollClear(runtime.GOOS, os.Environ()),
657 mouseCaptureOff: mouseCaptureOffByDefault(),
658 glyphs: newConsoleGlyphFit(os.Stdout),
659 input: ti,
660 spinner: sp,
661 submittedInputCursor: -1,
662 queueEditCursor: -1,
663 maintenanceTranscriptIdx: -1,
664 maintenanceTerminal: make(map[string]struct{}),
665 maintenanceLatest: make(map[string]event.SessionOperationInfo),
666 nextPasteID: nextPasteID,
667 usedPasteIDs: usedPasteIDs,
668 reasoningLineIdx: -1,
669 reasoningTextIdx: -1,
670 answerIdx: -1,
671 toolStreamIdx: -1,
672 reasoning: &strings.Builder{},
673 pending: &strings.Builder{},
674 pendingCommit: &commitBuf,
675 diffMaxLines: diffFoldLimit,
676 showReasoning: nativeScrollback,
677 showTurnUsage: true,
678 shellOutputs: make(map[string]string),
679 shellExpanded: make(map[string]bool),
680 shellTranscriptIdx: make(map[string]int),
681 toolLineCountByID: make(map[string]int),
682 subagentProgressIdx: make(map[string]int),
683 subagentProgress: make(map[string]*cliSubagentProgress),
684 eventCh: eventCh,
685 history: history,
686 host: ctrl.Host(),
687 commands: ctrl.Commands(),
688 skills: ctrl.SlashSkills(),
689 viewport: viewport.New(viewport.WithWidth(termW)),
690 statusLineCount: 3,
691 }
692 }
693
694 func transcriptContentWidth(termW int, nativeScrollback bool) int {
695 if !nativeScrollback {
696 termW-- // reserve the last column for the transcript scrollbar
697 }
698 return max(termW, 1)
699 }
700
701 func configureChatTextarea(ti *textarea.Model) {
702 // Keep a stable two-cell input affordance, matching the prompt treatment in
703 // other coding TUIs. Continuation rows receive two spaces so text and the
704 // real terminal cursor stay aligned without repeating the arrow.
705 ti.SetPromptFunc(composerPromptWidth, func(info textarea.PromptInfo) string {
706 if info.LineNumber != 0 {
707 return ""
708 }
709 if info.Focused {
710 return accent("❯ ")
711 }
712 return dim("❯ ")
713 })
714 ti.CharLimit = 16384
715 // The prompt and real terminal cursor already show where typing starts. Keep
716 // the idle composer quiet; modal free-text questions set their own temporary
717 // placeholder through refreshInputPlaceholder.
718 ti.Placeholder = ""
719 ti.DynamicHeight = true
720 ti.MinHeight = 1
721 ti.MaxHeight = maxInputRows
722 ti.MaxContentHeight = ti.CharLimit
723 ti.SetHeight(1)
724 ti.ShowLineNumbers = false
725 applyTextareaTheme(ti)
726 // Use the real terminal cursor (not a styled virtual one) so View can place
727 // it at the insertion point and IME candidate windows anchor to the input.
728 ti.SetVirtualCursor(false)
729 // Plain Enter submits (the chatTUI handler intercepts it), so the textarea's
730 // own InsertNewline binding moves to Alt+Enter / Ctrl+J / Shift+Enter.
731 ti.KeyMap.InsertNewline = key.NewBinding(key.WithKeys("alt+enter", "ctrl+j", "shift+enter"))
732 // bubbles binds word motion to Alt+arrows (the macOS convention); Windows and
733 // Linux terminals send Ctrl+arrows for the same intent.
734 ti.KeyMap.WordForward = key.NewBinding(key.WithKeys("alt+right", "alt+f", "ctrl+right"))
735 ti.KeyMap.WordBackward = key.NewBinding(key.WithKeys("alt+left", "alt+b", "ctrl+left"))
736 // Linux terminals send Ctrl+Backspace to delete the word behind the cursor.
737 ti.KeyMap.DeleteWordBackward = key.NewBinding(key.WithKeys("alt+backspace", "ctrl+w", "ctrl+backspace"))
738 ti.Focus()
739 }
740
741 func (m *chatTUI) refreshInputPlaceholder() {
742 if m.chooserTyping() {
743 m.input.Placeholder = i18n.M.AskTypeSomething
744 return
745 }
746 m.input.Placeholder = ""
747 }
748
749 func isTermuxTerminal() bool {
750 if os.Getenv("TERMUX_VERSION") != "" || os.Getenv("TERMUX_APP_PID") != "" || os.Getenv("TERMUX__PREFIX") != "" {
751 return true
752 }
753 return strings.Contains(os.Getenv("PREFIX"), "/com.termux/")
754 }
755
756 var detectTermuxTerminal = isTermuxTerminal
757
758 func (m *chatTUI) rememberSubmittedInput(input string) {
759 if strings.TrimSpace(input) == "" {
760 return
761 }
762 if len(m.submittedInputs) == 0 || m.submittedInputs[len(m.submittedInputs)-1] != input {
763 m.submittedInputs = append(m.submittedInputs, input)
764 }
765 m.submittedInputCursor = -1
766 m.submittedInputDraft = ""
767 }
768
769 func (m *chatTUI) recallSubmittedInput(delta int) bool {
770 if len(m.submittedInputs) == 0 {
771 return false
772 }
773 if m.submittedInputCursor >= 0 && m.input.Value() != m.submittedInputs[m.submittedInputCursor] {
774 m.resetSubmittedInputRecall() // an edited entry is the new draft
775 }
776 cursor := m.submittedInputCursor
777 if cursor < 0 {
778 if delta > 0 {
779 return false
780 }
781 if m.input.Line() != 0 {
782 return false // first-line Up enters history; lower lines navigate the draft
783 }
784 m.submittedInputDraft = m.input.Value()
785 cursor = len(m.submittedInputs) - 1
786 } else {
787 if delta < 0 && m.input.Line() != 0 {
788 return false // inside a multi-line entry the textarea moves the cursor
789 }
790 if delta > 0 && m.input.Line() != m.input.LineCount()-1 {
791 return false
792 }
793 cursor += delta
794 }
795
796 if cursor < 0 {
797 cursor = 0
798 }
799 if cursor >= len(m.submittedInputs) {
800 m.submittedInputCursor = -1
801 m.input.SetValue(m.submittedInputDraft)
802 m.growInputToFit()
803 return true
804 }
805 m.submittedInputCursor = cursor
806 m.input.SetValue(m.submittedInputs[cursor])
807 m.growInputToFit()
808 return true
809 }
810
811 func (m *chatTUI) resetSubmittedInputRecall() {
812 m.submittedInputCursor = -1
813 m.submittedInputDraft = ""
814 }
815
816 // navigateQueue moves through the durable inbox during tuiRunning.
817 // delta < 0 means ↑ (older), delta > 0 means ↓ (newer). Returns true if the
818 // input was updated. Bodies are loaded by ID only for the selected row.
819 func (m *chatTUI) navigateQueue(delta int) bool {
820 items := m.inboxPreviews()
821 if len(items) == 0 {
822 return false
823 }
824 cursor := m.queueEditCursor
825 if cursor < 0 {
826 if delta > 0 {
827 return false // already at "new draft" — nothing newer
828 }
829 // First ↑: save the current draft and jump to the last queued item.
830 m.queueEditDraft = m.input.Value()
831 cursor = len(items) - 1
832 } else {
833 cursor += delta
834 }
835
836 if cursor < 0 {
837 cursor = 0
838 }
839 if cursor >= len(items) {
840 // Past the end: restore the draft the user was composing.
841 m.queueEditCursor = -1
842 m.inboxSelectedID = ""
843 m.input.SetValue(m.queueEditDraft)
844 m.growInputToFit()
845 return true
846 }
847 m.queueEditCursor = cursor
848 m.inboxSelectedID = items[cursor].ID
849 // Load body only for the selected item (edit path).
850 if _, env, err := m.ctrl.ReadInboxItem(items[cursor].ID); err == nil {
851 m.input.SetValue(env.SubmitText)
852 } else {
853 m.input.SetValue(items[cursor].Preview)
854 }
855 m.growInputToFit()
856 return true
857 }
858
859 // resetQueueNavigation resets the queue browsing cursor so the user returns to
860 // normal input mode. Any in-progress edit is discarded (the queued item keeps
861 // its previous value).
862 func (m *chatTUI) resetQueueNavigation() {
863 m.queueEditCursor = -1
864 m.queueEditDraft = ""
865 m.inboxSelectedID = ""
866 m.queueConfirmDelete = false
867 }
868
869 // renderQueueIndicator renders up to three bounded inbox previews above the
870 // input when instructions are queued. Full bodies are never materialised here.
871 func (m chatTUI) renderQueueIndicator() string {
872 items := m.inboxPreviews()
873 if len(items) == 0 {
874 return ""
875 }
876 queueStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")) // dim grey
877 highlightStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("250"))
878 var lines []string
879 // Ordinary status: at most three rows; full list via /queue.
880 limit := min(len(items), 3)
881 for i := range limit {
882 it := items[i]
883 preview := it.Preview
884 if preview == "" {
885 preview = "(empty)"
886 }
887 // Already bounded by sessioninbox.PreviewText; cap display further.
888 if r := []rune(preview); len(r) > 50 {
889 preview = string(r[:47]) + "…"
890 }
891 cursor := " "
892 style := queueStyle
893 if m.queueEditCursor == i || m.inboxSelectedID == it.ID {
894 cursor = "▸"
895 style = highlightStyle
896 }
897 mark := ""
898 switch it.State {
899 case sessioninbox.StateUncertain:
900 mark = " ?"
901 case sessioninbox.StateBlocked:
902 mark = " !"
903 case sessioninbox.StateRunning, sessioninbox.StateSteerAccepted, sessioninbox.StateSteerConsumed:
904 mark = " …"
905 }
906 lines = append(lines, style.Render(fmt.Sprintf(" %s [%d]%s %s", cursor, it.Pos, mark, preview)))
907 }
908 if more := len(items) - limit; more > 0 {
909 lines = append(lines, queueStyle.Render(fmt.Sprintf(" … +%d more (/queue list)", more)))
910 }
911 if m.inboxSnap().Paused {
912 lines = append(lines, queueStyle.Render(" ⏸ inbox paused (space to resume)"))
913 }
914 return strings.Join(lines, "\n")
915 }
916
917 // prompts returns the MCP prompts discovered at startup (nil when no plugins).
918 func (m *chatTUI) prompts() []plugin.Prompt {
919 if m.host == nil {
920 return nil
921 }
922 return m.host.Prompts()
923 }
924
925 func (m chatTUI) Init() tea.Cmd {
926 return tea.Batch(
927 textarea.Blink, forceSyncOutputCmd(),
928 waitForAgentEvent(m.eventCh), fetchBalance(m.ctrl),
929 m.runStatusline(), // nil (no-op) unless a custom status line is configured
930 m.refreshGitStatus(),
931 )
932 }
933
934 func suspendWithMouseReset() tea.Cmd {
935 return tea.Sequence(tea.Raw(resetMouseTracking), tea.Suspend)
936 }
937
938 func (m chatTUI) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
939 // Confirm booting → idle on the first Update. User input (keys/mouse/focus)
940 // must NOT refresh the active-turn heartbeat; only elapsedTick and work
941 // events do, so interaction cannot mask a stuck event loop (#7809).
942 if m.diagnostics != nil {
943 m.diagnostics.NoteBooted()
944 }
945 logFirstFrame := false
946 if m.diagnostics != nil && !m.firstFrameLogged {
947 if _, ok := msg.(tea.WindowSizeMsg); ok {
948 logFirstFrame = true
949 }
950 }
951 // Prefer explicit scrollMode over a raw AtBottom snapshot so opening an
952 // approval/chooser (height-only change) does not disable tail-follow (#6430).
953 followTail := m.shouldFollowTail()
954 prevLines := len(m.transcript)
955 prevWidth := m.width
956 prevHeight := m.height
957 prevYOff := m.viewport.YOffset()
958 var resizeAnchor transcriptResizeAnchor
959 if size, ok := msg.(tea.WindowSizeMsg); ok && size.Width != m.width && !followTail {
960 resizeAnchor = captureTranscriptResizeAnchor(m.transcript, m.viewport.Width(), prevYOff)
961 }
962
963 next, cmd := m.update(msg)
964 cm := next.(chatTUI)
965 if logFirstFrame {
966 cm.firstFrameLogged = true
967 if cm.diagnostics != nil {
968 cm.diagnostics.Milestone("first_frame")
969 }
970 }
971
972 contentW := transcriptContentWidth(cm.width, cm.nativeScrollback)
973 cm.viewport.SetWidth(contentW)
974 // Recompute the wrapped status-line count so bottomRows reserves the right
975 // height for the viewport. Use cm.width (same as boxW in View()) so the
976 // wrapping width matches what View() actually renders.
977 cm.statusLineCount = cm.computeStatusLineCount(cm.width)
978 // Keep the composer proportional to the live terminal instead of letting its
979 // absolute row cap crowd the transcript and fixed status rows on short
980 // windows. Textarea remains the owner of the scroll offset and caret reveal.
981 cm.syncInputHeightLimit()
982 cm.syncPinnedPanelScroll()
983 cm.viewport.SetHeight(cm.transcriptHeight())
984 widthChanged := cm.width != prevWidth
985 if widthChanged {
986 cm.reflowTranscript(cm.width)
987 // Selection coordinates are visual-line based and cannot survive a
988 // semantic reflow without selecting unrelated text.
989 cm.sel = selection{}
990 }
991 // Wrap sync: full rebuild only on width change or history shrink. Streaming
992 // answer/tool rewrites use invalidateWrapFrom → suffix-only re-wrap; the
993 // transcriptDirty flag alone must never force a full-history rebuild (#6978).
994 forceFullWrap := widthChanged || len(cm.transcript) < prevLines
995 wrapBehind := cm.wrapWidth != contentW || cm.wrapBlockCount != len(cm.transcript)
996 if forceFullWrap || wrapBehind || len(cm.transcript) != prevLines {
997 if cm.syncWrappedLines(contentW, forceFullWrap) {
998 cm.feedViewportContent()
999 }
1000 if followTail || cm.shouldFollowTail() {
1001 cm.viewport.GotoBottom() // tail-follow: stay pinned to newest output
1002 cm.markFollowTail()
1003 } else if widthChanged && resizeAnchor.valid {
1004 cm.viewport.SetYOffset(resizeAnchor.yOffset(cm.transcript, contentW))
1005 }
1006 } else if followTail && (cm.forceGotoBottom || cm.height != prevHeight) {
1007 // Height-only change (modal open/close, status wrap) must still pin
1008 // when we are in followTail — without waiting for new transcript.
1009 cm.viewport.GotoBottom()
1010 }
1011 if cm.forceGotoBottom {
1012 cm.viewport.GotoBottom()
1013 cm.markFollowTail()
1014 cm.forceGotoBottom = false
1015 }
1016 cm.transcriptDirty = false
1017
1018 // Rate-limited mouse re-enable after real resize, focus regain, or turn
1019 // settle so Windows ConPTY keeps wheel → MouseWheelMsg (#7583). Trailing
1020 // timer msgs are handled here too. Same-size WindowSizeMsg (session-switch
1021 // rebuilds) must not force a spurious Raw cmd.
1022 var mouseCmd tea.Cmd
1023 switch v := msg.(type) {
1024 case tea.WindowSizeMsg:
1025 if cm.width != prevWidth || cm.height != prevHeight {
1026 mouseCmd = cm.maybeReenableMouse()
1027 }
1028 case tea.FocusMsg:
1029 mouseCmd = cm.maybeReenableMouse()
1030 case mouseReenableMsg:
1031 mouseCmd = cm.handleMouseReenableMsg(v)
1032 }
1033 if cm.wantMouseReenable {
1034 cm.wantMouseReenable = false
1035 if c := cm.maybeReenableMouse(); c != nil {
1036 mouseCmd = batchCmds(mouseCmd, c)
1037 }
1038 }
1039
1040 // Keep the legacy full redraw only where Warp's scroll optimization can
1041 // strand stale rows. Every other terminal relies on Bubble Tea's renderer.
1042 if cm.legacyScrollClear && cm.viewport.YOffset() != prevYOff && !cm.nativeScrollback && !cm.sessionSwitch {
1043 cm.sessionSwitch = false
1044 return cm, batchCmds(tea.ClearScreen, mouseCmd, cmd)
1045 }
1046 cm.sessionSwitch = false
1047 return cm, batchCmds(mouseCmd, cmd)
1048 }
1049
1050 // batchCmds is tea.Batch that collapses an all-nil list to nil so callers can
1051 // assert "no work" without false positives from Batch(nil, nil).
1052 func batchCmds(cmds ...tea.Cmd) tea.Cmd {
1053 var out []tea.Cmd
1054 for _, c := range cmds {
1055 if c != nil {
1056 out = append(out, c)
1057 }
1058 }
1059 switch len(out) {
1060 case 0:
1061 return nil
1062 case 1:
1063 return out[0]
1064 default:
1065 return tea.Batch(out...)
1066 }
1067 }
1068
1069 // update runs the model's message handling. Update wraps it to keep the
1070 // transcript viewport sized, fed, and tail-following after every message.
1071 func (m chatTUI) update(msg tea.Msg) (tea.Model, tea.Cmd) {
1072 var cmds []tea.Cmd
1073 var inputBeforeSelection string
1074
1075 switch msg := msg.(type) {
1076 case tea.WindowSizeMsg:
1077 m.followComposerCursor()
1078 m.width = msg.Width
1079 m.height = msg.Height
1080 m.input.SetWidth(max(msg.Width-4, 1))
1081 // Commit the banner — and a resumed session's transcript — once, now
1082 // that the width is known.
1083 if !m.started {
1084 m.started = true
1085 history := append([]provider.Message(nil), m.history...)
1086 m.commitTranscriptSource(transcriptSource{
1087 kind: transcriptSourceReplayBundle, raw: m.missing, history: history,
1088 })
1089 m.history = nil
1090 }
1091
1092 case tea.FocusMsg:
1093 // Terminal regained focus — ConPTY may have dropped mouse tracking
1094 // while the pane was unfocused (#7583). Re-enable is issued from Update.
1095 return m, nil
1096
1097 case tea.MouseWheelMsg:
1098 if m.scrollPinnedPanelMouse(msg) {
1099 return m, nil
1100 }
1101 if m.mouseOverComposer(msg.X, msg.Y) {
1102 delta := 0
1103 switch msg.Button {
1104 case tea.MouseWheelUp:
1105 delta = -composerWheelRows
1106 case tea.MouseWheelDown:
1107 delta = composerWheelRows
1108 }
1109 if delta != 0 && m.scrollComposer(delta) {
1110 return m, nil
1111 }
1112 }
1113 // Outside the composer, or once its internal viewport has reached the
1114 // requested edge, continue the gesture in the transcript. This mirrors
1115 // ordinary nested-scroll behavior and avoids a dead wheel at boundaries.
1116 switch msg.Button {
1117 case tea.MouseWheelUp:
1118 m.viewport.ScrollUp(3)
1119 case tea.MouseWheelDown:
1120 m.viewport.ScrollDown(3)
1121 }
1122 m.syncScrollModeAfterGesture()
1123 return m, nil
1124
1125 case tea.MouseClickMsg:
1126 // Match the complete terminal right-click convention while Reasonix owns
1127 // the mouse: copy an active selection, otherwise paste clipboard text into
1128 // the visible composer. Left-press begins a selection unless it lands on
1129 // the transcript scrollbar or a shell-output hint line.
1130 // Middle-click pastes tmux's current buffer when tmux owns the pane;
1131 // otherwise it follows the X11/Wayland PRIMARY-selection convention.
1132 if msg.Button == tea.MouseMiddle {
1133 if m.hideComposer() {
1134 return m, nil
1135 }
1136 cmds = append(cmds, pasteMiddleClick())
1137 return m, finalize(m, cmds)
1138 }
1139 if msg.Button == tea.MouseRight && m.validComposerSelection() && !m.composerSel.empty() {
1140 cmds = append(cmds, m.copySelectionWithNotice(m.selectedComposerText()))
1141 return m, finalize(m, cmds)
1142 }
1143 if msg.Button == tea.MouseRight && m.sel.active && !m.sel.empty() {
1144 text := m.selectedText()
1145 m.sel = selection{}
1146 cmds = append(cmds, m.copySelectionWithNotice(text))
1147 return m, finalize(m, cmds)
1148 }
1149 if msg.Button == tea.MouseRight && !m.hideComposer() {
1150 cmds = append(cmds, pasteClipboardText())
1151 return m, finalize(m, cmds)
1152 }
1153 if msg.Button == tea.MouseLeft {
1154 if at, ok := m.composerCaretAt(msg.X, msg.Y, false); ok {
1155 m.sel = selection{}
1156 m.autoScroll = 0
1157 m.setComposerCursor(at.offset)
1158 m.composerSel = composerSelection{
1159 active: true, anchor: at.offset, head: at.offset, value: m.input.Value(),
1160 }
1161 return m, nil
1162 }
1163 m.composerSel = composerSelection{}
1164 }
1165 if msg.Button == tea.MouseLeft && m.inScrollbar(msg.X, msg.Y) {
1166 m.sel = selection{}
1167 m.autoScroll = 0
1168 m.scrollbarDrag = true
1169 m.scrollbarGrabOffset = m.scrollbarGrabRowOffset(msg.Y)
1170 m.dragScrollbar(msg.Y)
1171 return m, nil
1172 }
1173 if msg.Button == tea.MouseLeft && msg.Y < m.viewport.Height() {
1174 // Check if the clicked line is a shell-output hint.
1175 lineIdx := m.viewport.YOffset() + msg.Y
1176 if lineIdx >= 0 && lineIdx < len(m.wrappedLines) {
1177 clicked := m.wrappedLines[lineIdx]
1178 if strings.Contains(clicked, "more lines") && strings.Contains(clicked, "Ctrl+B") {
1179 m.toggleShellOutput()
1180 return m, finalize(m, cmds)
1181 }
1182 }
1183 at := m.transcriptCaret(msg.X, msg.Y)
1184 m.sel = selection{active: true, anchor: at, head: at}
1185 m.autoScroll = 0
1186 }
1187 return m, nil
1188
1189 case tea.MouseMotionMsg:
1190 if m.validComposerSelection() {
1191 if at, ok := m.composerCaretAt(msg.X, msg.Y, true); ok {
1192 m.composerSel.head = at.offset
1193 }
1194 return m, nil
1195 }
1196 if m.scrollbarDrag {
1197 m.dragScrollbar(msg.Y)
1198 return m, nil
1199 }
1200 // Drag extends the live selection (CellMotion only reports motion while
1201 // a button is held, so this is a drag). A drag held against the top or
1202 // bottom edge starts an auto-scroll ticker so the selection can run past
1203 // the visible window.
1204 if m.sel.active {
1205 m.sel.head = m.transcriptCaret(msg.X, msg.Y)
1206 m.dragX = msg.X
1207 prev := m.autoScroll
1208 m.autoScroll = edgeScrollDir(msg.Y, m.viewport.Height())
1209 if m.autoScroll != 0 && prev == 0 {
1210 return m, autoScrollTick()
1211 }
1212 }
1213 return m, nil
1214
1215 case autoScrollMsg:
1216 // One edge-scroll step: scroll a single line, drag the selection head to
1217 // the edge row, and keep ticking until the drag ends, leaves the edge, or
1218 // the viewport can't scroll further (so it can't run away to the end).
1219 if !m.sel.active || m.autoScroll == 0 {
1220 return m, nil
1221 }
1222 edgeY := 0
1223 if m.autoScroll > 0 {
1224 m.viewport.ScrollDown(1)
1225 edgeY = m.viewport.Height() - 1
1226 } else {
1227 m.viewport.ScrollUp(1)
1228 }
1229 m.syncScrollModeAfterGesture()
1230 m.sel.head = m.transcriptCaret(m.dragX, edgeY)
1231 // Stop at the boundary so a held edge can't run away to the very end.
1232 if (m.autoScroll > 0 && m.viewport.AtBottom()) || (m.autoScroll < 0 && m.viewport.AtTop()) {
1233 m.autoScroll = 0
1234 return m, nil
1235 }
1236 return m, autoScrollTick()
1237
1238 case tea.MouseReleaseMsg:
1239 if msg.Button == tea.MouseLeft && m.validComposerSelection() {
1240 if at, ok := m.composerCaretAt(msg.X, msg.Y, true); ok {
1241 m.composerSel.head = at.offset
1242 m.setComposerCursor(at.offset)
1243 }
1244 if m.composerSel.empty() {
1245 m.composerSel = composerSelection{}
1246 return m, nil
1247 }
1248 // The terminal cannot see Reasonix's application-owned highlight, and
1249 // macOS commonly consumes Cmd+C before it reaches the TUI. Copy on drag
1250 // release just like transcript selection so the visible selection always
1251 // has a usable clipboard result.
1252 cmds = append(cmds, m.copySelectionWithNotice(m.selectedComposerText()))
1253 return m, finalize(m, cmds)
1254 }
1255 // Release finalizes the selection: a real drag auto-copies it (native
1256 // terminal convention), while the highlight stays on as the visual
1257 // "what's selected" cue and a right-click can still re-copy it. A plain
1258 // click (no drag) clears any prior selection.
1259 if m.scrollbarDrag {
1260 m.dragScrollbar(msg.Y) // already syncs scrollMode
1261 m.scrollbarDrag = false
1262 m.scrollbarGrabOffset = 0
1263 return m, nil
1264 }
1265 m.autoScroll = 0 // stop edge auto-scroll
1266 if msg.Button == tea.MouseLeft && m.sel.active {
1267 if m.sel.empty() {
1268 m.sel = selection{}
1269 } else {
1270 cmds = append(cmds, m.copySelectionWithNotice(m.selectedText()))
1271 }
1272 }
1273 return m, finalize(m, cmds)
1274
1275 case tea.PasteMsg:
1276 return m.applyComposerPaste(msg, true)
1277
1278 case tea.KeyPressMsg:
1279 if m.scrollPinnedPanelKey(msg) {
1280 return m, nil
1281 }
1282 // Any keystroke dismisses a finished selection (copy is a right-click),
1283 // with a few exceptions: Ctrl/Super/Meta+C and Ctrl+Insert copy the
1284 // selection, the paste shortcuts keep it so the async clipboard result
1285 // can replace it, and Left/Right collapse it to its ordered start/end.
1286 sel := m.sel
1287 m.sel = selection{}
1288 if m.validComposerSelection() && !m.composerSel.empty() {
1289 switch {
1290 case msg.String() == "ctrl+c" || msg.String() == "super+c" || msg.String() == "meta+c" || msg.String() == "ctrl+insert":
1291 cmds = append(cmds, m.copySelectionWithNotice(m.selectedComposerText()))
1292 return m, finalize(m, cmds)
1293 case imagePasteShortcut(msg.String(), runtime.GOOS):
1294 // The asynchronous image result replaces the still-active
1295 // selection. Terminal text paste arrives separately as PasteMsg.
1296 case msg.String() == "left":
1297 start, _ := m.composerSel.ordered()
1298 m.composerSel = composerSelection{}
1299 m.setComposerCursor(start)
1300 return m, finalize(m, cmds)
1301 case msg.String() == "right":
1302 _, end := m.composerSel.ordered()
1303 m.composerSel = composerSelection{}
1304 m.setComposerCursor(end)
1305 return m, finalize(m, cmds)
1306 default:
1307 inputBeforeSelection = m.input.Value()
1308 if composerSelectionDeletes(msg, m.input.KeyMap) {
1309 m.deleteComposerSelection()
1310 m.growInputToFit()
1311 m.updateCompletion()
1312 if shouldClearWideInputChange(inputBeforeSelection, m.input.Value()) {
1313 cmds = append(cmds, tea.ClearScreen)
1314 }
1315 return m, finalize(m, cmds)
1316 }
1317 if composerSelectionReplaces(msg, m.input.KeyMap) {
1318 m.deleteComposerSelection()
1319 } else {
1320 m.composerSel = composerSelection{}
1321 }
1322 }
1323 }
1324 // Transcript scroll keys work in any state (PgUp/PgDn are never text).
1325 switch msg.String() {
1326 case "pgup":
1327 m.viewport.PageUp()
1328 m.syncScrollModeAfterGesture()
1329 return m, finalize(m, cmds)
1330 case "pgdown":
1331 m.viewport.PageDown()
1332 m.syncScrollModeAfterGesture()
1333 return m, finalize(m, cmds)
1334 case "ctrl+home":
1335 m.viewport.GotoTop()
1336 m.markUserScrolled()
1337 return m, finalize(m, cmds)
1338 case "ctrl+end":
1339 m.viewport.GotoBottom()
1340 m.markFollowTail()
1341 return m, finalize(m, cmds)
1342 case "ctrl+z":
1343 return m, suspendWithMouseReset()
1344 }
1345 // From this point on the key belongs to the active control rather than
1346 // transcript navigation. Editing or moving the insertion cursor restores
1347 // the textarea's normal caret-following viewport.
1348 m.followComposerCursor()
1349 // A question card is modal: keys drive it. In its free-text ("Type
1350 // something") mode, the keystroke goes to the textarea — Enter confirms the
1351 // custom answer, Esc backs out of typing — so input/IME work as usual.
1352 if m.elicit != nil {
1353 if model, cmd, handled := m.elicitKey(msg, cmds); handled {
1354 return model, cmd
1355 }
1356 }
1357 if m.chooser != nil {
1358 if m.chooser.typing {
1359 switch msg.String() {
1360 case "enter":
1361 val := strings.TrimSpace(m.input.Value())
1362 m.resetComposerInput()
1363 m.chooser.typing = false
1364 m.refreshInputPlaceholder()
1365 if val == "" {
1366 return m, finalize(m, cmds)
1367 }
1368 m.chooser.custom[m.chooser.tab] = val
1369 m.chooser.sel[m.chooser.tab] = map[int]bool{}
1370 return m.chooserAdvance()
1371 case "esc":
1372 m.chooser.typing = false
1373 m.resetComposerInput()
1374 m.refreshInputPlaceholder()
1375 return m, finalize(m, cmds)
1376 }
1377 beforeInput := m.input.Value()
1378 var ic tea.Cmd
1379 m.input, ic = m.input.Update(msg)
1380 cmds = append(cmds, ic)
1381 m.growInputToFit()
1382 if shouldClearWideInputChange(beforeInput, m.input.Value()) {
1383 cmds = append(cmds, tea.ClearScreen)
1384 }
1385 return m, finalize(m, cmds)
1386 }
1387 return m.handleChooserKey(msg)
1388 }
1389 // The rewind picker is modal while open: keys navigate it.
1390 if m.rewind != nil {
1391 return m.handleRewindKey(msg)
1392 }
1393 // The MCP import picker is modal while open: keys select candidates.
1394 if m.mcpImport != nil {
1395 return m.handleMCPImportKey(msg)
1396 }
1397 // Copy picker is modal while open.
1398 if m.copyPick != nil {
1399 return m.handleCopyPickerKey(msg)
1400 }
1401 // The resume picker is modal while open: keys navigate it.
1402 if m.resumePick != nil {
1403 return m.handleResumePickerKey(msg)
1404 }
1405 // Searchable command pickers are modal while open.
1406 if m.quickPick != nil {
1407 return m.handleQuickPickerKey(msg)
1408 }
1409 if m.setup != nil {
1410 return m.handleConnectionSetupKey(msg)
1411 }
1412 // The MCP manager is modal while open: keys navigate it.
1413 if m.mcp != nil {
1414 return m.handleMCPManagerKey(msg)
1415 }
1416 // The destructive /clear confirmation is modal while open.
1417 if m.clearConfirm != nil {
1418 return m.handleClearConfirmKey(msg)
1419 }
1420 // The skill picker is modal while open: keys navigate it.
1421 if m.skillPick != nil {
1422 return m.handleSkillPickerKey(msg)
1423 }
1424 // A pending tool approval is modal: keystrokes answer it (y/a/n, Enter,
1425 // Esc) rather than reaching the input.
1426 if m.pendingApproval != nil {
1427 return m.handleApprovalKey(msg)
1428 }
1429 // While the autocomplete menu is open it captures navigation/accept keys
1430 // (↑/↓ move, Tab/Enter accept, Esc close); everything else falls through
1431 // to the textarea and re-filters the menu at the end of Update.
1432 if m.completion.active {
1433 switch msg.String() {
1434 case "up", "ctrl+p":
1435 m.moveCompletion(-1)
1436 return m, nil
1437 case "down", "ctrl+n":
1438 m.moveCompletion(1)
1439 return m, nil
1440 case "tab", "enter":
1441 if msg.String() == "enter" && (m.completionExactLabel() || m.completionBareOverlayCommand()) {
1442 m.dismissCompletion()
1443 break // fall through to regular Enter and submit the command
1444 }
1445 // When Enter is pressed and the selected completion is already fully
1446 // present in the input, close the menu and submit instead of accepting
1447 // the same item again (/resume 1 still has /resume 10 as a prefix match).
1448 if msg.String() == "enter" && m.completionSelectedInsertPresent() {
1449 m.dismissCompletion()
1450 break // fall through to regular Enter
1451 }
1452 m.acceptCompletion()
1453 return m, nil
1454 case "esc":
1455 m.dismissCompletion()
1456 if m.state == tuiRunning {
1457 break // a turn is running — also cancel it via the main Esc handler
1458 }
1459 return m, nil
1460 }
1461 }
1462 switch msg.String() {
1463 case "up":
1464 if m.state == tuiRunning {
1465 if m.navigateQueue(-1) {
1466 return m, nil
1467 }
1468 } else if m.recallSubmittedInput(-1) {
1469 return m, nil
1470 }
1471 case "down":
1472 if m.state == tuiRunning {
1473 if m.navigateQueue(1) {
1474 return m, nil
1475 }
1476 } else if m.recallSubmittedInput(1) {
1477 return m, nil
1478 }
1479 case "alt+up", "meta+up":
1480 if m.handleQueueReorder(-1) {
1481 return m, finalize(m, cmds)
1482 }
1483 case "alt+down", "meta+down":
1484 if m.handleQueueReorder(1) {
1485 return m, finalize(m, cmds)
1486 }
1487 case " ":
1488 if m.inboxQueuedCount() > 0 && m.input.Value() == "" {
1489 m.toggleInboxPaused()
1490 return m, finalize(m, cmds)
1491 }
1492 case "r":
1493 if m.queueEditCursor >= 0 && m.inboxSelectedID != "" {
1494 if err := m.ctrl.RetryInboxItem(m.inboxSelectedID); err != nil {
1495 m.notice("retry: " + err.Error())
1496 } else {
1497 m.notice("retry queued #" + shortID(m.inboxSelectedID))
1498 }
1499 return m, finalize(m, cmds)
1500 }
1501 case "d":
1502 if m.queueEditCursor >= 0 && m.inboxSelectedID != "" {
1503 if !m.queueConfirmDelete {
1504 m.queueConfirmDelete = true
1505 m.notice("press d again to delete #" + shortID(m.inboxSelectedID))
1506 return m, finalize(m, cmds)
1507 }
1508 if err := m.ctrl.DeleteInboxItem(m.inboxSelectedID); err != nil {
1509 m.notice("delete: " + err.Error())
1510 } else {
1511 m.notice("deleted #" + shortID(m.inboxSelectedID))
1512 }
1513 m.resetQueueNavigation()
1514 return m, finalize(m, cmds)
1515 }
1516 case "enter":
1517 // Don't reset queue navigation — the Enter handler below needs
1518 // queueEditCursor to decide whether to save an edit or enqueue.
1519 default:
1520 // Preserve queue navigation while the user is editing a queued
1521 // item — only reset when they're not browsing the queue, so that
1522 // typing replacement text keeps queueEditCursor alive for the
1523 // Enter handler to save the edit in-place. (#4877)
1524 if m.queueEditCursor < 0 {
1525 m.resetQueueNavigation()
1526 } else {
1527 m.queueConfirmDelete = false
1528 }
1529 }
1530 if imagePasteShortcut(msg.String(), runtime.GOOS) {
1531 if m.state == tuiRunning {
1532 return m, nil
1533 }
1534 if cmd := m.beginClipboardImagePaste(); cmd != nil {
1535 cmds = append(cmds, cmd)
1536 }
1537 return m, finalize(m, cmds)
1538 }
1539 // Shift+Insert is the classic terminal paste key. Most terminals
1540 // intercept it themselves and deliver the clipboard text as bracketed
1541 // paste (tea.PasteMsg); some forward the key sequence instead (e.g. via
1542 // the kitty keyboard protocol). Bind it explicitly so paste works
1543 // either way — same native-clipboard read path as right-click, so SSH
1544 // sessions get the same remote hint and never read the remote host's
1545 // clipboard.
1546 if msg.String() == "shift+insert" {
1547 cmds = append(cmds, pasteClipboardText())
1548 return m, finalize(m, cmds)
1549 }
1550 // Mode shortcuts share one dispatcher so terminal-specific Shift+Tab
1551 // encodings and Ctrl+Y stay consistent without duplicating state logic.
1552 if m.handleModeShortcut(msg.String()) {
1553 return m, nil
1554 }
1555 switch m.endSlashArgSnapshotForKey(msg.String()) {
1556 case "esc":
1557 // "Back out" of the most specific in-progress state: un-send a just-sent
1558 // turn (server not yet replied), cancel a streaming turn, or clear
1559 // typed-but-unsent input. Mode switches (normal/plan/YOLO) are
1560 // exclusively driven by Shift+Tab — Esc must not silently flip a
1561 // session from plan or YOLO back to a less-permissive mode. PR #3051
1562 // removed the YOLO half of this; plan mode was missed and is fixed
1563 // here. Scrollback is the terminal's now, so there's no viewport to
1564 // dismiss.
1565 switch {
1566 case m.maintenanceCancellable():
1567 m.stopMaintenance()
1568 case m.maintenance != nil:
1569 // A projection already being saved cannot be rolled back. Keep
1570 // the draft intact while the authoritative operation settles.
1571 case m.state == tuiRunning && m.bubblePending:
1572 m.unsendPending()
1573 case m.state == tuiRunning:
1574 m.ctrl.Cancel()
1575 // Defensive: if the controller is no longer running (cancel
1576 // completed synchronously, e.g. for shell commands), transition
1577 // to idle immediately instead of waiting for TurnDone.
1578 if !m.ctrl.Running() {
1579 m.state = tuiIdle
1580 m.confirmBubbleSent()
1581 m.noteWatchdogIdle()
1582 }
1583 default:
1584 // Idle (any mode): a double-Esc on an empty composer opens the
1585 // rewind picker (Claude Code's gesture); a first Esc just arms
1586 // it. Non-empty input clears as before.
1587 if strings.TrimSpace(m.input.Value()) == "" {
1588 if !m.lastEsc.IsZero() && time.Since(m.lastEsc) < 600*time.Millisecond {
1589 m.lastEsc = time.Time{}
1590 m.openRewind()
1591 } else {
1592 m.lastEsc = time.Now()
1593 }
1594 } else {
1595 m.resetComposerInput()
1596 m.pastedBlocks = nil
1597 }
1598 }
1599 return m, nil
1600 case "ctrl+insert":
1601 // Terminal-convention copy without Ctrl+C's destructive side
1602 // effects: copy an active selection if there is one, otherwise do
1603 // nothing (no clear-input, no cancel, no quit). The selection lives
1604 // in-app because Reasonix owns the mouse, so the terminal's own
1605 // Ctrl+Insert (which copies the terminal selection) would see an
1606 // empty one.
1607 if sel.active && !sel.empty() {
1608 m.sel = sel // restore so selectedText() can read it
1609 text := m.selectedText()
1610 m.sel = selection{}
1611 cmds = append(cmds, m.copySelectionWithNotice(text))
1612 return m, finalize(m, cmds)
1613 }
1614 return m, nil
1615 case "ctrl+c", "super+c", "meta+c":
1616 if m.state == tuiRunning {
1617 // Selection takes precedence: copy instead of cancel, same as idle.
1618 if sel.active && !sel.empty() {
1619 m.sel = sel
1620 text := m.selectedText()
1621 m.sel = selection{}
1622 cmds = append(cmds, m.copySelectionWithNotice(text))
1623 return m, finalize(m, cmds)
1624 }
1625 if m.bubblePending {
1626 m.unsendPending() // server not yet replied — restore text, leave no trace
1627 } else if m.cancelRequested() {
1628 m.ctrl.Cancel()
1629 return m, shutdownNow
1630 } else {
1631 m.ctrl.Cancel()
1632 }
1633 return m, nil
1634 }
1635 // Idle: an active text selection takes precedence over the
1636 // composer-clear / double-press-quit gestures. Standard terminal
1637 // convention is "Ctrl+C copies the selection" — the user can still
1638 // clear the input with a second Ctrl+C once the selection is gone.
1639 // Hoisting this branch above the clear branch also stops the
1640 // previous behaviour where Ctrl+C would dismiss a selection AND
1641 // wipe any draft text the user was typing — felt like the
1642 // selection was being silently lost.
1643 if sel.active && !sel.empty() {
1644 m.sel = sel // restore so selectedText() can read it
1645 text := m.selectedText()
1646 m.sel = selection{}
1647 cmds = append(cmds, m.copySelectionWithNotice(text))
1648 return m, finalize(m, cmds)
1649 }
1650 // No selection: if the composer has text, a single press clears it
1651 // (like Esc); on an empty composer a double-press within 1.5s quits.
1652 if strings.TrimSpace(m.input.Value()) != "" {
1653 m.resetComposerInput()
1654 m.pastedBlocks = nil
1655 m.lastCtrlCAt = time.Time{}
1656 return m, nil
1657 }
1658 if !m.lastCtrlCAt.IsZero() && time.Since(m.lastCtrlCAt) < 1500*time.Millisecond {
1659 return m, shutdownNow
1660 }
1661 m.lastCtrlCAt = time.Now()
1662 m.notice(i18n.M.CtrlCQuitHint)
1663 return m, finalize(m, nil)
1664 case "ctrl+d":
1665 // Compatible Ctrl+D: forward-delete when the composer has any
1666 // raw content (including whitespace-only); only quit when idle
1667 // with a truly empty composer (bash/readline-style EOF).
1668 if m.input.Value() != "" {
1669 // Delegate to textarea DeleteCharacterForward (bound to
1670 // ctrl+d by default) so mid-line forward delete works.
1671 var ic tea.Cmd
1672 m.input, ic = m.input.Update(msg)
1673 if ic != nil {
1674 cmds = append(cmds, ic)
1675 }
1676 m.growInputToFit()
1677 m.updateCompletion()
1678 return m, finalize(m, cmds)
1679 }
1680 if m.state == tuiIdle {
1681 return m, shutdownNow
1682 }
1683 return m, nil
1684 case "ctrl+l":
1685 if m.state != tuiRunning {
1686 m.finalizeStreamed()
1687 m.clearTranscriptDisplay()
1688 m.commitTranscriptSource(transcriptSource{kind: transcriptSourceBanner})
1689 m.transcriptDirty = true
1690 m.forceGotoBottom = true
1691 m.notice(i18n.M.SlashClsDone)
1692 }
1693 return m, finalize(m, cmds)
1694 case "ctrl+o":
1695 m.toggleVerboseReasoning(m.state != tuiRunning)
1696 return m, finalize(m, cmds)
1697 case "ctrl+b":
1698 m.toggleShellOutput()
1699 return m, finalize(m, cmds)
1700 case "ctrl+enter":
1701 // Durable mid-turn steer (terminals without modified Enter use /steer).
1702 if m.state == tuiRunning {
1703 line := strings.TrimSpace(m.input.Value())
1704 if line == "" {
1705 return m, nil
1706 }
1707 // Local /queue always, even while running.
1708 if handled, msg := m.handleQueueSlash(line); handled {
1709 m.notice(msg)
1710 m.resetComposerInput()
1711 m.pastedBlocks = nil
1712 return m, finalize(m, cmds)
1713 }
1714 body := m.expandPastedBlocks(line)
1715 rec, err := m.enqueueSteer(body, body)
1716 if err != nil {
1717 m.notice("steer: " + err.Error())
1718 // Keep composer text on durable failure.
1719 return m, finalize(m, cmds)
1720 }
1721 switch rec.Disposition {
1722 case sessioninbox.DispositionSteerAccepted:
1723 m.notice(fmt.Sprintf("steer accepted #%s", shortID(rec.ItemID)))
1724 case sessioninbox.DispositionQueuedFollowup:
1725 m.notice(fmt.Sprintf("steer rejected — durable follow-up #%s", shortID(rec.ItemID)))
1726 default:
1727 m.notice(fmt.Sprintf("queued #%s", shortID(rec.ItemID)))
1728 }
1729 m.resetComposerInput()
1730 m.pastedBlocks = nil
1731 m.resetQueueNavigation()
1732 return m, finalize(m, cmds)
1733 }
1734 case "enter":
1735 if m.state == tuiRunning {
1736 line := strings.TrimSpace(m.input.Value())
1737 if line == "" {
1738 m.viewport.GotoBottom()
1739 m.markFollowTail()
1740 return m, nil
1741 }
1742 // /queue and /steer are local commands even mid-turn.
1743 if handled, msg := m.handleQueueSlash(line); handled {
1744 m.notice(msg)
1745 m.resetComposerInput()
1746 m.pastedBlocks = nil
1747 return m, finalize(m, cmds)
1748 }
1749 body := m.expandPastedBlocks(line)
1750 items := m.inboxPreviews()
1751 if m.queueEditCursor >= 0 && m.queueEditCursor < len(items) {
1752 id := items[m.queueEditCursor].ID
1753 if _, err := m.ctrl.UpdateInboxItem(id, body, body, body); err != nil {
1754 m.notice("queue update: " + err.Error())
1755 return m, finalize(m, cmds)
1756 }
1757 m.notice(fmt.Sprintf("queue [%d] updated", m.queueEditCursor+1))
1758 m.resetQueueNavigation()
1759 } else {
1760 rec, err := m.enqueueFollowup(body, body)
1761 if err != nil {
1762 m.notice("queue: " + err.Error())
1763 // Keep composer text on durable failure / capacity.
1764 return m, finalize(m, cmds)
1765 }
1766 m.notice(fmt.Sprintf("durable follow-up queued #%s — will run when idle", shortID(rec.ItemID)))
1767 m.resetQueueNavigation()
1768 }
1769 m.resetComposerInput()
1770 m.pastedBlocks = nil
1771 return m, finalize(m, cmds)
1772 }
1773 if m.modelSwitchPending {
1774 return m, nil // ignore Enter while /model switch is building
1775 }
1776 line := strings.TrimSpace(m.input.Value())
1777
1778 if line == "" {
1779 m.viewport.GotoBottom()
1780 m.markFollowTail()
1781 return m, nil
1782 }
1783 if line == "exit" || line == "quit" || line == ":q" {
1784 return m, shutdownNow
1785 }
1786 if m.reclaimBlocksInput(line) {
1787 return m, finalize(m, cmds)
1788 }
1789 // /queue and /steer are local even when idle (never model-prompted).
1790 if handled, msg := m.handleQueueSlash(line); handled {
1791 m.notice(msg)
1792 m.resetComposerInput()
1793 m.pastedBlocks = nil
1794 return m, finalize(m, cmds)
1795 }
1796 m.rememberSubmittedInput(line)
1797
1798 // "# <note>" quick-adds a memory line locally, no model turn. The
1799 // space keeps "#7" / "#issue" prompts from being swallowed.
1800 if note, ok := control.MemoryQuickAddNote(line); ok {
1801 m.resetComposerInput()
1802 m.pastedBlocks = nil
1803 if note == "" {
1804 m.notice(i18n.M.QuickRememberEmpty)
1805 } else if path, err := m.ctrl.QuickAdd(memory.ScopeProject, note); err != nil {
1806 m.notice("memory: " + err.Error())
1807 } else {
1808 m.notice(fmt.Sprintf(i18n.M.QuickRememberDoneFmt, path))
1809 }
1810 return m, finalize(m, cmds)
1811 }
1812
1813 // "!<cmd>" runs a shell command directly, bypassing the model.
1814 if after, ok := strings.CutPrefix(line, "!"); ok {
1815 cmd := after
1816 if strings.TrimSpace(cmd) == "" {
1817 m.resetComposerInput()
1818 m.pastedBlocks = nil
1819 m.notice(i18n.M.ShellExecEmpty)
1820 return m, finalize(m, cmds)
1821 }
1822 m.resetComposerInput()
1823 m.pastedBlocks = nil
1824 m.state = tuiRunning
1825 m.runStart = time.Now()
1826 m.elapsed = 0
1827 m.turnTokens = 0
1828 m.pendingRestore = line
1829 m.bubbleStartIdx = len(m.transcript)
1830 m.commitLine("")
1831 m.commitTranscriptSource(transcriptSource{
1832 kind: transcriptSourceUser, raw: line, planMode: m.planMode,
1833 })
1834 m.bubblePending = true
1835 m.turnDiscarded = false
1836 m.confirmBubbleSent() // shell events arrive instantly
1837 m.noteWatchdogRunning()
1838 m.ctrl.RunShell(cmd)
1839 return m, m.startRunningTicks()
1840 }
1841
1842 // Slash commands run locally without going through the model. A
1843 // '/'-leading line that's actually a dragged file path is an attachment,
1844 // not a command, so it's rewritten to an @reference instead.
1845 if control.SlashCodeCommentLine(line) {
1846 // Slash-prefixed code comments are prompt text, not commands.
1847 // Not a command. Fall through to normal message path.
1848 } else if strings.HasPrefix(line, "/") {
1849 if ref, ok := control.FileRefLine(line); ok {
1850 line = ref
1851 } else {
1852 m.resetComposerInput()
1853 m.pastedBlocks = nil
1854 cmds = append(cmds, m.runSlashCommand(line))
1855 return m, finalize(m, cmds)
1856 }
1857 }
1858
1859 sentLine := m.expandPastedBlocks(line)
1860 m.resetComposerInput()
1861
1862 // @references (local files / MCP resources, including inline image
1863 // attachments) are resolved off the event loop by the controller; the turn
1864 // starts when they resolve (refsResolvedMsg).
1865 if m.ctrl.HasRefs(sentLine) {
1866 cmds = append(cmds, m.resolveRefs(sentLine, sentLine, line))
1867 return m, finalize(m, cmds)
1868 }
1869
1870 // Keep the expanded paste content as the raw turn, not the folded label,
1871 // so downstream consumers never see just the placeholder label.
1872 cmds = append(cmds, m.startTurnWithRaw(sentLine, sentLine, line, sentLine))
1873 return m, finalize(m, cmds)
1874 }
1875
1876 case agentEventMsg:
1877 e := event.Event(msg)
1878 drained := m.drainAgentEvents(e)
1879 cmds = append(cmds, waitForAgentEvent(m.eventCh))
1880 cmds = append(cmds, drained.cmds...)
1881 // A turn just spent tokens (and money) — refresh the balance readout and
1882 // the custom status line (its context/cost inputs just changed).
1883 if drained.turnDone {
1884 cmds = append(cmds, fetchBalance(m.ctrl))
1885 if c := m.runStatusline(); c != nil {
1886 cmds = append(cmds, c)
1887 }
1888 // Durable inbox dispatch is owned by the controller after TurnDone.
1889 // Reset local queue navigation when the snapshot changes.
1890 m.resetQueueNavigation()
1891 // A /reload typed while the turn ran fires now that the TUI may be
1892 // idle; the drain re-checks busy state (an inbox admission above or a
1893 // background job keeps it queued).
1894 if c := m.drainQueuedRuntimeReload(); c != nil {
1895 cmds = append(cmds, c)
1896 }
1897 }
1898 if drained.turnDone || drained.gitMaybeChanged {
1899 if c := m.refreshGitStatus(); c != nil {
1900 cmds = append(cmds, c)
1901 }
1902 }
1903
1904 case balanceMsg:
1905 m.balance = msg.text
1906
1907 case statuslineMsg:
1908 m.statuslineOut = msg.out
1909
1910 case gitStatusMsg:
1911 m.gitStatus = msg.status
1912
1913 case compactDoneMsg:
1914 if m.maintenance != nil && m.maintenance.OperationID == "" {
1915 m.maintenance = nil
1916 }
1917 if msg.err != nil && !m.compactLifecycleObserved {
1918 m.notice(fmt.Sprintf("%s: %v", i18n.M.SlashCompactFailed, msg.err))
1919 } else if msg.err == nil {
1920 m.followSessionLease()
1921 }
1922 m.compactLifecycleObserved = false
1923 m.compactCompatibilityPending = false
1924
1925 case tuiShutdownMsg:
1926 return m.shutdownAndQuit(msg)
1927
1928 case tuiSessionReclaimedMsg:
1929 return m.completeSessionReclaim()
1930
1931 case turnModelSettingsMsg:
1932 return m, m.handleTurnModelSettings(msg)
1933 case modelSwitchMsg:
1934 cmds = append(cmds, m.handleModelSwitch(msg)...)
1935
1936 case connectionCredentialSavedMsg:
1937 return m, m.handleConnectionCredentialSaved(msg)
1938 case connectionCredentialTestedMsg:
1939 m.handleConnectionCredentialTested(msg)
1940 return m, nil
1941
1942 case promptResolvedMsg:
1943 switch {
1944 case msg.err != nil:
1945 m.commitLine(wrapForViewport(i18n.M.ErrorPrefix+" "+msg.err.Error(), m.width, activeCLITheme.warn))
1946 case strings.TrimSpace(msg.sent) == "":
1947 m.notice(i18n.M.SlashPromptEmpty)
1948 default:
1949 cmds = append(cmds, m.startTurn(msg.sent, msg.display, msg.display))
1950 }
1951
1952 case extensionActionMsg:
1953 switch {
1954 case msg.err != nil:
1955 m.commitLine(wrapForViewport(i18n.M.ErrorPrefix+" "+msg.err.Error(), m.width, activeCLITheme.warn))
1956 case strings.TrimSpace(msg.message) != "":
1957 m.notice(msg.message)
1958 }
1959
1960 case mcpExternalDoneMsg:
1961 if cmd := m.handleMCPExternalDone(msg); cmd != nil {
1962 cmds = append(cmds, cmd)
1963 }
1964
1965 case mcpConnectDoneMsg:
1966 m.handleMCPConnectDone(msg)
1967
1968 case refsResolvedMsg:
1969 for _, e := range msg.errs {
1970 m.notice(e) // surface a fetch failure but still send the turn
1971 }
1972 sent := msg.sent
1973 if msg.block != "" {
1974 sent = "Referenced context:\n\n" + msg.block + "\n\n" + msg.sent
1975 }
1976 // raw = msg.display (the expanded paste content, without resolved @-ref
1977 // payloads) — NOT msg.restore (the folded label). See the non-refs branch
1978 // above for why raw needs the expansion.
1979 cmds = append(cmds, m.startTurnWithRaw(sent, msg.display, msg.restore, msg.display))
1980
1981 case clipboardImageMsg:
1982 requests := max(m.clipboardImageRequests, 1)
1983 m.clipboardImagePending = false
1984 m.clipboardImageRequests = 0
1985 if msg.err != nil {
1986 // An empty image clipboard is the normal case for a text paste on
1987 // terminals that hand Ctrl+V to the application instead of pasting
1988 // themselves. Fall through to text rather than blocking the paste.
1989 if errors.Is(msg.err, control.ErrNoClipboardImage) {
1990 // Skip the fallback when the terminal already delivered a
1991 // bracketed paste for this key press; it owns the paste and
1992 // pasting again would duplicate the text.
1993 pending := pendingClipboardTextPastes(requests, m.clipboardImageTerminalPasteSeq, m.terminalPasteSeq)
1994 if pending > 0 {
1995 cmds = append(cmds, pasteClipboardTextGuarded(m.terminalPasteSeq, pending, msg.err))
1996 }
1997 break
1998 }
1999 m.notice(fmt.Sprintf(i18n.M.ClipboardImagePasteFailedFmt, sanitizeExternalDisplayText(msg.err.Error())))
2000 break
2001 }
2002 imageBefore := m.input.Value()
2003 m.insertImageRef(msg.path)
2004 if shouldClearWideInputChange(imageBefore, m.input.Value()) {
2005 cmds = append(cmds, tea.ClearScreen)
2006 }
2007
2008 case clipboardTextPasteMsg:
2009 return m.handleClipboardTextPaste(msg)
2010
2011 case clipboardCopyMsg:
2012 if msg.statusHint && msg.seq != m.copyNoticeSeq {
2013 break
2014 }
2015 label := i18n.M.MouseCopiedHint
2016 if !msg.statusHint {
2017 label = i18n.M.SlashCopyDone
2018 }
2019 if msg.osc52 || msg.err != nil {
2020 label = i18n.M.ClipboardCopyOSC52Hint
2021 if msg.err != nil {
2022 label = i18n.M.ClipboardCopyFallbackHint
2023 }
2024 cmds = append(cmds, tea.SetClipboard(msg.text))
2025 }
2026 if msg.statusHint {
2027 m.copyNoticeText = label
2028 cmds = append(cmds, copyNoticeExpire(msg.seq))
2029 } else {
2030 m.notice(label)
2031 }
2032
2033 case copyNoticeExpireMsg:
2034 if msg.seq == m.copyNoticeSeq {
2035 m.copyNoticeText = ""
2036 }
2037
2038 case themeSweepTickMsg:
2039 if m.themeSweep != nil {
2040 if m.themeSweep.advance() {
2041 cmds = append(cmds, themeSweepTick())
2042 } else {
2043 m.themeSweep = nil
2044 }
2045 }
2046
2047 case elapsedTickMsg:
2048 if m.state == tuiRunning && msg.generation == m.elapsedTickGeneration {
2049 // elapsedTick is the primary active-turn heartbeat: long turns that
2050 // emit no agent events still prove the Bubble Tea loop is alive.
2051 m.noteWatchdogHeartbeat("elapsed_tick")
2052 m.elapsed = int(time.Since(m.runStart).Seconds())
2053 m.tickToolRunning()
2054 m.tickSubagentProgress()
2055 cmds = append(cmds, elapsedTick(msg.generation))
2056 }
2057
2058 case spinner.TickMsg:
2059 if m.state == tuiRunning {
2060 var cmd tea.Cmd
2061 m.spinner, cmd = m.spinner.Update(msg)
2062 cmds = append(cmds, cmd)
2063 }
2064 }
2065
2066 beforeInput := m.input.Value()
2067 if inputBeforeSelection != "" {
2068 beforeInput = inputBeforeSelection
2069 }
2070 var ic tea.Cmd
2071 m.input, ic = m.input.Update(msg)
2072 cmds = append(cmds, ic)
2073 m.growInputToFit()
2074 // Re-filter the autocomplete menu against the freshly-edited input.
2075 if _, ok := msg.(tea.KeyPressMsg); ok {
2076 m.updateCompletion()
2077 }
2078 if shouldClearWideInputChange(beforeInput, m.input.Value()) {
2079 cmds = append(cmds, tea.ClearScreen)
2080 }
2081
2082 return m, finalize(m, cmds)
2083 }
2084
2085 var clearWideInputChanges = runtime.GOOS == "windows"
2086
2087 func shouldClearWideInputChange(before, after string) bool {
2088 return clearWideInputChanges &&
2089 before != after &&
2090 (hasWideInputCells(before) || hasWideInputCells(after))
2091 }
2092
2093 func hasWideInputCells(s string) bool {
2094 return s != "" && visibleWidth(s) != utf8.RuneCountInString(s)
2095 }
2096
2097 // finalize drains the committed-line queue and batches the turn's commands. In
2098 // the default alt-screen path the queue is already mirrored in m.transcript. In
2099 // Termux finalized lines are also emitted into the terminal's native scrollback.
2100 func finalize(m chatTUI, cmds []tea.Cmd) tea.Cmd {
2101 if m.nativeScrollback && len(*m.pendingCommit) > 0 {
2102 out := strings.TrimRight(clampWidth(strings.Join(*m.pendingCommit, "\n"), m.width), "\n")
2103 *m.pendingCommit = (*m.pendingCommit)[:0]
2104 var prints []tea.Cmd
2105 for _, chunk := range chunkLines(out, m.scrollChunkHeight()) {
2106 prints = append(prints, tea.Println(chunk))
2107 }
2108 cmds = append(cmds, tea.Sequence(prints...))
2109 return tea.Batch(cmds...)
2110 }
2111 *m.pendingCommit = (*m.pendingCommit)[:0]
2112 return tea.Batch(cmds...)
2113 }
2114
2115 func (m *chatTUI) clearTranscriptDisplay() {
2116 if m.pendingCommit != nil {
2117 *m.pendingCommit = (*m.pendingCommit)[:0]
2118 }
2119 m.transcript = nil
2120 m.transcriptSources = nil
2121 m.clearWrapCache()
2122 m.viewport.SetContent("")
2123 m.shellOutputs = make(map[string]string)
2124 m.shellExpanded = make(map[string]bool)
2125 m.shellTranscriptIdx = make(map[string]int)
2126 m.toolLineCountByID = make(map[string]int)
2127 m.subagentProgressIdx = make(map[string]int)
2128 m.subagentProgress = make(map[string]*cliSubagentProgress)
2129 m.toolStreamID = ""
2130 m.toolStreamIdx = -1
2131 m.toolTail = nil
2132 m.toolPartial = ""
2133 m.toolLineCount = 0
2134 }
2135
2136 // scrollChunkHeight is the largest block (in lines) finalize prints at once in
2137 // native-scrollback mode, leaving room for the pinned bottom frame.
2138 func (m chatTUI) scrollChunkHeight() int {
2139 if m.height <= 0 {
2140 return 100
2141 }
2142 if n := m.height - m.bottomRows(); n > 1 {
2143 return n
2144 }
2145 return 1
2146 }
2147
2148 // chunkLines splits s into blocks of at most n lines each, preserving order and
2149 // line content. A single block is returned when it already fits.
2150 func chunkLines(s string, n int) []string {
2151 if n < 1 {
2152 n = 1
2153 }
2154 lines := strings.Split(s, "\n")
2155 if len(lines) <= n {
2156 return []string{s}
2157 }
2158 var out []string
2159 for i := 0; i < len(lines); i += n {
2160 end := min(i+n, len(lines))
2161 out = append(out, strings.Join(lines[i:end], "\n"))
2162 }
2163 return out
2164 }
2165
2166 // clampWidth hard-breaks any line wider than width so no scrollback line wraps
2167 // in the terminal. bubbletea's inline renderer estimates how far to scroll for
2168 // each printed block from each line's width (insertAbove: offset += width/w); an
2169 // over-wide line that the terminal wraps throws that estimate off and drifts the
2170 // pinned input box off-screen. Lines already within width are left byte-for-byte
2171 // untouched (chunkByWidth preserves content and ANSI), so rendered tables and the
2172 // wrapped answer — which the markdown renderer already fit to width — are safe;
2173 // only stray long lines (tool-dispatch args, unwrapped code) get broken.
2174 func clampWidth(s string, width int) string {
2175 if width <= 0 {
2176 return s
2177 }
2178 return hardwrapTerminalText(s, width)
2179 }
2180
2181 // commitLine queues one finalized block for the next scrollback flush.
2182 func (m *chatTUI) commitLine(s string) {
2183 *m.pendingCommit = append(*m.pendingCommit, s)
2184 m.appendTranscriptBlock(s, transcriptSource{kind: transcriptSourceFixed})
2185 }
2186
2187 // commitSpacer separates the next block (a thinking marker or a tool line) from
2188 // the previous one with a single blank line, skipping it at the top of the
2189 // transcript or when a blank already trails so spacers never double up.
2190 func (m *chatTUI) commitSpacer() {
2191 if n := len(m.transcript); n > 0 && strings.TrimSpace(m.transcript[n-1]) != "" {
2192 m.commitLine("")
2193 }
2194 }
2195
2196 // bottomRows is the terminal-row height of the pinned bottom region: any open
2197 // bottom panels (todo / approval / chooser / rewind / completion), the composer
2198 // when visible, and the two fixed status rows. Full-screen managers such as MCP
2199 // and skills normally render inside the main transcript area; in native
2200 // scrollback mode they join the bottom rail because there is no main viewport.
2201 func (m chatTUI) bottomRows() int {
2202 return m.pinnedPanelView().height() + m.protectedBottomRows()
2203 }
2204
2205 // protectedBottomRows is shared by panel sizing and transcript/composer sizing.
2206 // The status count already includes the independently wrapped working line.
2207 func (m chatTUI) protectedBottomRows() int {
2208 rows := 0
2209 if footer := m.renderMainManagerFooter(); footer != "" {
2210 rows += strings.Count(footer, "\n") + 1
2211 }
2212 if !m.hideComposer() {
2213 rows += m.input.Height() + 2
2214 if queue := m.renderQueueIndicator(); queue != "" {
2215 rows += strings.Count(queue, "\n") + 1
2216 }
2217 }
2218 if m.statusLineCount > 0 {
2219 return rows + m.statusLineCount
2220 }
2221 return rows + 2 // fallback for tests that don't set statusLineCount
2222 }
2223
2224 // hideComposer is the single ownership gate for the bottom composer.
2225 //
2226 // Rule for new CLI panels:
2227 // - If a panel is modal and keystrokes navigate/confirm/cancel the panel, hide
2228 // the composer so users do not see an inactive chat input.
2229 // - If a panel is input-owned (autocomplete, or chooser free-text mode), keep
2230 // the composer visible because the textarea is the active control.
2231 //
2232 // Whenever a new slash-command overlay or approval-style prompt is added, update
2233 // this function and the modal layout tests together. Otherwise the panel may
2234 // reserve rows for a composer that cannot receive input, leaving a confusing
2235 // blank/bordered area at the bottom of the TUI.
2236 func (m chatTUI) hideComposer() bool {
2237 if m.mcp != nil || m.clearConfirm != nil || m.mcpImport != nil || m.skillPick != nil || m.resumePick != nil || m.quickPick != nil || m.setup != nil || m.copyPick != nil || m.rewind != nil || m.pendingApproval != nil {
2238 return true
2239 }
2240 return (m.chooser != nil && !m.chooser.typing) || (m.elicit != nil && !m.elicit.typing)
2241 }
2242
2243 // transcriptHeight is the row budget left for the transcript viewport once the
2244 // pinned bottom region is accounted for (at least one row).
2245 func (m chatTUI) transcriptHeight() int {
2246 if h := m.height - m.bottomRows(); h > 1 {
2247 return h
2248 }
2249 return 1
2250 }
2251
2252 func (m chatTUI) renderMainManager() string {
2253 return m.renderMainManagerPanel().text
2254 }
2255
2256 func (m chatTUI) renderMainManagerPanel() panelContent {
2257 if card := m.renderMCPManagerPanel(); card.text != "" {
2258 return card
2259 }
2260 if card := m.renderClearConfirmPanel(); card.text != "" {
2261 return card
2262 }
2263 return m.renderSkillPickerPanel()
2264 }
2265
2266 func managerContentPanelStyle(width int) lipgloss.Style {
2267 return choicePanelStyle.
2268 Border(lipgloss.NormalBorder(), true, false, false, false).
2269 Width(width)
2270 }
2271
2272 func managerFooterPanelStyle(width int) lipgloss.Style {
2273 return choicePanelStyle.
2274 Border(lipgloss.NormalBorder(), false, false, true, false).
2275 Width(width)
2276 }
2277
2278 func (m chatTUI) renderMainManagerFooter() string {
2279 hint := ""
2280 switch {
2281 case m.mcp != nil:
2282 hint = m.mcp.footerHint()
2283 case m.clearConfirm != nil:
2284 hint = "Enter confirm · y clear · n/Esc cancel"
2285 case m.skillPick != nil:
2286 hint = m.skillPickerFooterHint()
2287 }
2288 if strings.TrimSpace(hint) == "" {
2289 return ""
2290 }
2291 w := max(viewWidth(m.width), 40)
2292 return managerFooterPanelStyle(w).Render(dim(hint))
2293 }
2294
2295 func (m chatTUI) renderTranscriptWithMainManager(card string) string {
2296 h := m.viewport.Height()
2297 if h <= 0 {
2298 return ""
2299 }
2300 cw := m.viewport.Width()
2301 if cw <= 0 {
2302 cw = max(m.width-1, 1)
2303 }
2304
2305 cardLines := strings.Split(strings.TrimRight(card, "\n"), "\n")
2306 if len(cardLines) > h {
2307 cardLines = cardLines[:h]
2308 }
2309 maxTranscriptRows := h - len(cardLines)
2310 if maxTranscriptRows > 0 && len(cardLines) > 0 && len(m.wrappedLines) > 0 {
2311 maxTranscriptRows--
2312 }
2313
2314 var rows []string
2315 if maxTranscriptRows > 0 {
2316 lines := m.wrappedLines
2317 start := max(0, len(lines)-maxTranscriptRows)
2318 rows = append(rows, lines[start:]...)
2319 }
2320 if len(rows) > 0 && len(cardLines) > 0 {
2321 rows = append(rows, "")
2322 }
2323 rows = append(rows, cardLines...)
2324 for len(rows) < h {
2325 rows = append(rows, "")
2326 }
2327 for i, row := range rows {
2328 rows[i] = padRight(ansi.Cut(row, 0, cw), cw)
2329 }
2330 return strings.Join(rows, "\n")
2331 }
2332
2333 // reasoningViewMax bounds the live thinking buffer the streamed block renders
2334 // from. Re-rendering the full chain of thought on every delta was O(n²) (a 2k-
2335 // token thought churned ~4.7GB); rendering only the trailing window keeps each
2336 // delta O(1). The full text still lives in m.reasoning for verbose mode.
2337 const reasoningViewMax = 4096
2338
2339 // reasoningTailLines caps how many trailing visual lines the live block shows.
2340 const reasoningTailLines = 12
2341
2342 // streamReasoning appends a chunk and rewrites the live reasoning block from a
2343 // bounded trailing view (mirrors streamToolOutput), so the chain of thought is
2344 // visible while the model works without re-rendering the whole thing per token.
2345 func (m *chatTUI) streamReasoning(chunk string) {
2346 m.reasoning.WriteString(chunk) // full text retained for verbose mode
2347 if m.reasoningTextIdx < 0 {
2348 return
2349 }
2350 m.reasoningView = append(m.reasoningView, chunk...)
2351 if len(m.reasoningView) > reasoningViewMax {
2352 drop := len(m.reasoningView) - reasoningViewMax
2353 for drop < len(m.reasoningView) && !utf8.RuneStart(m.reasoningView[drop]) {
2354 drop++
2355 }
2356 m.reasoningView = m.reasoningView[:copy(m.reasoningView, m.reasoningView[drop:])]
2357 }
2358 raw := string(m.reasoningView)
2359 m.setTranscriptBlock(m.reasoningTextIdx, reasoningBlock(raw, m.width, reasoningTailLines), transcriptSource{
2360 kind: transcriptSourceReasoning, raw: raw, maxLines: reasoningTailLines,
2361 })
2362 }
2363
2364 // reasoningBlock renders raw thinking text as dim, width-wrapped lines under a
2365 // "⎿" connector that ties the block to the "▎ thinking…" marker above it. A
2366 // positive maxLines keeps only the trailing visual lines (the live view); 0
2367 // renders all (verbose collapse).
2368 func reasoningBlock(raw string, width, maxLines int) string {
2369 return connectorBlock(reasoningBlockLines(raw, width, maxLines))
2370 }
2371
2372 // toolStreamTailLines caps how many trailing output lines a running tool shows;
2373 // the live block scrolls within this window so a chatty build doesn't flood.
2374 const toolStreamTailLines = 8
2375
2376 // shellPreviewLines is how many lines of shell output to show by default after
2377 // the command finishes. Ctrl+B toggles the full output.
2378 const shellPreviewLines = 10
2379
2380 // shellExpandMaxLines caps how many lines Ctrl+B shows in expanded mode, so a
2381 // very large output (e.g. thousands of lines) doesn't hang the TUI or push the
2382 // input box off-screen.
2383 const shellExpandMaxLines = 200
2384
2385 // streamToolOutput appends a chunk of a running tool's output and re-renders its
2386 // live block (the last toolStreamTailLines lines) under the tool card, opening
2387 // the block on the first chunk. Mirrors streamReasoning.
2388 func (m *chatTUI) streamToolOutput(id, chunk string) {
2389 if id == "" {
2390 return
2391 }
2392 if m.toolStreamID != id {
2393 // Switching to a different id means either:
2394 // (a) the previous tool finished and a new one is starting — collapse
2395 // the current id's live block, then append a fresh slot at the
2396 // end of the transcript.
2397 // (b) late ToolProgress for an earlier (already dispatched and
2398 // possibly collapsed) tool — reuse the slot beginToolRunning
2399 // already wrote for that id, so the live block stays directly
2400 // under the earlier tool's card rather than stacking at the end.
2401 if existingIdx, ok := m.shellTranscriptIdx[id]; ok && existingIdx >= 0 && existingIdx < len(m.transcript) {
2402 // Stash the switched-away id's live count before resetting it;
2403 // its late ToolResult reads it back via toolLineCountByID.
2404 if m.toolStreamID != "" && m.toolStreamID != id {
2405 n := m.toolLineCount
2406 if m.toolPartial != "" {
2407 n++
2408 }
2409 if n > 0 {
2410 m.toolLineCountByID[m.toolStreamID] = n
2411 }
2412 }
2413 m.toolStreamID = id
2414 m.toolStreamIdx = existingIdx
2415 m.toolTail = m.toolTail[:0]
2416 m.toolPartial = ""
2417 m.toolLineCount = 0
2418 } else {
2419 // Unknown id: collapse the active stream (its live count is intact).
2420 m.collapseToolOutput(m.toolStreamID, "")
2421 m.toolStreamID = id
2422 m.toolTail = m.toolTail[:0]
2423 m.toolPartial = ""
2424 m.toolLineCount = 0
2425 if m.nativeScrollback {
2426 m.toolStreamIdx = -1
2427 } else {
2428 m.toolStreamIdx = len(m.transcript)
2429 m.commitConnectorBlock(nil)
2430 }
2431 }
2432 }
2433 // Accumulate full output for shell commands so Ctrl+B can expand it.
2434 if strings.HasPrefix(id, "shell-") {
2435 m.shellOutputs[id] += chunk
2436 }
2437 // Fold completed lines into the bounded tail; keep the trailing partial.
2438 data := m.toolPartial + chunk
2439 for {
2440 i := strings.IndexByte(data, '\n')
2441 if i < 0 {
2442 break
2443 }
2444 m.pushToolLine(strings.TrimRight(data[:i], "\r"))
2445 data = data[i+1:]
2446 }
2447 m.toolPartial = data
2448
2449 vis := m.toolTail
2450 if m.toolPartial != "" {
2451 vis = append(append([]string{}, m.toolTail...), m.toolPartial)
2452 }
2453 if m.nativeScrollback {
2454 return
2455 }
2456 lines := make([]string, len(vis))
2457 for i, ln := range vis {
2458 lines[i] = dim(clampPlain(ln, m.width-len([]rune(connector))))
2459 }
2460 m.rewriteConnectorBlock(m.toolStreamIdx, lines)
2461 }
2462
2463 // pushToolLine appends a completed output line to the bounded tail, dropping the
2464 // oldest when it exceeds the window (the backing array stays ≤ window+1).
2465 func (m *chatTUI) pushToolLine(line string) {
2466 m.toolLineCount++
2467 m.toolTail = append(m.toolTail, line)
2468 if len(m.toolTail) > toolStreamTailLines {
2469 copy(m.toolTail, m.toolTail[1:])
2470 m.toolTail = m.toolTail[:toolStreamTailLines]
2471 }
2472 }
2473
2474 // subagentPreviewMax bounds each child's retained reasoning/text preview tail
2475 // (verbose mode renders from it); the notice tail is smaller.
2476 const (
2477 subagentPreviewMax = 4096
2478 subagentNoticeMax = 2048
2479 // subagentPreviewTailLines caps the trailing visual lines of a preview.
2480 subagentPreviewTailLines = 12
2481 )
2482
2483 // cliSubagentProgress is the per-child live state backing one fixed transcript
2484 // slot. Everything here is in-memory only: the persisted sub-agent transcript
2485 // remains the source of truth after a restart.
2486 type cliSubagentProgress struct {
2487 phase string
2488 startedAt time.Time
2489 lastActive time.Time
2490 reasoning string // bounded ≤ subagentPreviewMax, UTF-8-safe tail
2491 text string
2492 notice string
2493 truncated bool
2494 durationMs int64
2495 terminal bool
2496 lastPrintedPhase string // native-scrollback dedupe
2497 verboseLastPrint time.Time
2498 }
2499
2500 func subagentPhaseTerminal(phase string) bool {
2501 switch phase {
2502 case "completed", "failed", "cancelled":
2503 return true
2504 }
2505 return false
2506 }
2507
2508 // cliPreviewTail keeps the most recent maxBytes of s at a rune boundary.
2509 func cliPreviewTail(s string, maxBytes int) string {
2510 if len(s) <= maxBytes {
2511 return s
2512 }
2513 s = s[len(s)-maxBytes:]
2514 for len(s) > 0 && !utf8.RuneStart(s[0]) {
2515 s = s[1:]
2516 }
2517 return s
2518 }
2519
2520 // streamSubagentProgress routes reserved ToolProgress channels into per-child
2521 // progress state instead of the single live tool stream: each child keeps its
2522 // own phase, elapsed, recent activity, and (verbose-only) preview tails.
2523 func (m *chatTUI) streamSubagentProgress(t event.Tool) {
2524 if t.ID == "" {
2525 return
2526 }
2527 sp := m.subagentProgress[t.ID]
2528 if sp == nil {
2529 sp = &cliSubagentProgress{startedAt: time.Now()}
2530 m.subagentProgress[t.ID] = sp
2531 }
2532 sp.lastActive = time.Now()
2533 switch t.Name {
2534 case event.SubagentProgressStatusName:
2535 sp.phase = t.Output
2536 if t.DurationMs > 0 {
2537 sp.durationMs = t.DurationMs
2538 }
2539 sp.terminal = subagentPhaseTerminal(t.Output)
2540 m.renderSubagentProgress(t.ID)
2541 case event.SubagentProgressReasoningName:
2542 sp.reasoning = cliPreviewTail(sp.reasoning+t.Output, subagentPreviewMax)
2543 sp.truncated = sp.truncated || t.Truncated
2544 if m.showReasoning {
2545 m.renderSubagentProgress(t.ID)
2546 }
2547 case event.SubagentProgressTextName:
2548 sp.text = cliPreviewTail(sp.text+t.Output, subagentPreviewMax)
2549 sp.truncated = sp.truncated || t.Truncated
2550 if m.showReasoning {
2551 m.renderSubagentProgress(t.ID)
2552 }
2553 case event.SubagentProgressNoticeName:
2554 sp.notice = cliPreviewTail(sp.notice+t.Output, subagentNoticeMax)
2555 sp.truncated = sp.truncated || t.Truncated
2556 if m.showReasoning {
2557 m.renderSubagentProgress(t.ID)
2558 }
2559 }
2560 }
2561
2562 // renderSubagentProgress redraws a child's progress block. Alt-screen TUIs
2563 // rewrite the fixed transcript slot in place (created on first sight under the
2564 // current transcript end); native-scrollback terminals print a status line
2565 // only on phase changes and terminal, since printed output cannot be rewritten.
2566 func (m *chatTUI) renderSubagentProgress(id string) {
2567 sp := m.subagentProgress[id]
2568 if sp == nil || sp.phase == "" {
2569 return
2570 }
2571 if m.nativeScrollback {
2572 m.printSubagentProgressScrollback(id, sp)
2573 return
2574 }
2575 idx, ok := m.subagentProgressIdx[id]
2576 if !ok {
2577 idx = len(m.transcript)
2578 m.subagentProgressIdx[id] = idx
2579 m.commitLine(m.subagentProgressBlock(id, sp))
2580 return
2581 }
2582 m.setTranscriptBlock(idx, m.subagentProgressBlock(id, sp), transcriptSource{kind: transcriptSourceSubagentProgress, raw: id})
2583 }
2584
2585 // tickSubagentProgress refreshes the elapsed / recent-activity fields of live
2586 // progress blocks once a second (mirrors tickToolRunning), so a child that
2587 // produces no events still reads as alive.
2588 func (m *chatTUI) tickSubagentProgress() {
2589 if m.nativeScrollback {
2590 return
2591 }
2592 for id, sp := range m.subagentProgress {
2593 if sp.terminal || sp.phase == "" {
2594 continue
2595 }
2596 idx, ok := m.subagentProgressIdx[id]
2597 if !ok {
2598 continue
2599 }
2600 m.setTranscriptBlock(idx, m.subagentProgressBlock(id, sp), transcriptSource{kind: transcriptSourceSubagentProgress, raw: id})
2601 }
2602 }
2603
2604 // subagentProgressBlock renders one child's progress block. The default line
2605 // shows phase, running elapsed, and recent activity; verbose mode adds the
2606 // bounded reasoning/text/notice tails above it. Terminal children collapse to
2607 // a one-line summary (the preview survives in memory for verbose re-render).
2608 func (m *chatTUI) subagentProgressBlock(id string, sp *cliSubagentProgress) string {
2609 var lines []string
2610 if m.showReasoning {
2611 if sp.reasoning != "" {
2612 lines = append(lines, subagentPreviewBlock(i18n.M.ChatSubagentPreviewLabel, sp.reasoning, m.width, subagentPreviewTailLines))
2613 }
2614 if sp.text != "" {
2615 lines = append(lines, subagentPreviewBlock("✎", sp.text, m.width, subagentPreviewTailLines))
2616 }
2617 if sp.notice != "" {
2618 lines = append(lines, subagentPreviewBlock("!", sp.notice, m.width, subagentPreviewTailLines))
2619 }
2620 if sp.truncated {
2621 lines = append(lines, dim("… preview truncated"))
2622 }
2623 }
2624 label := subagentPhaseLabel(sp.phase)
2625 switch sp.phase {
2626 case "completed":
2627 label = green(label + " ✓")
2628 case "failed":
2629 label = red(label + " ✗")
2630 case "cancelled":
2631 label = dim(label + " ⊘")
2632 case "retrying":
2633 label = yellow(label)
2634 }
2635 if sp.terminal {
2636 secs := sp.durationMs / 1000
2637 if secs <= 0 && !sp.startedAt.IsZero() {
2638 secs = int64(time.Since(sp.startedAt).Seconds())
2639 }
2640 lines = append(lines, fmt.Sprintf(i18n.M.ChatSubagentProgressDoneFmt, label, secs))
2641 } else {
2642 elapsed := int64(0)
2643 idle := int64(0)
2644 if !sp.startedAt.IsZero() {
2645 elapsed = int64(time.Since(sp.startedAt).Seconds())
2646 }
2647 if !sp.lastActive.IsZero() {
2648 idle = int64(time.Since(sp.lastActive).Seconds())
2649 }
2650 lines = append(lines, fmt.Sprintf(i18n.M.ChatSubagentProgressFmt, label, elapsed, idle))
2651 }
2652 return connectorBlock(lines)
2653 }
2654
2655 // subagentPreviewBlock renders a bounded trailing window of a preview channel
2656 // as dim, width-wrapped lines carrying a small glyph marker.
2657 func subagentPreviewBlock(glyph, raw string, width, maxLines int) string {
2658 w := max(width-len([]rune(connector)), 8)
2659 var lines []string
2660 first := true
2661 for ln := range strings.SplitSeq(strings.TrimRight(raw, "\n"), "\n") {
2662 if first {
2663 ln = glyph + " " + ln
2664 first = false
2665 }
2666 for wl := range strings.SplitSeq(ansi.Wrap(expandTabs(ln), w, ""), "\n") {
2667 lines = append(lines, dim(wl))
2668 }
2669 }
2670 if maxLines > 0 && len(lines) > maxLines {
2671 lines = lines[len(lines)-maxLines:]
2672 }
2673 return strings.Join(lines, "\n")
2674 }
2675
2676 // subagentPhaseLabel maps a reserved status value to its localized label.
2677 func subagentPhaseLabel(phase string) string {
2678 switch phase {
2679 case "queued":
2680 return i18n.M.ChatSubagentPhaseQueued
2681 case "running":
2682 return i18n.M.ChatSubagentPhaseRunning
2683 case "reasoning":
2684 return i18n.M.ChatSubagentPhaseReasoning
2685 case "responding":
2686 return i18n.M.ChatSubagentPhaseResponding
2687 case "tool":
2688 return i18n.M.ChatSubagentPhaseTool
2689 case "retrying":
2690 return i18n.M.ChatSubagentPhaseRetrying
2691 case "completed":
2692 return i18n.M.ChatSubagentPhaseCompleted
2693 case "failed":
2694 return i18n.M.ChatSubagentPhaseFailed
2695 case "cancelled":
2696 return i18n.M.ChatSubagentPhaseCancelled
2697 }
2698 return phase
2699 }
2700
2701 // printSubagentProgressScrollback queues a status line for native-scrollback
2702 // terminals, which cannot rewrite printed output (finalized blocks drain via
2703 // pendingCommit like every other scrollback commit): status lines appear on
2704 // phase changes and terminal only, and verbose previews are throttled to at
2705 // most one print per 2s per child.
2706 func (m *chatTUI) printSubagentProgressScrollback(id string, sp *cliSubagentProgress) {
2707 if m.pendingCommit == nil {
2708 return
2709 }
2710 block := m.subagentProgressBlock(id, sp)
2711 if sp.terminal {
2712 *m.pendingCommit = append(*m.pendingCommit, block)
2713 sp.lastPrintedPhase = sp.phase
2714 sp.verboseLastPrint = time.Now()
2715 return
2716 }
2717 if sp.phase != sp.lastPrintedPhase {
2718 *m.pendingCommit = append(*m.pendingCommit, block)
2719 sp.lastPrintedPhase = sp.phase
2720 sp.verboseLastPrint = time.Now()
2721 return
2722 }
2723 if m.showReasoning && time.Since(sp.verboseLastPrint) >= 2*time.Second && (sp.reasoning != "" || sp.text != "" || sp.notice != "") {
2724 *m.pendingCommit = append(*m.pendingCommit, block)
2725 sp.verboseLastPrint = time.Now()
2726 }
2727 }
2728
2729 // collapseToolOutput replaces a finished tool's live block with a dim
2730 // "⎿ N lines" summary, so the scrollback keeps a marker of the run without the
2731 // full output (which the model already received). For shell commands ("shell-"
2732 // prefix), it shows the first shellPreviewLines with a Ctrl+B hint instead.
2733 // No-op when id isn't streaming. resultOutput (the ToolResult's final output)
2734 // is the last-resort line-count source when the live state was already reset.
2735 func (m *chatTUI) collapseToolOutput(id, resultOutput string) {
2736 if m.nativeScrollback {
2737 if id == "" || m.toolStreamID != id {
2738 return
2739 }
2740 n := m.toolLineCount
2741 if m.toolPartial != "" {
2742 n++
2743 }
2744 if n > 0 {
2745 if full, ok := m.shellOutputs[id]; ok {
2746 lines := strings.Split(strings.TrimRight(full, "\n"), "\n")
2747 total := len(lines)
2748 if total > shellPreviewLines {
2749 preview := make([]string, shellPreviewLines+1)
2750 for i := range shellPreviewLines {
2751 preview[i] = dim(clampPlain(lines[i], m.width-len([]rune(connector))))
2752 }
2753 preview[shellPreviewLines] = dim(fmt.Sprintf("… %d more lines (Ctrl+B)", total-shellPreviewLines))
2754 m.commitConnectorBlock(preview)
2755 } else {
2756 rendered := make([]string, total)
2757 for i, ln := range lines {
2758 rendered[i] = dim(clampPlain(ln, m.width-len([]rune(connector))))
2759 }
2760 m.commitConnectorBlock(rendered)
2761 }
2762 m.shellTranscriptIdx[id] = len(m.transcript) - 1
2763 } else {
2764 m.commitConnectorBlock([]string{dim(fmt.Sprintf("%d lines", n))})
2765 }
2766 }
2767 m.toolStreamIdx = -1
2768 m.toolStreamID = ""
2769 m.toolTail = m.toolTail[:0]
2770 m.toolPartial = ""
2771 m.toolLineCount = 0
2772 return
2773 }
2774 if m.toolStreamIdx < 0 || id == "" || m.toolStreamID != id {
2775 // Slot no longer active (another tool took over, or this id never
2776 // streamed). If beginToolRunning recorded a transcript index, collapse
2777 // in place so a late ToolResult doesn't leave raw streamed text behind.
2778 if idx, ok := m.shellTranscriptIdx[id]; ok && idx >= 0 && idx < len(m.transcript) {
2779 m.collapseShellSlot(id, idx, resultOutput)
2780 }
2781 return
2782 }
2783 m.collapseShellSlot(id, m.toolStreamIdx, resultOutput)
2784 m.toolStreamIdx = -1
2785 m.toolStreamID = ""
2786 m.toolTail = m.toolTail[:0]
2787 m.toolPartial = ""
2788 m.toolLineCount = 0
2789 }
2790
2791 // collapseShellSlot finalises a tool's live block at idx. Used both by the
2792 // active-tool path (idx == toolStreamIdx, streaming state intact) and the
2793 // late-result path (idx recorded in shellTranscriptIdx at dispatch). Line-count
2794 // sources, in order: live streaming state, shellOutputs ("shell-" ids only),
2795 // the per-id count stashed by streamToolOutput, then the ToolResult's output.
2796 func (m *chatTUI) collapseShellSlot(id string, idx int, resultOutput string) {
2797 m.transcriptDirty = true
2798 n := -1
2799 if id == m.toolStreamID {
2800 // Prefer the larger of the live count and resultOutput: resultOutput
2801 // is the authoritative end-state, the live state may lag behind it.
2802 n = m.toolLineCount
2803 if m.toolPartial != "" {
2804 n++
2805 }
2806 if resultOutput != "" {
2807 fromResult := len(strings.Split(strings.TrimRight(resultOutput, "\n"), "\n"))
2808 if fromResult > n {
2809 n = fromResult
2810 }
2811 }
2812 }
2813 if n < 0 {
2814 if full, ok := m.shellOutputs[id]; ok {
2815 n = len(strings.Split(strings.TrimRight(full, "\n"), "\n"))
2816 } else if c, ok := m.toolLineCountByID[id]; ok {
2817 n = c
2818 } else if resultOutput != "" {
2819 n = len(strings.Split(strings.TrimRight(resultOutput, "\n"), "\n"))
2820 }
2821 }
2822 if n < 0 {
2823 // Nothing applies (e.g. a late result for a non-"shell-" id that never
2824 // streamed): treat as zero rather than fabricate a "-1 lines" count.
2825 n = 0
2826 }
2827 if n == 0 {
2828 // Tool finished with no output: clear the "working…" placeholder but
2829 // keep the slot (shellTranscriptIdx still points here for late progress).
2830 m.rewriteConnectorBlock(idx, nil)
2831 return
2832 }
2833 if full, ok := m.shellOutputs[id]; ok {
2834 // Shell command: show first N lines + hint.
2835 lines := strings.Split(strings.TrimRight(full, "\n"), "\n")
2836 total := len(lines)
2837 if total > shellPreviewLines {
2838 preview := make([]string, shellPreviewLines+1)
2839 for i := range shellPreviewLines {
2840 preview[i] = dim(clampPlain(lines[i], m.width-len([]rune(connector))))
2841 }
2842 preview[shellPreviewLines] = dim(fmt.Sprintf("… %d more lines (Ctrl+B)", total-shellPreviewLines))
2843 m.rewriteConnectorBlock(idx, preview)
2844 } else {
2845 rendered := make([]string, total)
2846 for i, ln := range lines {
2847 rendered[i] = dim(clampPlain(ln, m.width-len([]rune(connector))))
2848 }
2849 m.rewriteConnectorBlock(idx, rendered)
2850 }
2851 } else {
2852 m.rewriteConnectorBlock(idx, []string{dim(fmt.Sprintf("%d lines", n))})
2853 }
2854 m.shellTranscriptIdx[id] = idx
2855 }
2856
2857 // toggleShellOutput expands or collapses the output of the most recent shell
2858 // command. When expanded, up to shellExpandMaxLines lines are shown; when
2859 // collapsed, only the first shellPreviewLines are shown. Called on Ctrl+B.
2860 func (m *chatTUI) toggleShellOutput() {
2861 // Find the most recent shell output that has a transcript entry.
2862 var lastID string
2863 lastIdx := -1
2864 for id, idx := range m.shellTranscriptIdx {
2865 if idx >= 0 && idx < len(m.transcript) && idx > lastIdx {
2866 lastID = id
2867 lastIdx = idx
2868 }
2869 }
2870 if lastID == "" {
2871 return
2872 }
2873 full, ok := m.shellOutputs[lastID]
2874 if !ok {
2875 return
2876 }
2877 lines := strings.Split(strings.TrimRight(full, "\n"), "\n")
2878 total := len(lines)
2879 innerW := m.width - len([]rune(connector))
2880 if innerW < 10 {
2881 innerW = 80
2882 }
2883
2884 if m.shellExpanded[lastID] {
2885 // Collapse back to preview.
2886 m.shellExpanded[lastID] = false
2887 if total > shellPreviewLines {
2888 preview := make([]string, shellPreviewLines+1)
2889 for i := range shellPreviewLines {
2890 preview[i] = dim(clampPlain(lines[i], innerW))
2891 }
2892 preview[shellPreviewLines] = dim(fmt.Sprintf("… %d more lines (Ctrl+B)", total-shellPreviewLines))
2893 m.rewriteConnectorBlock(lastIdx, preview)
2894 }
2895 } else {
2896 // Expand: show up to shellExpandMaxLines lines.
2897 m.shellExpanded[lastID] = true
2898 show := min(total, shellExpandMaxLines)
2899 rendered := make([]string, show)
2900 for i := range show {
2901 rendered[i] = dim(clampPlain(lines[i], innerW))
2902 }
2903 if total > shellExpandMaxLines {
2904 rendered = append(rendered, dim(fmt.Sprintf("… %d more lines", total-shellExpandMaxLines)))
2905 }
2906 m.rewriteConnectorBlock(lastIdx, rendered)
2907 }
2908 if m.nativeScrollback {
2909 m.commitLine(m.transcript[lastIdx])
2910 }
2911 }
2912
2913 // toolWorkingFrames is the braille spinner cycled once per second on the
2914 // "⎿ working · Ns" line of a tool that hasn't streamed output yet.
2915 var toolWorkingFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
2916
2917 // beginToolRunning opens an empty live block under a just-dispatched tool card,
2918 // keyed by the call id. tickToolRunning fills it with a "working · Ns" line each
2919 // second; if the tool later streams output, streamToolOutput reuses the same
2920 // block; collapseToolOutput closes it on the result.
2921 func (m *chatTUI) beginToolRunning(id string) {
2922 if id == "" {
2923 return
2924 }
2925 m.toolStreamID = id
2926 m.toolTail = m.toolTail[:0]
2927 m.toolPartial = ""
2928 m.toolLineCount = 0
2929 // Clear accumulated output for this tool ID so a re-run (e.g. repeated
2930 // !pwd with the same "shell-pwd" id) doesn't append to old output.
2931 delete(m.shellOutputs, id)
2932 m.toolStreamStart = time.Now()
2933 m.toolStreamFrame = 0
2934 if m.nativeScrollback {
2935 m.toolStreamIdx = -1
2936 return
2937 }
2938 m.toolStreamIdx = len(m.transcript)
2939 m.commitConnectorBlock([]string{dim(fmt.Sprintf(i18n.M.ChatToolWorkingFmt, toolWorkingFrames[0], 0))})
2940 // Remember the transcript slot for this id so a late ToolProgress for a
2941 // previously dispatched (and possibly already collapsed) tool can reuse
2942 // it instead of appending a fresh slot at the end of the transcript. For
2943 // back-to-back tool calls this keeps each tool's live block directly
2944 // under its own card.
2945 m.shellTranscriptIdx[id] = m.toolStreamIdx
2946 }
2947
2948 // tickToolRunning re-renders the working line of a tool that's dispatched but
2949 // hasn't produced output yet. A no-op once output streams in or no tool runs.
2950 func (m *chatTUI) tickToolRunning() {
2951 if m.nativeScrollback {
2952 return
2953 }
2954 if m.toolStreamIdx < 0 || m.toolLineCount != 0 || m.toolPartial != "" {
2955 return
2956 }
2957 m.toolStreamFrame++
2958 frame := toolWorkingFrames[m.toolStreamFrame%len(toolWorkingFrames)]
2959 secs := int(time.Since(m.toolStreamStart).Seconds())
2960 m.rewriteConnectorBlock(m.toolStreamIdx, []string{dim(fmt.Sprintf(i18n.M.ChatToolWorkingFmt, frame, secs))})
2961 }
2962
2963 // commitReasoning closes the live thinking block: the "▎ thinking…" marker is
2964 // rewritten to a dim "▎ thought for Ns" summary and the streamed text below it is
2965 // removed (collapsed) — kept only in verbose mode. The viewport re-wraps from
2966 // m.transcript, so the change is flagged via transcriptDirty.
2967 func (m *chatTUI) commitReasoning() {
2968 if m.reasoningNative {
2969 if strings.TrimSpace(m.reasoning.String()) != "" || !m.thinkStart.IsZero() {
2970 secs := int(time.Since(m.thinkStart).Seconds())
2971 m.commitSpacer()
2972 m.commitLine(dim(fmt.Sprintf(" ▎ "+i18n.M.ChatThoughtForFmt, secs)))
2973 if m.showReasoning && strings.TrimSpace(m.reasoning.String()) != "" {
2974 m.commitLine(reasoningBlock(m.reasoning.String(), m.width, 0))
2975 }
2976 }
2977 m.reasoning.Reset()
2978 m.reasoningView = m.reasoningView[:0]
2979 m.reasoningNative = false
2980 m.thinkStart = time.Time{}
2981 return
2982 }
2983 if m.reasoningLineIdx < 0 {
2984 return
2985 }
2986 secs := int(time.Since(m.thinkStart).Seconds())
2987 m.setTranscriptBlock(m.reasoningLineIdx, dim(fmt.Sprintf(" ▎ "+i18n.M.ChatThoughtForFmt, secs)), transcriptSource{kind: transcriptSourceFixed})
2988 if m.reasoningTextIdx >= 0 {
2989 if m.showReasoning && strings.TrimSpace(m.reasoning.String()) != "" {
2990 raw := m.reasoning.String()
2991 m.setTranscriptBlock(m.reasoningTextIdx, reasoningBlock(raw, m.width, 0), transcriptSource{
2992 kind: transcriptSourceReasoning, raw: raw,
2993 })
2994 } else {
2995 m.removeTranscriptBlock(m.reasoningTextIdx)
2996 }
2997 }
2998 m.transcriptDirty = true
2999 m.reasoning.Reset()
3000 m.reasoningView = m.reasoningView[:0]
3001 m.reasoningLineIdx = -1
3002 m.reasoningTextIdx = -1
3003 }
3004
3005 // commitReasoningBeforeAnswer closes a real reasoning block and leaves exactly
3006 // one blank transcript row before the assistant answer. Answers that start
3007 // without reasoning keep their existing compact placement.
3008 func (m *chatTUI) commitReasoningBeforeAnswer() {
3009 hadReasoning := m.reasoningNative || m.reasoningLineIdx >= 0
3010 m.commitReasoning()
3011 if hadReasoning {
3012 m.commitSpacer()
3013 }
3014 }
3015
3016 // streamAnswer renders the answer streamed so far up to its last completed
3017 // paragraph (flushableMarkdownPrefix) and writes it as one transcript block,
3018 // rewritten in place as later paragraphs land — so a long reply appears chunk by
3019 // chunk instead of all at once on turn end. The trailing, still-streaming block
3020 // stays buffered (a half-written fence/list never renders early), and it only
3021 // re-renders when a new paragraph actually closes.
3022 func (m *chatTUI) streamAnswer() {
3023 if m.nativeScrollback {
3024 return
3025 }
3026 prefix := flushableMarkdownPrefix(m.pending.String())
3027 if len(prefix) <= m.answerFlushed {
3028 return
3029 }
3030 source := transcriptSource{kind: transcriptSourceMarkdown, raw: prefix}
3031 m.answerFlushed = len(prefix)
3032 if m.answerIdx < 0 {
3033 m.answerIdx = len(m.transcript)
3034 m.commitTranscriptSource(source)
3035 } else {
3036 // setTranscriptBlock invalidates the wrap suffix from answerIdx so the
3037 // next Update only re-wraps the live answer block — not the full history.
3038 block := m.renderTranscriptSource(source, m.width)
3039 m.setTranscriptBlock(m.answerIdx, block, source)
3040 }
3041 }
3042
3043 // commitPending freezes the full accumulated answer as markdown — overwriting the
3044 // streamed block if one is open (streamAnswer), else committing fresh. Joining
3045 // commitReasoning then commitPending puts the answer on its own line, restoring
3046 // the thinking→answer break the renderer strips.
3047 func (m *chatTUI) commitPending() {
3048 if m.pending.Len() == 0 {
3049 m.answerIdx = -1
3050 m.answerFlushed = 0
3051 return
3052 }
3053 raw := m.pending.String()
3054 source := transcriptSource{kind: transcriptSourceMarkdown, raw: raw}
3055 if m.answerIdx < 0 {
3056 m.commitTranscriptSource(source)
3057 } else {
3058 block := m.renderTranscriptSource(source, m.width)
3059 m.setTranscriptBlock(m.answerIdx, block, source)
3060 }
3061 m.pending.Reset()
3062 m.answerIdx = -1
3063 m.answerFlushed = 0
3064 }
3065
3066 // flushableMarkdownPrefix returns the longest prefix of buf made of complete
3067 // markdown blocks — text up to the last blank line outside any open fenced code
3068 // block. A blank line inside a ``` / ~~~ fence isn't a boundary, so a half-written
3069 // code block stays buffered until it closes.
3070 func flushableMarkdownPrefix(buf string) string {
3071 lines := strings.Split(buf, "\n")
3072 inFence := false
3073 boundary := -1
3074 for i, ln := range lines {
3075 t := strings.TrimSpace(ln)
3076 if strings.HasPrefix(t, "```") || strings.HasPrefix(t, "~~~") {
3077 inFence = !inFence
3078 continue
3079 }
3080 if !inFence && t == "" {
3081 boundary = i
3082 }
3083 }
3084 if boundary <= 0 {
3085 return ""
3086 }
3087 return strings.Join(lines[:boundary], "\n")
3088 }
3089
3090 // planApprovalTool is the Tool name the controller puts on the ApprovalRequest it
3091 // emits to gate a plan (mirrors control's constant). The banner, status line, and
3092 // approval handler key on it to render the plan-specific prompt and to keep the
3093 // [plan] tag in sync when the user starts execution or exits without executing.
3094 const planApprovalTool = "exit_plan_mode"
3095
3096 // handleApprovalKey resolves a pending approval from a keystroke and re-arms the
3097 // listener. 1/y/Enter allows once and 2/a allows the exact scope for the rest
3098 // of the session. Fresh two-choice prompts use 2 for deny, while n/Esc and
3099 // legacy 4 still deny. Plan prompts use 1 to execute, 2/n/Esc to keep planning, and 3 to
3100 // reject the pending plan and leave plan mode without executing it.
3101 // Ctrl-C cancels the whole turn via the run context. For a plan approval
3102 // (planApprovalTool), starting execution or explicitly exiting without execution
3103 // drops the local [plan] tag and turns plan mode off on the controller.
3104 func (m chatTUI) handleApprovalKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
3105 if isRecoveryApprovalEvent(m.pendingApproval) {
3106 // Historical recovery requests are display-only. Escape and n dismiss the
3107 // compatibility record locally; no recovery RPC or tool replay is issued.
3108 if msg.String() == "esc" || strings.EqualFold(msg.String(), "n") {
3109 m.pendingApproval = nil
3110 }
3111 return m, nil
3112 }
3113 choices := approvalChoices(m.pendingApproval)
3114 answer := func(choice approvalChoice) (tea.Model, tea.Cmd) {
3115 allow, session := choice.allow, choice.allowForSession
3116 if m.pendingApproval.Tool == planApprovalTool && (allow || choice.exitPlan) {
3117 m.planMode = false
3118 m.ctrl.SetPlanMode(false)
3119 }
3120 m.ctrl.Approve(m.pendingApproval.ID, allow, session, false)
3121 m.pendingApproval = nil
3122 return m, nil
3123 }
3124 switch msg.String() {
3125 case "ctrl+c":
3126 m.ctrl.Cancel()
3127 return answer(approvalChoice{})
3128 case "up", "k", "ctrl+p":
3129 if m.approvalSelection < 0 && len(choices) > 0 {
3130 m.approvalSelection = 0
3131 } else if m.approvalSelection > 0 {
3132 m.approvalSelection--
3133 }
3134 return m, nil
3135 case "down", "j", "ctrl+n":
3136 if m.approvalSelection < len(choices)-1 {
3137 m.approvalSelection++
3138 }
3139 return m, nil
3140 case "enter":
3141 if m.approvalSelection >= 0 && m.approvalSelection < len(choices) {
3142 return answer(choices[m.approvalSelection])
3143 }
3144 return m, nil
3145 case "esc":
3146 return answer(approvalChoice{})
3147 }
3148 lower := strings.ToLower(msg.String())
3149 if len(lower) == 1 && lower[0] >= '1' && lower[0] <= '9' {
3150 idx := int(lower[0] - '1')
3151 if idx < len(choices) {
3152 return answer(choices[idx])
3153 }
3154 // Legacy muscle memory: tool approvals historically numbered deny as 4.
3155 // Honor 4 as deny even when the current prompt shows fewer rows, matching
3156 // the "legacy 4 still deny" contract in this function's doc comment.
3157 if lower == "4" {
3158 return answer(approvalChoice{})
3159 }
3160 return m, nil
3161 }
3162 switch lower {
3163 case "y":
3164 if len(choices) > 0 {
3165 return answer(choices[0])
3166 }
3167 case "a":
3168 for _, choice := range choices {
3169 if choice.allowForSession {
3170 return answer(choice)
3171 }
3172 }
3173 case "n":
3174 return answer(approvalChoice{})
3175 }
3176 return m, nil
3177 }
3178
3179 func isRecoveryApprovalEvent(a *event.Approval) bool {
3180 return a != nil && (a.Kind == recovery.ApprovalKindRecovery || a.Recovery != nil)
3181 }
3182
3183 func isRecoveryPlanChangeApproval(a *event.Approval) bool {
3184 if !isRecoveryApprovalEvent(a) || a.Recovery == nil {
3185 return false
3186 }
3187 switch strings.ToLower(strings.TrimSpace(a.Recovery.ChangeKind)) {
3188 case string(recovery.ChangeStrategy), string(recovery.ChangeScope):
3189 return true
3190 default:
3191 return false
3192 }
3193 }
3194
3195 func freshApprovalAllowsSession(toolName string) bool {
3196 return toolName == control.SandboxEscapeApprovalTool || toolName == control.ManagedConfigWriteApprovalTool
3197 }
3198
3199 var (
3200 // Input box: only top + bottom borders, no sides. The concrete colors are
3201 // refreshed from the active CLI theme during startup.
3202 inputBoxStyle lipgloss.Style
3203 todoPanelStyle lipgloss.Style
3204 statusBlockStyle lipgloss.Style
3205 workingStyle lipgloss.Style
3206 )
3207
3208 func (m chatTUI) cancelRequested() bool {
3209 if m.state != tuiRunning || m.ctrl == nil {
3210 return false
3211 }
3212 return m.ctrl.CancelRequested()
3213 }
3214
3215 func (m chatTUI) View() tea.View {
3216 v := m.frame()
3217 v.Content = m.glyphs.apply(v.Content)
3218 return v
3219 }
3220
3221 func (m chatTUI) frame() tea.View {
3222 if m.themeSweep != nil {
3223 v := tea.NewView(m.themeSweep.render())
3224 if !m.nativeScrollback {
3225 v.AltScreen = true
3226 if m.mouseCaptureOff {
3227 v.MouseMode = tea.MouseModeNone
3228 } else {
3229 v.MouseMode = tea.MouseModeCellMotion
3230 }
3231 }
3232 return v
3233 }
3234 boxW := max(m.width, 10)
3235 hideComposer := m.hideComposer()
3236 shellMode := strings.HasPrefix(strings.TrimSpace(m.input.Value()), "!")
3237 cancelRequested := m.cancelRequested()
3238 var box string
3239 if !hideComposer {
3240 style := inputBoxStyle.Width(boxW)
3241 if shellMode {
3242 style = withThemeBorderFG(style, statusShellColor)
3243 }
3244 box = style.Render(m.renderComposerInput())
3245 }
3246
3247 var modeTag string
3248 if shellMode {
3249 modeTag = modeTagStyle(statusShellColor, modeTagLight).Render("Shell")
3250 } else {
3251 background := statusAutoColor
3252 foreground := modeTagDark
3253 switch {
3254 case m.ctrl.AutoApproveTools():
3255 background = statusYoloColor
3256 foreground = modeTagLight
3257 case m.planMode:
3258 background = statusPlanColor
3259 foreground = modeTagLight
3260 }
3261 modeTag = modeTagStyle(background, foreground).Render(m.modeTagText())
3262 }
3263
3264 primaryStatus := m.primaryStatusLine(modeTag, shellMode, cancelRequested)
3265 // The spinning "thinking…" indicator is its own line ABOVE the input box (shown
3266 // only while a turn runs); the status/data rows stay below. This mirrors Claude
3267 // Code: live progress over the composer, shortcuts + stats under it.
3268 working := m.runningWorkingLine(cancelRequested, true)
3269 // Bottom region pinned under the transcript viewport: optional panels, the
3270 // composer when visible, then the two status rows. Its height feeds
3271 // transcriptHeight so the viewport above fills exactly the rest of the screen.
3272 var parts []string
3273 panels := m.pinnedPanelView()
3274 rowsAboveBox := panels.height()
3275 if content := panels.render(boxW); content != "" {
3276 parts = append(parts, content)
3277 }
3278 // Layout: the working spinner (when running), then the composer when visible,
3279 // then the persistent status block. Wide terminals keep two information rows
3280 // separated by a quiet rule: interaction + model/profile, then flexible Git
3281 // + fixed telemetry. Narrow
3282 // terminals break only between those semantic groups. Padding to full width
3283 // prevents stale cells.
3284 if working != "" {
3285 parts = append(parts, workingStyle.Width(boxW).MaxWidth(boxW).Render(wrapStatusLine(working, boxW)))
3286 // The working line wraps to multiple terminal rows on narrow terminals;
3287 // rowsAboveBox must count the wrapped rows or the composer cursor is
3288 // placed above the input box (see #7537).
3289 rowsAboveBox += workingLineRows(working, boxW)
3290 }
3291 if footer := m.renderMainManagerFooter(); footer != "" {
3292 parts = append(parts, footer)
3293 rowsAboveBox += strings.Count(footer, "\n") + 1
3294 }
3295 statusBlock := m.renderStatusBlock(primaryStatus, boxW)
3296 if !hideComposer {
3297 if qi := m.renderQueueIndicator(); qi != "" {
3298 parts = append(parts, qi)
3299 rowsAboveBox += strings.Count(qi, "\n") + 1
3300 }
3301 parts = append(parts, box)
3302 }
3303 parts = append(parts, statusBlockStyle.Width(boxW).MaxWidth(boxW).Render(statusBlock))
3304
3305 if m.nativeScrollback {
3306 v := tea.NewView(strings.Join(parts, "\n"))
3307 if !hideComposer {
3308 if cur := m.composerCursor(); cur != nil {
3309 cur.X += 1
3310 cur.Y += rowsAboveBox + 1
3311 v.Cursor = clampCursorToTerminal(cur, m.width, m.height)
3312 }
3313 }
3314 return v
3315 }
3316
3317 // Full-screen frame: the transcript viewport on top (it pads to exactly its
3318 // height), the pinned bottom region beneath. Alt-screen owns the grid, so
3319 // resize repaints cleanly — no scrollback reflow, no ghost borders.
3320 mainArea := m.renderTranscript()
3321 if card := m.renderMainManager(); card != "" {
3322 mainArea = m.renderTranscriptWithMainManager(card)
3323 }
3324 v := tea.NewView(mainArea + "\n" + strings.Join(parts, "\n"))
3325 v.AltScreen = true
3326 if m.mouseCaptureOff {
3327 // Release the mouse to the terminal: native click-drag selection and
3328 // right-click context menu work again, at the cost of the in-app
3329 // scrollbar, wheel-scroll, and drag-select while it's off.
3330 v.MouseMode = tea.MouseModeNone
3331 } else {
3332 v.MouseMode = tea.MouseModeCellMotion // wheel targets the hovered scroll region; text selection is handled in-app
3333 }
3334 // Anchor the real terminal cursor at the textarea's insertion point only when
3335 // the composer is visible. input.Cursor() is relative to the textarea; offset
3336 // by the viewport height + rows above + the box's top border row (+1 column
3337 // for PaddingLeft). Clamp to terminal bounds so VS Code fullscreen / resize
3338 // storms cannot leave the caret off-grid (#6282, #7236).
3339 if !hideComposer {
3340 if cur := m.composerCursor(); cur != nil {
3341 cur.X += 1
3342 cur.Y += m.viewport.Height() + rowsAboveBox + 1
3343 v.Cursor = clampCursorToTerminal(cur, m.width, m.height)
3344 }
3345 }
3346 return v
3347 }
3348
3349 // clampCursorToTerminal keeps the reported caret inside [0,w) × [0,h).
3350 func clampCursorToTerminal(cur *tea.Cursor, width, height int) *tea.Cursor {
3351 if cur == nil {
3352 return nil
3353 }
3354 if width > 0 {
3355 if cur.X < 0 {
3356 cur.X = 0
3357 }
3358 if cur.X >= width {
3359 cur.X = width - 1
3360 }
3361 }
3362 if height > 0 {
3363 if cur.Y < 0 {
3364 cur.Y = 0
3365 }
3366 if cur.Y >= height {
3367 cur.Y = height - 1
3368 }
3369 }
3370 return cur
3371 }
3372
3373 // compactionCardLines renders a finished compaction as a titled card: a header
3374 // with the message count and trigger, then the structured summary under a dim
3375 // gutter so it reads as one block in scrollback. The summary is also the new
3376 // context base, so this card is the user's window into exactly what was kept.
3377 func compactionCardLines(c event.Compaction) []string {
3378 trigger := c.Trigger
3379 switch c.Trigger {
3380 case "auto":
3381 trigger = i18n.M.CompactionAuto
3382 case "manual":
3383 trigger = i18n.M.CompactionManual
3384 }
3385 header := fmt.Sprintf("%s · %d %s · %s", i18n.M.CompactionTitle, c.Messages, i18n.M.CompactionUnit, trigger)
3386 lines := []string{accent("◆ " + header)}
3387 for ln := range strings.SplitSeq(strings.TrimRight(c.Summary, "\n"), "\n") {
3388 lines = append(lines, dim(" │ "+ln))
3389 }
3390 if c.Archive != "" {
3391 lines = append(lines, dim(" │ archived "+c.Archive))
3392 }
3393 return lines
3394 }
3395
3396 // contextTag renders the prompt-vs-context-window gauge for the status line,
3397 // framed around the auto-compaction threshold: it shows how much headroom is
3398 // left until the next compaction, and colours by proximity to that point rather
3399 // than the raw window. Falls back to a plain percentage when compaction is disabled.
3400 func (m chatTUI) contextTag() string {
3401 used, window := m.ctrl.ContextSnapshot()
3402 if used == 0 || window == 0 {
3403 return ""
3404 }
3405 pct := used * 100 / window
3406 ratio := m.ctrl.CompactRatio()
3407 if ratio <= 0 || ratio >= 1 {
3408 // Compaction disabled: just the raw gauge, coloured on window fill.
3409 body := fmt.Sprintf("%s / %s ctx (%d%%)", shortTokens(used), shortTokens(window), pct)
3410 switch {
3411 case pct >= 85:
3412 return themeStyle(activeCLITheme.danger).Render(body)
3413 case pct >= 60:
3414 return themeStyle(activeCLITheme.warn).Render(body)
3415 default:
3416 return dim(body)
3417 }
3418 }
3419 threshold := int(ratio * 100)
3420 // Headroom to the compaction point, as a percentage of the window (clamped at 0).
3421 left := max(threshold-pct, 0)
3422 body := fmt.Sprintf("%s ctx (%d%%) · %d%% to compact", shortTokens(used), pct, left)
3423 switch {
3424 case pct >= threshold:
3425 return themeStyle(activeCLITheme.danger).Render(fmt.Sprintf("%s ctx (%d%%) · compacting soon", shortTokens(used), pct))
3426 case left <= 10:
3427 return themeStyle(activeCLITheme.warn).Render(body)
3428 default:
3429 return dim(body)
3430 }
3431 }
3432
3433 func cacheRateLabel(format string, hit, denom int) string {
3434 if denom <= 0 {
3435 return ""
3436 }
3437 return fmt.Sprintf(format, fmt.Sprintf("%.2f%%", float64(hit)*100/float64(denom)))
3438 }
3439
3440 // cacheTag renders both prompt cache-hit rates for the status line —
3441 // "turn hit 88.00% · avg 78.00%": the single-turn rate (latest turn, the higher/steeper
3442 // number on a non-compacting DeepSeek session) and the session-aggregate rate
3443 // Σhit/Σ(hit+miss) (the steadier, cost-oriented number that matches the legacy
3444 // dashboard). "" before any cache tokens have been reported.
3445 func (m chatTUI) cacheStatus() (body string, rate float64, ok bool) {
3446 now := ""
3447 nowRate := 0.0
3448 if u := m.ctrl.LastUsage(); u != nil {
3449 // Only render when the provider actually reports cache token fields:
3450 // falling back to PromptTokens as the denominator painted a bogus
3451 // "turn hit 0.00%" for providers with no prompt-cache support.
3452 now = cacheRateLabel(i18n.M.ChatStatusCacheNowFmt, u.CacheHitTokens, u.CacheHitTokens+u.CacheMissTokens)
3453 if denom := u.CacheHitTokens + u.CacheMissTokens; denom > 0 {
3454 nowRate = float64(u.CacheHitTokens) * 100 / float64(denom)
3455 }
3456 }
3457 avg := ""
3458 avgRate := 0.0
3459 if hit, miss := m.ctrl.SessionCache(); hit+miss > 0 {
3460 avg = cacheRateLabel(i18n.M.ChatStatusCacheAvgFmt, hit, hit+miss)
3461 avgRate = float64(hit) * 100 / float64(hit+miss)
3462 }
3463 switch {
3464 case now != "" && avg != "":
3465 return now + " · " + avg, avgRate, true
3466 case now != "":
3467 return now, nowRate, true
3468 case avg != "":
3469 return avg, avgRate, true
3470 }
3471 return "", 0, false
3472 }
3473
3474 func (m chatTUI) cacheTag() string {
3475 body, _, ok := m.cacheStatus()
3476 if !ok {
3477 return ""
3478 }
3479 return dim(body)
3480 }
3481
3482 // jobsTag shows the count of running background jobs in the status line. Job
3483 // start/finish emit Notices that arrive on eventCh and re-render the frame, so
3484 // the count stays current without a dedicated tick.
3485 func (m chatTUI) jobsTag() string {
3486 n := len(m.ctrl.Jobs())
3487 if n == 0 {
3488 return ""
3489 }
3490 return dim(fmt.Sprintf("⚙ %d", n))
3491 }
3492
3493 func (m chatTUI) effortTag() string {
3494 if m.effortLevel == "" {
3495 return ""
3496 }
3497 value := footerValue(m.effortLevel)
3498 if m.effortLevel != "auto" {
3499 value = themeStyle(activeCLITheme.info).Bold(true).Render(m.effortLevel)
3500 }
3501 return footerMetric(i18n.M.ChatStatusEffortLabel, value)
3502 }
3503
3504 // mouseTag is a persistent status-line marker while mouseCaptureOff is on, so
3505 // the loss of in-app scrollbar/wheel-scroll/drag-select reads as a deliberate
3506 // state rather than a bug the user has to guess at.
3507 func (m chatTUI) mouseTag() string {
3508 if !m.mouseCaptureOff {
3509 return ""
3510 }
3511 return dim(i18n.M.MouseCaptureTag)
3512 }
3513
3514 // shortTokens prints token counts compactly: 1_500 → "1.5K", 142_000 → "142.0K", 1_000_000 → "1.0M".
3515 func shortTokens(n int) string {
3516 switch {
3517 case n >= 999_950:
3518 return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
3519 case n >= 1_000:
3520 return fmt.Sprintf("%.1fK", float64(n)/1_000)
3521 default:
3522 return fmt.Sprintf("%d", n)
3523 }
3524 }
3525
3526 // turnPhaseStatusLabel maps host turn_phase values to a short status label.
3527 // Empty when the phase is unknown so callers fall back to the default thinking line.
3528 func turnPhaseStatusLabel(phase string) string {
3529 switch strings.ToLower(strings.TrimSpace(phase)) {
3530 case "working":
3531 return i18n.M.TurnPhaseWorking
3532 case "checking":
3533 return i18n.M.TurnPhaseChecking
3534 case "verifying":
3535 return i18n.M.TurnPhaseVerifying
3536 case "reviewing":
3537 return i18n.M.TurnPhaseReviewing
3538 default:
3539 return ""
3540 }
3541 }
3542
3543 // formatCompletionSummaryLine renders a content-free quality summary for TUI scrollback.
3544 func formatCompletionSummaryLine(c *event.CompletionSummaryInfo) string {
3545 if c == nil {
3546 return ""
3547 }
3548 verdict := strings.TrimSpace(c.Verdict)
3549 if verdict == "" {
3550 verdict = "complete"
3551 }
3552 line := fmt.Sprintf("%s · mut=%d · checks %d✓/%d✗/%d⊘",
3553 verdict, c.Mutations, c.ChecksPassed, c.ChecksFailed, c.ChecksSuppressed)
3554 if c.Review != "" && c.Review != "none" {
3555 line += " · review=" + c.Review
3556 }
3557 if len(c.GapKinds) > 0 {
3558 line += " · gaps=" + strings.Join(c.GapKinds, ",")
3559 }
3560 if c.ConstraintDegraded {
3561 line += " · constraints"
3562 }
3563 return line
3564 }
3565
3566 func completionSummaryNeedsAttention(c *event.CompletionSummaryInfo, _ string) bool {
3567 if c == nil {
3568 return false
3569 }
3570 if strings.TrimSpace(c.Floor) != "" {
3571 return c.Attention
3572 }
3573 if strings.EqualFold(strings.TrimSpace(c.Verdict), "blocked") || c.ChecksFailed > 0 || c.ChecksSuppressed > 0 {
3574 return true
3575 }
3576 for _, gap := range c.GapKinds {
3577 switch strings.ToLower(strings.TrimSpace(gap)) {
3578 case "unbacked_claim", "failed_verification":
3579 return true
3580 }
3581 }
3582 return false
3583 }
3584
3585 func completionSummaryWarning(c *event.CompletionSummaryInfo) string {
3586 if c != nil && strings.EqualFold(strings.TrimSpace(c.Verdict), "blocked") {
3587 return i18n.M.CompletionSummaryBlocked
3588 }
3589 return i18n.M.CompletionSummaryNeedsAttention
3590 }
3591
3592 // renderApprovalBanner is the slim notice shown above the input while a tool
3593 // call (or a plan) awaits the user's decision.
3594 func (m chatTUI) renderApprovalBanner() string {
3595 return m.renderApprovalBannerPanel().text
3596 }
3597
3598 func (m chatTUI) renderApprovalBannerPanel() panelContent {
3599 w := max(m.width, 10)
3600 if m.pendingApproval == nil {
3601 return panelContent{}
3602 }
3603 if isRecoveryApprovalEvent(m.pendingApproval) {
3604 return panelContent{text: choicePanelStyle.Width(w).Render("ℹ Historical recovery record (retired). It cannot confirm or replay an operation.\n" + dim("Esc/n dismiss"))}
3605 }
3606 var text string
3607 var planDetails []string
3608 if m.pendingApproval.Tool == planApprovalTool {
3609 text = i18n.M.PlanApprovalPrompt
3610 } else if isRecoveryPlanChangeApproval(m.pendingApproval) {
3611 text = i18n.M.RecoveryPlanDecisionPrompt
3612 if rec := m.pendingApproval.Recovery; rec != nil {
3613 if before := compactApprovalPlan(rec.PlanBefore); before != "" {
3614 planDetails = append(planDetails, fmt.Sprintf(i18n.M.RecoveryPlanBeforeFmt, truncateSubject(before, w)))
3615 }
3616 if after := compactApprovalPlan(rec.PlanAfter); after != "" {
3617 planDetails = append(planDetails, fmt.Sprintf(i18n.M.RecoveryPlanAfterFmt, truncateSubject(after, w)))
3618 }
3619 }
3620 } else {
3621 name, detail := approvalToolDetails(m.pendingApproval.Tool)
3622 subj := strings.TrimSpace(m.pendingApproval.Subject)
3623 full := subj
3624 if subj != "" {
3625 subj = " " + truncateSubject(subj, w)
3626 }
3627 text = strings.TrimSpace(fmt.Sprintf(i18n.M.ToolApprovalPromptFmt, name, subj, detail, ""))
3628 // A command clipped to one line can hide the part that matters — the
3629 // path being written, the flag that makes it destructive (#4682).
3630 if body := approvalSubjectBody(full, strings.TrimSpace(subj), w); body != "" {
3631 planDetails = append(planDetails, body)
3632 }
3633 }
3634 planDetails = append(planDetails, writeAccessBannerDetails(m.pendingApproval)...)
3635 if reason := strings.TrimSpace(m.pendingApproval.Reason); reason != "" {
3636 text += " · " + truncateSubject(reason, w)
3637 }
3638 if len(planDetails) > 0 {
3639 text += "\n" + strings.Join(planDetails, "\n")
3640 }
3641 var b panelBuilder
3642 b.WriteString("⏸ " + text + "\n")
3643 for i, choice := range approvalChoices(m.pendingApproval) {
3644 b.MarkFocus(i == m.approvalSelection, i)
3645 b.WriteString(rowLine(i == m.approvalSelection, i+1, "", choice.label, false) + "\n")
3646 }
3647 b.WriteString(dim("↑/↓ navigate · Enter select · y/a/p/n shortcuts"))
3648 return b.render(choicePanelStyle.Width(w), m.width)
3649 }
3650
3651 // maxApprovalSubjectLines bounds the expanded command so a heredoc cannot push
3652 // the composer off screen.
3653 const maxApprovalSubjectLines = 8
3654
3655 // approvalSubjectBody returns the full command wrapped over several lines when
3656 // the banner's one-line preview had to clip it, or "" when the preview already
3657 // showed everything.
3658 func approvalSubjectBody(full, preview string, width int) string {
3659 full = strings.TrimSpace(full)
3660 if full == "" || full == preview {
3661 return ""
3662 }
3663 wrapWidth := max(width-4, 20)
3664 lines := strings.Split(wrapStatusLine(full, wrapWidth), "\n")
3665 if len(lines) > maxApprovalSubjectLines {
3666 lines = lines[:maxApprovalSubjectLines]
3667 lines[maxApprovalSubjectLines-1] = ansi.Truncate(lines[maxApprovalSubjectLines-1], wrapWidth-1, "") + "…"
3668 }
3669 return strings.Join(lines, "\n")
3670 }
3671
3672 func compactApprovalPlan(plan string) string {
3673 return strings.Join(strings.Fields(strings.ReplaceAll(strings.TrimSpace(plan), "\n", " · ")), " ")
3674 }
3675
3676 // approvalToolDetails turns provider-visible tool IDs into user-facing labels.
3677 // MCP tools are advertised as mcp__<server>__<tool>; showing the short tool name
3678 // first keeps the approval prompt readable while preserving the source.
3679 func approvalToolDetails(toolName string) (name, detail string) {
3680 if toolName == agent.PlanModeReadOnlyCommandApprovalTool {
3681 return i18n.M.ApprovalToolLabelPlanModeReadOnly, fmt.Sprintf(i18n.M.ToolApprovalSourceFmt, i18n.M.ToolApprovalBuiltIn)
3682 }
3683 if toolName == control.SandboxEscapeApprovalTool {
3684 return i18n.M.ApprovalToolLabelSandboxEscape, fmt.Sprintf(i18n.M.ToolApprovalSourceFmt, i18n.M.ToolApprovalBuiltIn)
3685 }
3686 if toolName == control.ManagedConfigWriteApprovalTool {
3687 return i18n.M.ApprovalToolLabelConfigWrite, fmt.Sprintf(i18n.M.ToolApprovalSourceFmt, i18n.M.ToolApprovalBuiltIn)
3688 }
3689 if server, short, ok := tool.SplitMCPName(toolName); ok {
3690 lines := []string{}
3691 if strings.EqualFold(short, "understand_image") {
3692 lines = append(lines, i18n.M.ToolApprovalImageUse)
3693 }
3694 lines = append(lines, fmt.Sprintf(i18n.M.ToolApprovalSourceFmt, server))
3695 return short, strings.Join(lines, "\n")
3696 }
3697 return approvalToolLabel(toolName), fmt.Sprintf(i18n.M.ToolApprovalSourceFmt, i18n.M.ToolApprovalBuiltIn)
3698 }
3699
3700 func approvalToolLabel(toolName string) string {
3701 switch toolName {
3702 case "bash", "pwsh", "powershell", "shell":
3703 return i18n.M.ApprovalToolLabelBash
3704 case "edit_file":
3705 return i18n.M.ApprovalToolLabelEditFile
3706 case "write_file":
3707 return i18n.M.ApprovalToolLabelWriteFile
3708 case "multi_edit":
3709 return i18n.M.ApprovalToolLabelMultiEdit
3710 case "move_file":
3711 return i18n.M.ApprovalToolLabelMoveFile
3712 case "web_fetch":
3713 return i18n.M.ApprovalToolLabelWebFetch
3714 case "run_skill":
3715 return i18n.M.ApprovalToolLabelRunSkill
3716 case "remember":
3717 return i18n.M.ApprovalToolLabelRemember
3718 case "forget":
3719 return i18n.M.ApprovalToolLabelForget
3720 default:
3721 return toolName
3722 }
3723 }
3724
3725 // todoPanelMaxRows caps how many task lines the pinned panel shows; a long list
3726 // is truncated with a "+N more" footer so the bottom region stays compact.
3727 const todoPanelMaxRows = 8
3728
3729 // renderTodoPanel renders the committed current-turn task list above the input.
3730 // Completed lists remain inspectable until the next host turn boundary.
3731 func (m chatTUI) renderTodoPanel() string {
3732 return m.renderTodoContent().text
3733 }
3734
3735 func (m chatTUI) renderTodoContent() panelContent {
3736 if m.todosDismissed || len(m.todos) == 0 {
3737 return panelContent{}
3738 }
3739 done := 0
3740 for _, t := range m.todos {
3741 if t.Status == "completed" {
3742 done++
3743 }
3744 }
3745
3746 var b panelBuilder
3747 fmt.Fprintf(&b, "%s %s\n", accent("To-dos"), dim(fmt.Sprintf("%d/%d", done, len(m.todos))))
3748 start, end := todoPanelWindow(m.todos)
3749 if start > 0 {
3750 b.WriteString(dim(fmt.Sprintf(" +%d above", start)) + "\n")
3751 }
3752 for i, t := range m.todos[start:end] {
3753 b.MarkFocus(t.Status == "in_progress", start+i)
3754 indent := " "
3755 switch t.Status {
3756 case "completed":
3757 b.WriteString(indent + green("✔") + " " + dim(t.Content) + "\n")
3758 case "in_progress":
3759 b.WriteString(indent + yellow("▶ "+t.Content) + "\n")
3760 default:
3761 b.WriteString(indent + dim("○ "+t.Content) + "\n")
3762 }
3763 }
3764 if end < len(m.todos) {
3765 b.WriteString(dim(fmt.Sprintf(" +%d more", len(m.todos)-end)) + "\n")
3766 }
3767 return b.body().trimTrailingNewlines().render(todoPanelStyle.Width(max(m.width, 10)), m.width)
3768 }
3769
3770 func todoPanelWindow(todos []event.Todo) (int, int) {
3771 if len(todos) <= todoPanelMaxRows {
3772 return 0, len(todos)
3773 }
3774 active := -1
3775 for i, t := range todos {
3776 if t.Status == "in_progress" {
3777 active = i
3778 break
3779 }
3780 }
3781 if active < 0 {
3782 return 0, todoPanelMaxRows
3783 }
3784 start := max(active-todoPanelMaxRows/2, 0)
3785 if maxStart := len(todos) - todoPanelMaxRows; start > maxStart {
3786 start = maxStart
3787 }
3788 return start, start + todoPanelMaxRows
3789 }
3790
3791 // truncateSubject trims a tool subject so the approval banner fits one line.
3792 func truncateSubject(s string, width int) string {
3793 max := width - 28
3794 if max < 16 {
3795 max = 16
3796 }
3797 return ansi.Truncate(s, max, "…")
3798 }
3799
3800 // wrapStatusLine wraps a status line to `width` visible columns, ANSI-aware,
3801 // so text that exceeds one row flows onto additional lines instead of being
3802 // truncated with an ellipsis. Wrapping is permissive — spaces are preferred
3803 // break points — and works within the alt-screen view so there is no scrollback
3804 // artifact.
3805 func wrapStatusLine(s string, width int) string {
3806 if width <= 0 || s == "" {
3807 return s
3808 }
3809 return hardwrapTerminalText(s, width)
3810 }
3811
3812 // workingLineRows returns the number of terminal rows the working (spinner)
3813 // line occupies after wrapping to `width` (0 when the line is hidden). It
3814 // mirrors the wrapped render in View() so rowsAboveBox (cursor placement) and
3815 // computeStatusLineCount (bottomRows height) reserve the same row count.
3816 func workingLineRows(working string, width int) int {
3817 if working == "" || width <= 0 {
3818 return 0
3819 }
3820 return strings.Count(wrapStatusLine(working, width), "\n") + 1
3821 }
3822
3823 // computeStatusLineCount returns the number of terminal rows the status block
3824 // (working line + first status line + optional data band) will occupy after
3825 // wrapping to `width`. It mirrors the construction in View() so the reserved
3826 // height matches the rendered height exactly — the load-bearing invariant for
3827 // bottomRows().
3828 // Use the same width (m.width) that View() passes to wrapStatusLine.
3829 func (m chatTUI) computeStatusLineCount(width int) int {
3830 if m.ctrl == nil {
3831 return 3 // two information rows plus their divider
3832 }
3833 shellMode := strings.HasPrefix(strings.TrimSpace(m.input.Value()), "!")
3834 cancelRequested := m.cancelRequested()
3835
3836 // Replicate the first status line (mode tag + state) from View().
3837 // ModeTag is rendered with Padding(0,1) in View() — add the same padding
3838 // here so the visible width matches exactly.
3839 modeTag := " " + m.modeTagText() + " "
3840 if shellMode {
3841 modeTag = " Shell "
3842 }
3843 primaryStatus := m.primaryStatusLine(modeTag, shellMode, cancelRequested)
3844 statusBlock := m.renderStatusBlock(primaryStatus, width)
3845
3846 // Replicate the working (spinner) line from View(), shown only while a turn runs.
3847 working := m.runningWorkingLine(cancelRequested, false)
3848
3849 // Count wrapped rows for every piece that View() renders as wrapped.
3850 var lines int
3851 if working != "" {
3852 // working (spinner) line — wraps independently of the status block below.
3853 lines += workingLineRows(working, width)
3854 }
3855 lines += strings.Count(statusBlock, "\n") + 1
3856 return lines
3857 }
3858
3859 // The composer grows with its content up to this comfort cap. The effective
3860 // cap is lowered for short terminals by syncInputHeightLimit, after which the
3861 // textarea scrolls internally and keeps the caret visible.
3862 const maxInputRows = 8
3863
3864 const (
3865 composerBorderRows = 2
3866 minTranscriptRows = 3
3867 )
3868 const foldedPasteMinChars = 1000
3869 const foldedPasteMinLines = 5
3870
3871 type pastedBlock struct {
3872 label string
3873 text string
3874 image bool // an image attachment: expands to its bare @ref, not a wrapped block
3875 }
3876
3877 func (m *chatTUI) chooserTyping() bool {
3878 return m.chooser != nil && m.chooser.typing
3879 }
3880
3881 // inputHeightLimit returns the number of visible textarea rows that fit without
3882 // letting the complete composer block consume more than half the terminal or
3883 // pushing the transcript below its minimum useful height. Panel and wrapped
3884 // status rows are treated as fixed bottom chrome and remain outside the input
3885 // viewport.
3886 func (m chatTUI) inputHeightLimit() int {
3887 if m.height <= 0 {
3888 return maxInputRows
3889 }
3890
3891 limit := maxInputRows
3892 // Match the bounded-composer convention used by other coding TUIs: borders
3893 // are part of the half-screen budget, not extra rows added afterward.
3894 halfScreen := max(1, m.height/2-composerBorderRows)
3895 limit = min(limit, halfScreen)
3896
3897 // bottomRows includes the current composer. Remove it to get the fixed
3898 // panels/status budget, then reserve the input borders and a readable slice
3899 // of transcript. On extremely short terminals one editable row still wins.
3900 fixedBottomRows := m.bottomRows()
3901 if !m.hideComposer() {
3902 fixedBottomRows -= m.input.Height() + composerBorderRows
3903 }
3904 available := max(1, m.height-fixedBottomRows-composerBorderRows-minTranscriptRows)
3905 return max(1, min(limit, available))
3906 }
3907
3908 func (m *chatTUI) syncInputHeightLimit() {
3909 limit := m.inputHeightLimit()
3910 if m.input.MaxHeight == limit {
3911 return
3912 }
3913 m.followComposerCursor()
3914 m.input.MaxHeight = limit
3915 // SetWidth recalculates DynamicHeight from the full soft-wrapped content,
3916 // clamping the visible viewport to the new limit while preserving the text.
3917 m.input.SetWidth(max(m.width-4, 1))
3918 }
3919
3920 func (m *chatTUI) growInputToFit() {
3921 if m.input.DynamicHeight {
3922 return
3923 }
3924 lines := min(max(strings.Count(m.input.Value(), "\n")+1, 1), maxInputRows)
3925 if lines != m.input.Height() {
3926 m.input.SetHeight(lines)
3927 }
3928 }
3929
3930 func (m chatTUI) desktopShortcutLayout() bool {
3931 return m.cfg != nil && m.cfg.UIShortcutLayout() == "desktop"
3932 }
3933
3934 func (m chatTUI) modeTagText() string {
3935 goalMode := strings.TrimSpace(m.ctrl.Goal()) != "" && m.ctrl.GoalStatus() == control.GoalStatusRunning
3936 toolApprovalMode := m.ctrl.ToolApprovalMode()
3937 if m.desktopShortcutLayout() {
3938 switch {
3939 case m.planMode && toolApprovalMode == control.ToolApprovalDangerFullAccess:
3940 return "Plan+YOLO"
3941 case goalMode && toolApprovalMode == control.ToolApprovalDangerFullAccess:
3942 return "Goal+YOLO"
3943 case toolApprovalMode == control.ToolApprovalDangerFullAccess:
3944 return "YOLO"
3945 case m.planMode:
3946 return "Plan"
3947 case goalMode && toolApprovalMode == control.ToolApprovalWorkspaceWrite:
3948 return "Goal+Workspace"
3949 case goalMode:
3950 return "Goal"
3951 case toolApprovalMode == control.ToolApprovalWorkspaceWrite:
3952 return "Workspace"
3953 case toolApprovalMode == control.ToolApprovalDontAsk:
3954 return "Read only"
3955 default:
3956 return "Read only"
3957 }
3958 }
3959 switch {
3960 case m.planMode && toolApprovalMode == control.ToolApprovalDangerFullAccess:
3961 return "Plan+YOLO"
3962 case m.planMode && toolApprovalMode == control.ToolApprovalWorkspaceWrite:
3963 return "Plan+Workspace"
3964 case goalMode && toolApprovalMode == control.ToolApprovalDangerFullAccess:
3965 return "Goal+YOLO"
3966 case goalMode && toolApprovalMode == control.ToolApprovalWorkspaceWrite:
3967 return "Goal+Workspace"
3968 case toolApprovalMode == control.ToolApprovalDangerFullAccess:
3969 return "YOLO"
3970 case toolApprovalMode == control.ToolApprovalWorkspaceWrite:
3971 return "Workspace"
3972 case toolApprovalMode == control.ToolApprovalDontAsk:
3973 return "Read only"
3974 case m.planMode:
3975 return "Plan"
3976 case goalMode:
3977 return "Goal"
3978 default:
3979 return "Read only"
3980 }
3981 }
3982
3983 func (m *chatTUI) toggleVerboseReasoning(notify bool) {
3984 m.showReasoning = !m.showReasoning
3985 var saveErr error
3986 if m.cfg != nil {
3987 _ = m.cfg.SetShowReasoning(m.showReasoning)
3988 path := config.SourcePath()
3989 if path == "" {
3990 path = "reasonix.toml"
3991 }
3992 saveErr = config.EditConfigFile(path, func(cfg *config.Config) error {
3993 return cfg.SetShowReasoning(m.showReasoning)
3994 })
3995 }
3996 if !notify {
3997 return
3998 }
3999 suffix := ""
4000 if saveErr != nil {
4001 suffix = "\npreference was not saved: " + saveErr.Error()
4002 }
4003 if m.showReasoning {
4004 m.notice("verbose on — thinking text will be shown" + suffix)
4005 } else {
4006 m.notice("verbose off — thinking text will stay collapsed" + suffix)
4007 }
4008 }
4009
4010 // toggleMouseCapture flips whether Reasonix owns the mouse. It's session-only
4011 // (unlike /verbose, this accommodates the terminal/multiplexer at hand rather
4012 // than recording a lasting preference) — mirrors nativeScrollback, which is
4013 // likewise never persisted to config. Clears any in-app selection/scrollbar
4014 // drag in flight so a stale one can't be found mid-gesture once the terminal
4015 // starts intercepting the events that would have finished it.
4016 func (m *chatTUI) toggleMouseCapture() {
4017 m.mouseCaptureOff = !m.mouseCaptureOff
4018 m.sel = selection{}
4019 m.composerSel = composerSelection{}
4020 m.scrollbarDrag = false
4021 m.autoScroll = 0
4022 if m.mouseCaptureOff {
4023 m.notice(i18n.M.MouseCaptureOffHint)
4024 } else {
4025 m.notice(i18n.M.MouseCaptureOnHint)
4026 }
4027 }
4028
4029 // unsendPending "un-sends" the in-flight turn while the server hasn't replied yet
4030 // (bubblePending): it pops the echoed bubble back off the transcript, restores the
4031 // just-sent text to the input box, and cancels the request — marking the turn
4032 // discarded so its already-buffered events reach nothing. Once a packet has arrived
4033 // the bubble is confirmed and this path isn't taken (Esc cancels normally instead).
4034 func (m *chatTUI) unsendPending() {
4035 m.input.SetValue(m.pendingRestore)
4036 m.growInputToFit()
4037 m.truncateTranscriptBlocks(m.bubbleStartIdx)
4038 m.transcriptDirty = true
4039 m.bubblePending = false
4040 m.pendingRestore = ""
4041 m.pendingPastes = nil
4042 m.turnDiscarded = true
4043 m.ctrl.Cancel()
4044 }
4045
4046 // ingestEvent routes one typed event from the agent. Reasoning (dim) and answer
4047 // free-text accumulate in their live buffers; every other event first finalizes
4048 // the reasoning and answer streamed so far, then commits its own line —
4049 // preserving order. Switching on the event Kind replaces the old prefix-sniffing
4050 // of a flattened byte stream: the structure is now explicit.
4051
4052 // finalizeStreamed freezes any in-progress reasoning + answer into scrollback so
4053 // a following event line lands after them, preserving chronological order.
4054 func (m *chatTUI) finalizeStreamed() {
4055 m.collapseToolOutput(m.toolStreamID, "")
4056 m.commitReasoning()
4057 m.commitPending()
4058 }
4059
4060 func waitForAgentEvent(ch chan event.Event) tea.Cmd {
4061 return func() tea.Msg { return agentEventMsg(<-ch) }
4062 }
4063
4064 func elapsedTick(generation uint64) tea.Cmd {
4065 return tea.Tick(time.Second, func(_ time.Time) tea.Msg {
4066 return elapsedTickMsg{generation: generation}
4067 })
4068 }
4069
4070 // runSlashCommand handles "/<cmd> <args>" input. Local commands queue their
4071 // output to scrollback; MCP prompt / custom commands resolve to a model turn.
4072 func (m *chatTUI) runSlashCommand(input string) tea.Cmd {
4073 typedCmd := strings.TrimSpace(strings.SplitN(input, " ", 2)[0])
4074 if notice := m.slashInputBlockedNotice(typedCmd); notice != "" {
4075 m.notice(notice)
4076 return nil
4077 }
4078
4079 if strings.HasPrefix(typedCmd, "/mcp__") {
4080 return m.runMCPPrompt(input)
4081 }
4082 cmd := canonicalBuiltinSlashCommand(typedCmd)
4083
4084 switch cmd {
4085 case control.RecoverContextCommand:
4086 id, guidance, _ := control.ParseProtocolRecoveryCommand(input)
4087 return m.startControllerTurn(input, input, func(ctrl control.SessionAPI) {
4088 if runner, ok := ctrl.(interface{ SubmitProtocolRecovery(string, string) }); ok {
4089 runner.SubmitProtocolRecovery(id, guidance)
4090 }
4091 })
4092 case control.ContinueChecksCommand:
4093 prompt, _ := control.ParseFinalReadinessRecoveryCommand(input)
4094 return m.startControllerTurn(input, input, func(ctrl control.SessionAPI) {
4095 ctrl.SubmitFinalReadinessRecovery(input, prompt)
4096 })
4097 case "/compact":
4098 return m.runCompactCommand(input, typedCmd)
4099 case "/context":
4100 return m.showContextReport(input)
4101 case "/new":
4102 m.echoLocalCommand(input)
4103 if err := m.ctrl.NewSession(); err != nil {
4104 m.notice(fmt.Sprintf("%s: %v", i18n.M.SlashNewFailed, err))
4105 return nil
4106 }
4107 m.followSessionLease()
4108 // Native scrollback keeps the old transcript; mark the fork with a fresh banner.
4109 m.resetFreshContextView(false)
4110 m.notice(i18n.M.SlashNewDone)
4111 case "/clear":
4112 m.echoLocalCommand(input)
4113 if m.ctrl.ToolApprovalMode() == control.ToolApprovalDangerFullAccess {
4114 // Full access is an explicit commitment to skip ordinary confirmations; /clear is
4115 // rarely mistyped and the damage is recoverable, so clear directly.
4116 return m.clearContext()
4117 } else {
4118 m.clearConfirm = &clearConfirm{confirm: 1}
4119 }
4120 case "/cls":
4121 m.echoLocalCommand(input)
4122 m.finalizeStreamed()
4123 m.clearTranscriptDisplay()
4124 m.commitLine(strings.TrimRight(
4125 renderTUIBanner(m.label, "", transcriptContentWidth(m.width, m.nativeScrollback)), "\n"))
4126 m.transcriptDirty = true
4127 m.forceGotoBottom = true
4128 m.notice(i18n.M.SlashClsDone)
4129 case "/resume":
4130 m.runResumeCommand(input)
4131 case "/takeover":
4132 m.runTakeoverCommand(input)
4133 case "/status":
4134 m.echoLocalCommand(input)
4135 m.showStatusDetails()
4136 case "/rename":
4137 m.runRenameCommand(input)
4138 case "/todo":
4139 m.echoLocalCommand(input)
4140 // Dismiss only this mounted view; a later committed write brings it back.
4141 m.todosDismissed = true
4142 m.notice(i18n.M.SlashTodoCleared)
4143 case "/verbose":
4144 m.toggleVerboseReasoning(true)
4145 case "/mouse":
4146 m.toggleMouseCapture()
4147 case "/sandbox":
4148 m.echoLocalCommand(input)
4149 m.showSandboxStatus()
4150 case "/effort":
4151 return m.runEffortCommand(input)
4152 case "/preset", "/work-mode", "/profile":
4153 m.echoLocalCommand(input)
4154 return m.runPresetCommand(input)
4155 case "/reasoning-language":
4156 m.echoLocalCommand(input)
4157 m.runReasoningLanguageCommand(input)
4158 case "/rewind":
4159 m.echoLocalCommand(input)
4160 m.openRewind()
4161 case "/tree":
4162 m.echoLocalCommand(input)
4163 m.showBranchTree()
4164 case "/branch":
4165 m.echoLocalCommand(input)
4166 m.runBranchCommand(input)
4167 case "/switch":
4168 m.echoLocalCommand(input)
4169 m.runSwitchCommand(input)
4170 case "/mcp":
4171 m.echoLocalCommand(input)
4172 m.runMCPSubcommand(input)
4173 case "/remote":
4174 m.echoLocalCommand(input)
4175 m.showRemoteHosts()
4176 case "/plugin", "/plugins":
4177 m.echoLocalCommand(input)
4178 m.runPluginSubcommand(input)
4179 case "/model":
4180 m.echoLocalCommand(input)
4181 m.runModelSubcommand(input)
4182 if m.pendingModelSwitch != nil {
4183 return m.pendingModelSwitch
4184 }
4185 case "/provider":
4186 m.echoLocalCommand(input)
4187 m.runProviderCommand(input)
4188 if m.pendingModelSwitch != nil {
4189 return m.pendingModelSwitch
4190 }
4191 case "/setup":
4192 m.echoLocalCommand(input)
4193 m.openConnectionSetup()
4194 case "/skill", "/skills":
4195 m.echoLocalCommand(input)
4196 m.runSkillSubcommand(input)
4197 if m.pendingModelSwitch != nil {
4198 return m.pendingModelSwitch
4199 }
4200 case "/hooks":
4201 m.echoLocalCommand(input)
4202 m.runHooksSubcommand(input)
4203 case "/reload-cmd":
4204 m.echoLocalCommand(input)
4205 if m.ctrl == nil {
4206 m.notice("controller not ready")
4207 return nil
4208 }
4209 if m.ctrl.Running() {
4210 m.notice("wait for the current turn to finish, then retry /reload-cmd")
4211 return nil
4212 }
4213 prev := len(m.commands)
4214 err := m.ctrl.ReloadCommands(context.Background())
4215 m.commands = m.ctrl.Commands()
4216 m.invalidateSlashCatalog()
4217 m.updateCompletion()
4218 if err != nil {
4219 m.notice("reload-cmd: " + err.Error())
4220 return nil
4221 }
4222 m.notice(fmt.Sprintf("commands reloaded: %d → %d commands", prev, len(m.commands)))
4223
4224 case "/reload":
4225 m.echoLocalCommand(input)
4226 return m.runReloadCommand()
4227
4228 case "/paste-image":
4229 return m.beginClipboardImagePaste()
4230 case "/output-style", "/output-styles":
4231 m.echoLocalCommand(input)
4232 styles := outputstyle.List(outputstyle.Dirs())
4233 if len(styles) == 0 {
4234 m.notice(i18n.M.OutputStyleNone)
4235 } else {
4236 m.commitLine(renderOutputStyles(m.width, styles, m.outputStyle))
4237 }
4238 case "/diff-fold":
4239 m.echoLocalCommand(input)
4240 if m.diffMaxLines == 0 {
4241 m.diffMaxLines = diffFoldLimit
4242 m.notice(fmt.Sprintf(i18n.M.DiffFoldEnabledFmt, diffFoldLimit))
4243 } else {
4244 m.diffMaxLines = 0
4245 m.notice(i18n.M.DiffFoldDisabled)
4246 }
4247 case "/theme":
4248 m.echoLocalCommand(input)
4249 return m.runThemeSubcommand(input)
4250 case "/language":
4251 m.echoLocalCommand(input)
4252 return m.runLanguageSubcommand(input)
4253 case "/currency":
4254 m.echoLocalCommand(input)
4255 return m.runCurrencySubcommand(input)
4256 case "/help", "/web":
4257 return m.runHelpOrWebSlash(input, typedCmd)
4258 case "/memory":
4259 m.echoLocalCommand(input)
4260 m.showMemory(input)
4261 case "/migrate", "/migration":
4262 m.echoLocalCommand(input)
4263 migration.RunLegacyRescueCommand(strings.TrimSpace(strings.TrimPrefix(input, typedCmd)), event.FuncSink(func(e event.Event) {
4264 if e.Kind == event.Notice {
4265 m.notice(e.Text)
4266 }
4267 }))
4268 case "/goal":
4269 return m.runGoalSubcommand(input)
4270 case "/remember":
4271 m.rememberNote(strings.TrimSpace(strings.TrimPrefix(input, typedCmd)))
4272 case "/quit", "/exit":
4273 return shutdownNow
4274 case "/copy":
4275 return m.runCopyCommand(input)
4276 case "/export":
4277 m.runExportCommand(input)
4278 case "/forget":
4279 m.forgetMemory(strings.TrimSpace(strings.TrimPrefix(input, typedCmd)))
4280 default:
4281 return m.runUnrecognizedSlash(input, typedCmd, cmd)
4282 }
4283 return nil
4284 }
4285
4286 // showStatusDetails keeps diagnostics available without permanently crowding
4287 // the two-line composer footer.
4288 func (m *chatTUI) showStatusDetails() {
4289 var lines []string
4290 lines = append(lines, viewHeader("%s", "Session status"))
4291 mode := "Workspace"
4292 if m.ctrl != nil {
4293 mode = m.modeTagText()
4294 }
4295 lines = append(lines, " mode "+mode)
4296 model := strings.TrimSpace(m.modelRef)
4297 if model == "" {
4298 model = strings.TrimSpace(m.label)
4299 }
4300 if model != "" {
4301 lines = append(lines, " model "+model)
4302 }
4303 if m.ctrl != nil {
4304 if tag := m.contextTag(); tag != "" {
4305 lines = append(lines, " context "+tag)
4306 }
4307 }
4308 if m.effortLevel != "" {
4309 // The persistent footer uses an uppercase semantic label. The expanded
4310 // diagnostic view keeps its sentence-like wording for readability.
4311 lines = append(lines, " effort effort "+m.effortLevel)
4312 }
4313 if m.ctrl != nil {
4314 if tag := m.cacheTag(); tag != "" {
4315 lines = append(lines, " cache "+tag)
4316 }
4317 }
4318 if tag := m.gitTag(); tag != "" {
4319 lines = append(lines, " git "+tag)
4320 }
4321 if m.ctrl != nil {
4322 if tag := m.jobsTag(); tag != "" {
4323 lines = append(lines, " jobs "+tag)
4324 }
4325 }
4326 if m.balance != "" {
4327 lines = append(lines, " balance "+m.balance)
4328 }
4329 if tag := m.mouseTag(); tag != "" {
4330 lines = append(lines, " mouse "+tag)
4331 }
4332 lines = append(lines, " config "+activeConfigTag())
4333 m.commitLine(strings.Join(lines, "\n"))
4334 }
4335
4336 // activeConfigTag names the config file actually in effect. A ./reasonix.toml
4337 // outranks the user-global file, so a session started in a directory holding
4338 // one silently ignores global edits unless the source is visible (#3317).
4339 func activeConfigTag() string {
4340 path := config.SourcePath()
4341 if path == "" {
4342 return "(defaults — no config file)"
4343 }
4344 abs, err := filepath.Abs(path)
4345 if err != nil {
4346 return displayPath(path)
4347 }
4348 return displayPath(abs)
4349 }
4350
4351 // runCopyCommand copies the Nth-latest assistant message from the current turn
4352 // (after the last user message) to the clipboard.
4353 //
4354 // - "/copy" — shows a numbered list of assistant messages to choose from.
4355 // - "/copy N" — copies the Nth message directly (1 = most recent).
4356 //
4357 // Counting does not cross user message boundaries.
4358 func (m *chatTUI) runCopyCommand(input string) tea.Cmd {
4359 m.echoLocalCommand(input)
4360 // "/copy N" copies the Nth-newest assistant message directly (1 = most
4361 // recent), matching the picker's newest-first ordering. A bare "/copy"
4362 // (or a non-numeric argument) opens the interactive picker instead.
4363 arg := strings.TrimSpace(strings.TrimPrefix(input, "/copy"))
4364 if n, err := strconv.Atoi(arg); err == nil && n > 0 {
4365 msgs := chatUIDisplayHistory(m.ctrl)
4366 parts := copyAssistantParts(msgs)
4367 if len(parts) == 0 {
4368 m.notice(i18n.M.SlashCopyEmpty)
4369 return nil
4370 }
4371 // copyAssistantParts is oldest-first; index 0 of the reversed slice
4372 // is the most recent, so "/copy 1" = parts[len-1].
4373 idx := len(parts) - n
4374 if idx < 0 || idx >= len(parts) {
4375 m.notice(i18n.M.SlashCopyEmpty)
4376 return nil
4377 }
4378 return copyToClipboard(parts[idx])
4379 }
4380 m.openCopyPicker()
4381 return nil
4382 }
4383
4384 // firstLine returns the first non-empty line of s, truncated to 80 runes.
4385 func firstLine(s string) string {
4386 for line := range strings.SplitSeq(s, "\n") {
4387 if t := strings.TrimSpace(line); t != "" {
4388 runes := []rune(t)
4389 if len(runes) > 80 {
4390 return string(runes[:77]) + "..."
4391 }
4392 return t
4393 }
4394 }
4395 return "..."
4396 }
4397
4398 // runExportCommand exports the entire session as a markdown file, excluding
4399 // system messages, reasoning/thinking content, and tool calls/results.
4400 func (m *chatTUI) runExportCommand(input string) {
4401 m.echoLocalCommand(input)
4402 msgs := chatUIDisplayHistory(m.ctrl)
4403 if len(msgs) == 0 {
4404 m.notice(i18n.M.SlashExportEmpty)
4405 return
4406 }
4407
4408 var b strings.Builder
4409 b.WriteString("# reasonix session\n\n")
4410 lastRole := provider.Role("")
4411 exportedMessages := 0
4412 for _, msg := range cliHistoryWithoutPinnedContextRevisions(msgs) {
4413 switch msg.Role {
4414 case provider.RoleUser:
4415 // Skip internal steer messages.
4416 if _, isSteer := agent.SteerText(msg.Content); isSteer {
4417 continue
4418 }
4419 content := exportUserContent(msg.Content)
4420 if content == "" {
4421 continue
4422 }
4423 if lastRole != provider.RoleUser {
4424 b.WriteString("## User\n\n")
4425 }
4426 b.WriteString(content)
4427 b.WriteString("\n\n")
4428 exportedMessages++
4429 lastRole = provider.RoleUser
4430 case provider.RoleAssistant:
4431 content := strings.TrimSpace(msg.Content)
4432 if content == "" {
4433 continue
4434 }
4435 if lastRole != provider.RoleAssistant {
4436 b.WriteString("## Assistant\n\n")
4437 }
4438 b.WriteString(content)
4439 b.WriteString("\n\n")
4440 exportedMessages++
4441 lastRole = provider.RoleAssistant
4442 }
4443 }
4444 if exportedMessages == 0 {
4445 m.notice(i18n.M.SlashExportEmpty)
4446 return
4447 }
4448
4449 // Choose a filename. If the workspace has a root, save there; otherwise
4450 // the current directory. Use a timestamp-based name.
4451 dir := "."
4452 if m.ctrl != nil {
4453 if wr := m.ctrl.WorkspaceRoot(); wr != "" {
4454 dir = wr
4455 }
4456 }
4457 ts := time.Now().Format("20060102-150405")
4458 filename := fmt.Sprintf("session-%s.md", ts)
4459 path := filepath.Join(dir, filename)
4460 if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
4461 m.notice(fmt.Sprintf("%s: %v", i18n.M.SlashUnknown, err))
4462 return
4463 }
4464 m.notice(fmt.Sprintf(i18n.M.SlashExportDoneFmt, path))
4465 }
4466
4467 func exportUserContent(content string) string {
4468 content = control.StripComposePrefixes(content)
4469 content = control.StripReferencedContextPrefix(content)
4470 return strings.TrimSpace(content)
4471 }
4472
4473 func (m *chatTUI) echoLocalCommand(input string) {
4474 input = strings.TrimSpace(input)
4475 if input == "" {
4476 return
4477 }
4478 m.commitLine(dim(" › " + input))
4479 }
4480
4481 // commandNames renders the custom command list for /help, "" when there are none.
4482 func (m *chatTUI) commandNames() string {
4483 names := make([]string, 0, len(m.commands))
4484 for _, c := range m.commands {
4485 if !c.Hidden {
4486 names = append(names, "/"+c.Name)
4487 }
4488 }
4489 return strings.Join(names, " · ")
4490 }
4491
4492 // showSandboxStatus displays the current sandbox configuration and whether
4493 // the OS sandbox backend is available. It reads from the stored config so
4494 // the user can inspect sandbox state without leaving the TUI (closes #3316).
4495 func (m *chatTUI) showSandboxStatus() {
4496 if m.cfg == nil {
4497 m.notice("sandbox: config not loaded")
4498 return
4499 }
4500 bash := m.cfg.BashMode()
4501 network := m.cfg.Sandbox.Network
4502 available := sandbox.Available()
4503 roots := m.cfg.WriteRoots()
4504
4505 var b strings.Builder
4506 b.WriteString("sandbox\n")
4507 b.WriteString(" phase 0 file-writer confinement\n")
4508 if len(roots) > 0 {
4509 fmt.Fprintf(&b, " write_roots %s\n", strings.Join(roots, ", "))
4510 }
4511 if m.cfg.Sandbox.WorkspaceRoot != "" {
4512 fmt.Fprintf(&b, " workspace_root %s\n", m.cfg.Sandbox.WorkspaceRoot)
4513 }
4514 if len(m.cfg.Sandbox.AllowWrite) > 0 {
4515 fmt.Fprintf(&b, " allow_write %s\n", strings.Join(m.cfg.Sandbox.AllowWrite, ", "))
4516 }
4517 b.WriteString(" phase 1 OS bash sandbox\n")
4518 fmt.Fprintf(&b, " bash %s", bash)
4519 if bash == "enforce" && !available {
4520 b.WriteString(" (unavailable: no OS sandbox on this host; bash execution is refused. " + sandbox.UnavailableRemediation() + ")")
4521 }
4522 b.WriteString("\n")
4523 fmt.Fprintf(&b, " network %v\n", network)
4524 m.notice(b.String())
4525 }
4526
4527 // runMCPSubcommand handles "/mcp" (status), "/mcp add …" (connect a server live
4528 // and persist it), and "/mcp remove <name>" (disconnect + drop from config). Add
4529 // connects synchronously — like /compact, an explicit command may briefly block
4530 // the UI while the handshake runs.
4531 func (m *chatTUI) runMCPSubcommand(input string) {
4532 args := tokenizeArgs(input) // args[0] == "/mcp"
4533 if len(args) < 2 {
4534 m.openMCPManager("")
4535 return
4536 }
4537 switch args[1] {
4538 case "list", "ls":
4539 // The completion menu offers "list"; treat it as the status view (same as
4540 // the legacy /mcp output) rather than an unknown subcommand.
4541 m.showMCPStatus()
4542 case "show":
4543 if len(args) < 3 {
4544 m.notice("usage: /mcp show <name>")
4545 return
4546 }
4547 m.openMCPManager(args[2])
4548 case "tools":
4549 if len(args) < 3 {
4550 m.notice("usage: /mcp tools <name>")
4551 return
4552 }
4553 m.openMCPManager(args[2])
4554 if m.mcp != nil {
4555 m.mcp.stage = mcpStageTools
4556 }
4557 case "add":
4558 entry, err := parseMCPAdd(args[2:])
4559 if err != nil {
4560 m.notice(err.Error())
4561 return
4562 }
4563 n, err := m.ctrl.AddMCPServer(entry)
4564 if err != nil {
4565 m.notice("mcp add: " + err.Error())
4566 return
4567 }
4568 m.refreshHostAndInvalidateSlashCatalog()
4569 m.notice(fmt.Sprintf("connected %s — %d tools, saved to global config (available next message)", entry.Name, n))
4570 case "connect":
4571 if len(args) < 3 {
4572 m.notice("usage: /mcp connect <name>")
4573 return
4574 }
4575 if m.mcpConnectBusy(args[2]) {
4576 return
4577 }
4578 n, err := m.ctrl.ConnectConfiguredMCPServer(args[2])
4579 if err != nil {
4580 m.notice("mcp connect: " + err.Error())
4581 return
4582 }
4583 m.refreshHostAndInvalidateSlashCatalog()
4584 m.notice(fmt.Sprintf("connected %s — %d tools (available next message)", args[2], n))
4585 case "remove", "rm":
4586 if len(args) < 3 {
4587 m.notice("usage: /mcp remove <name>")
4588 return
4589 }
4590 name := args[2]
4591 if m.mcpConnectBusy(name) {
4592 return
4593 }
4594 disconnected, err := m.ctrl.RemoveMCPServer(name)
4595 if err != nil {
4596 m.notice("mcp remove: " + err.Error())
4597 return
4598 }
4599 m.refreshHostAndInvalidateSlashCatalog()
4600 if disconnected {
4601 m.notice("disconnected " + name + " and removed it from config")
4602 } else {
4603 m.notice("removed " + name + " from config")
4604 }
4605 case "import":
4606 m.openMCPImportPicker()
4607 default:
4608 m.notice("unknown /mcp subcommand " + args[1] + " — try: /mcp, /mcp list, /mcp show, /mcp add, /mcp connect, /mcp import, /mcp remove")
4609 }
4610 }
4611
4612 // showMCPStatus queues the connected MCP servers, their counts, and the prompt
4613 // commands / resource refs they expose — the discovery surface for /mcp.
4614 func (m *chatTUI) showMCPStatus() {
4615 if m.host == nil || (len(m.host.Servers()) == 0 && len(m.host.Failures()) == 0) {
4616 m.notice(i18n.M.SlashMCPNone)
4617 return
4618 }
4619 m.commitLine(renderMCPStatus(m.width, m.host.Servers(), m.host.Prompts(), m.host.Resources(), m.host.Failures(), m.host.CapabilityViews()))
4620 }
4621
4622 // notice queues a dim informational line to scrollback.
4623 func (m *chatTUI) notice(note string) {
4624 m.commitLine(dim(" · " + note))
4625 }
4626
4627 // showRemoteHosts renders a read-only summary of configured remote hosts. The
4628 // remote session lives in a `reasonix serve` on the remote host, so connecting
4629 // happens from a terminal (`reasonix remote connect`), not inside this chat.
4630 func (m *chatTUI) showRemoteHosts() {
4631 cfg, err := config.Load()
4632 if err != nil {
4633 m.notice(err.Error())
4634 return
4635 }
4636 if len(cfg.Remote.Hosts) == 0 {
4637 m.notice(i18n.M.RemoteNoHostsHint)
4638 return
4639 }
4640 var b strings.Builder
4641 for _, h := range cfg.Remote.Hosts {
4642 target := h.Host
4643 if h.User != "" {
4644 target = h.User + "@" + target
4645 }
4646 if h.Port != 0 && h.Port != 22 {
4647 target = fmt.Sprintf("%s:%d", target, h.Port)
4648 }
4649 fmt.Fprintf(&b, " · %s %s\n", h.Name, target)
4650 }
4651 fmt.Fprintf(&b, " run `reasonix remote connect <name>` in a terminal to open the remote workspace")
4652 m.commitLine(dim(b.String()))
4653 }
4654
4655 // resolveRefs resolves a line's @references off the event loop via the
4656 // controller, delivering a refsResolvedMsg with the tagged context block.
4657 func (m *chatTUI) resolveRefs(sent, display, restore string) tea.Cmd {
4658 return func() tea.Msg {
4659 block, errs := m.ctrl.ResolveRefs(context.Background(), sent)
4660 return refsResolvedMsg{sent: sent, display: display, restore: restore, block: block, errs: errs}
4661 }
4662 }
4663
4664 // runMCPPrompt resolves a /mcp__server__prompt command off the event loop via
4665 // the controller, delivering a promptResolvedMsg with the rendered prompt.
4666 func (m *chatTUI) runMCPPrompt(input string) tea.Cmd {
4667 return func() tea.Msg {
4668 sent, found, err := m.ctrl.MCPPrompt(context.Background(), input)
4669 if !found {
4670 name := strings.TrimPrefix(strings.Fields(input)[0], "/")
4671 return promptResolvedMsg{display: input, err: fmt.Errorf("%s: /%s", i18n.M.SlashUnknown, name)}
4672 }
4673 return promptResolvedMsg{display: input, sent: sent, err: err}
4674 }
4675 }
4676
4677 // runExtensionAction invokes one extension UI action off the event loop (the
4678 // call is a blocking sidecar round-trip), delivering an extensionActionMsg
4679 // whose message surfaces as a transcript notice.
4680 func (m *chatTUI) runExtensionAction(name string, args map[string]string) tea.Cmd {
4681 return func() tea.Msg {
4682 message, err := m.ctrl.InvokeExtensionAction(context.Background(), name, args)
4683 return extensionActionMsg{message: message, err: err}
4684 }
4685 }
4686
4687 // replaySectionsFor turns a loaded session into scrollback blocks. Normal tool
4688 // results remain quiet, while interrupted-turn reasoning and tool cards replay
4689 // from provider-excluded LocalOnly records so restart matches the live view.
4690 func replaySectionsFor(history []provider.Message, width int) []string {
4691 return replaySectionsForWithAssistantRenderer(history, width, renderAssistantMarkdown)
4692 }
4693
4694 func replaySectionsForWithAssistantRenderer(
4695 history []provider.Message,
4696 width int,
4697 renderAssistant func(string, int) string,
4698 ) []string {
4699 return replaySectionsForWithRenderers(history, width, renderAssistant, reasoningBlock)
4700 }
4701
4702 func replaySectionsForWithRenderers(
4703 history []provider.Message,
4704 width int,
4705 renderAssistant func(string, int) string,
4706 renderReasoning func(string, int, int) string,
4707 ) []string {
4708 var out []string
4709 for _, m := range cliHistoryWithoutPinnedContextRevisions(history) {
4710 if m.LocalOnly {
4711 if recovery, ok := provider.DecodeProtocolRecovery(m.ProtocolRecovery); ok && recovery.State == "pending" {
4712 out = append(out, fmt.Sprintf(" · %s: /recover-context %s\n\n", i18n.M.ProtocolRecoveryLabel, recovery.ID))
4713 }
4714 if m.FinalReadinessRecovery != nil && m.FinalReadinessRecovery.Pending {
4715 out = append(out, fmt.Sprintf(" · %s\n\n", i18n.M.FinalReadinessRecovery))
4716 continue
4717 }
4718 if reasoning := strings.TrimSpace(m.ReasoningContent); reasoning != "" {
4719 out = append(out, dim(" ▎ "+i18n.M.ChatThinking)+"\n"+renderReasoning(reasoning, width, 0)+"\n\n")
4720 }
4721 if body := strings.TrimSpace(m.Content); body != "" {
4722 out = append(out, renderAssistant(body, width)+"\n\n")
4723 }
4724 for _, call := range m.ToolCalls {
4725 out = append(out, toolCard(call.Name, "", width)+"\n\n")
4726 }
4727 if m.InterruptedTurn != nil {
4728 out = append(out, fmt.Sprintf(" · %s\n\n", interruptedTurnDisplayNotice()))
4729 }
4730 continue
4731 }
4732 out = append(out, searchHistorySections(m, width, renderAssistant)...)
4733 switch m.Role {
4734 case provider.RoleUser:
4735 // Host-generated wrappers (session-context snapshots, injected
4736 // preamble) are provider-workset plumbing, not visible turns; the
4737 // desktop transcript drops them and so does this replay.
4738 if agent.IsHostGeneratedUserMessage(m) {
4739 continue
4740 }
4741 // Steer messages are surfaced as a notice line, not a user bubble.
4742 if text, handled := agent.ReplaySteerText(m.Content); handled {
4743 if text != "" {
4744 out = append(out, fmt.Sprintf(" ↪ %s\n\n", text))
4745 }
4746 continue
4747 }
4748 content := control.StripComposePrefixes(agent.UserMessageText(m))
4749 out = append(out, renderUserBubble(content, width, false)+"\n\n")
4750 case provider.RoleAssistant:
4751 if reasoning := strings.TrimSpace(m.ReasoningContent); reasoning != "" {
4752 out = append(out, dim(" ▎ "+i18n.M.ChatThinking)+"\n"+renderReasoning(reasoning, width, 0)+"\n\n")
4753 }
4754 body := strings.TrimSpace(m.Content)
4755 if body != "" {
4756 out = append(out, renderAssistant(body, width)+"\n\n")
4757 }
4758 for _, call := range m.ToolCalls {
4759 out = append(out, toolCard(call.Name, call.Arguments, width)+"\n\n")
4760 }
4761 }
4762 }
4763 return out
4764 }
4765
4766 func interruptedTurnDisplayNotice() string {
4767 return i18n.M.InterruptedRecovery
4768 }
4769
4770 // renderTUIBanner is the title + tip + optional missing-key warning printed once
4771 // at the top of the session.
4772 func renderTUIBanner(label, missing string, width int) string {
4773 var b strings.Builder
4774 b.WriteString(accent("◆") + " " + bold("reasonix") + " " + dim("· "+label) + "\n")
4775 b.WriteString(dim(" "+i18n.M.ChatTip) + "\n")
4776 if missing != "" {
4777 b.WriteString(wrapForViewport(" ! "+missing, width, activeCLITheme.warn) + "\n")
4778 }
4779 return b.String()
4780 }
4781
4782 // wrapForViewport hard-wraps text to fit width columns and colours every line.
4783 func wrapForViewport(text string, width int, fg cliColor) string {
4784 if width <= 0 {
4785 width = 80
4786 }
4787 return themeStyle(fg).Width(width).Render(text)
4788 }
4789
4790 // renderUserBubble renders the just-submitted prompt as a transcript line. Keep
4791 // it visually lighter than the real bottom composer so a fresh session does not
4792 // look like it has a second input box in the transcript.
4793 func renderUserBubble(line string, width int, planMode bool) string {
4794 line = displayLineForImageRefs(line)
4795 prefix := "› "
4796 if planMode {
4797 prefix = "› [plan] "
4798 }
4799 if !colorOn() {
4800 return "│ " + prefix + line
4801 }
4802 return " " + accent(prefix+line)
4803 }
4804
4805 var cliImageRefRe = regexp.MustCompile(`(?:^|\s)@\.reasonix/attachments/clipboard-\d{8}-\d{6}\.\d+(?:-(?:\d{6}|[a-f0-9]{8}))?\.(?:png|jpg|jpeg|gif|webp)`)
4806
4807 func displayLineForImageRefs(line string) string {
4808 idx := 0
4809 out := cliImageRefRe.ReplaceAllStringFunc(line, func(_ string) string {
4810 idx++
4811 return " [image" + strconv.Itoa(idx) + "]"
4812 })
4813 return strings.TrimSpace(out)
4814 }
4815
4816 // eventSink is the event.Sink the agent emits to in TUI mode. Each event
4817 // becomes an agentEventMsg. The channel is generously buffered so streaming
4818 // bursts don't back-pressure the agent goroutine.
4819 type eventSink struct {
4820 ch chan<- event.Event
4821 }
4822
4823 func (s *eventSink) Emit(e event.Event) { s.ch <- e }
4824
4824 lines GO