Skip to content

Feat/sidebar files panel#363

Closed
kevincodex1 wants to merge 2 commits into
mainfrom
feat/sidebar-files-panel
Closed

Feat/sidebar files panel#363
kevincodex1 wants to merge 2 commits into
mainfrom
feat/sidebar-files-panel

Conversation

@kevincodex1

@kevincodex1 kevincodex1 commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds a FILES section to the TUI's right context sidebar (between PLAN and ACTIVITY) showing the workspace files the session has touched — newest first, with an A/M/✗ status badge, an aggregated +added −removed diffstat per file, a pulsing row for the file whose write is streaming right now, and a +N more overflow trailer.

Clicking a row selects the file (accent ▸ on the row, its edit cards tint in the chat, transcript scrolls to the most recent one; Esc clears). A second click opens a drill-in view reusing the subchat pattern: the chat column swaps to the file's stacked full-depth edit cards (edit N of M); f toggles to the syntax-highlighted on-disk file with ▎ markers on session-added lines, d back to diff, Esc returns to the chat at its saved scroll position.

The roster has two data sources: changedFiles carried by write_file/edit_file/apply_patch results (persisted to the session payload, so the panel survives /resume), and a git sweep for mutations the tool stream can't see — agents that scaffold via exec_command/bash or delegate to subagents. A baseline git status --porcelain --untracked-files=all snapshot at startup hides pre-existing dirt; re-sweeps after each command-tool result and at turn end merge newly dirty paths with a git diff HEAD --numstat diffstat. Sweeps are single-flight, 3s-timeboxed, and latch off in non-git workspaces.

Implementation notes: the drill-in swaps the body inside transcriptBodyItems and replaces the pinned title bar with a one-line nav, so the scroll engine, viewport, and mouse hit-testing stay consistent with no special-casing; the selection tint is part of the render-cache key so stale cards can't be served; FILES renders below PLAN so existing plan-step click offsets are untouched.

Linked issuediffstat per file, a pulsing row for the file whose write is streaming right now, and a +N more overflow trailer.

Clicking a row selects the file (accent ▸ on the row, its edit cards tint in the chat, transcript scrolls to the most recent one; Esc clears). A second click opens a drill-in view reusing the subchat pattern: the chat column swaps to the file's stacked full-depth edit cards (edit N of M); f toggles to the syntax-highlighted on-disk file with ▎ markers on session-added lines, d back to diff, Esc returns to the chat at its saved scroll position.

The roster has two data sources: changedFiles carried by write_file/edit_file/apply_patch results (persisted to the session payload, so the panel survives /resume), and a git sweep for mutations the tool stream can't see — agents that scaffold via exec_command/bash or delegate to subagents. A baseline git status --porcelain --untracked-files=all snapshot at startup hides pre-existing dirt; re-sweeps after each command-tool result and at turn end merge newly dirty paths with a git diff HEAD --numstat diffstat. Sweeps are single-flight, 3s-timeboxed, and latch off in non-git workspaces.

Implementation notes: the drill-in swaps the body inside transcriptBodyItems and replaces the pinned title bar with a one-line nav, so the scroll engine, viewport, and mouse hit-testing stay consistent with no special-casing; the selection tint is part of the render-cache key so stale cards can't be served; FILES renders below PLAN so existing plan-step click offsets are untouched.

Checklist

  • The linked issue already has the issue-approved label.
  • go build ./..., go vet ./..., and go test ./... pass locally.
  • gofmt clean.
  • Tests added/updated for the change (and run under -race where relevant). — 22 new tests across files_panel_test.go, file_view_test.go, files_git_sweep_test.go (incl. a sweep test against a real temp git repo); go test -race ./internal/tui/ passes.
  • UI changes include screenshots or a short recording where possible. — terminal captures below.

Summary by CodeRabbit

  • New Features

    • Added a new FILES sidebar section that shows recently touched files, including change counts and a compact overflow indicator.
    • Added a drill-in file viewer with diff and full file modes, plus easy switching while viewing a file.
    • File rows now highlight related edits and support hovering/clicking for faster navigation.
  • Bug Fixes

    • Improved detection of file changes so more workspace edits appear in the sidebar.
    • Preserved scroll position and selection behavior when opening, closing, or switching file views.

kevincodex1 and others added 2 commits July 2, 2026 10:25
The right context sidebar gains a FILES section between PLAN and
ACTIVITY: the workspace files the session has touched, newest first,
with an A/M/✗ badge, an aggregated +added/−removed diffstat, and a
pulsing row for the file whose write is streaming right now. The roster
is recovered on demand from tool-result rows' changedFiles (persisted to
the session payload and restored on rehydrate), so it survives /resume
and can never drift from the transcript — the same derive-from-rows
pattern the swarm AGENTS roster uses.

Clicking a row selects the file: its row gets an accent ▸, its edit
cards tint accent in the chat, and the transcript scrolls to the most
recent one. A second click (or any FILES click while the view is open)
opens a drill-in reusing the subchat pattern — the chat column body
swaps to the file's stacked full-depth edit cards ("edit N of M"), f
toggles to the syntax-highlighted on-disk file with ▎ markers on
session-added lines, d back to diff, Esc returns to the chat at its
saved scroll position; a second Esc clears the selection. The body swap
happens inside transcriptBodyItems and the nav bar replaces the pinned
title bar, so the scroll engine, viewport, and mouse hit-testing stay
consistent for free.

fix(oauth): make xAI / Hugging Face OAuth actually launch from the wizard (#355)

The provider wizard offered "Sign in with OAuth" for xAI and Hugging Face, but
clicking did nothing: the login managers were built without an env, so the preset
opt-in (ZERO_OAUTH_ALLOW_PRESETS) read as unset, ResolveConfig errored before any
browser step, and the error was never rendered on the provider list. Only ChatGPT
worked, because its login path force-enables presets.

Add ManagerOptions.AllowPresets, which layers the opt-in onto the manager env
(snapshotting the process environment so ZERO_OAUTH_<NAME>_* overrides survive
envValue's hermetic-map rule) without the operator exporting the flag. Set it on
every user-initiated OAuth manager: the wizard loopback login, the device-code
prepare/complete, the post-login token refresh, the runtime resolver that
authenticates model calls, and `zero auth login`. This fixes xAI end to end (it
ships a public client_id, so the browser now opens).

Also surface a failed OAuth attempt on the provider list (renderProviderStep) so
the click is no longer a silent no-op, with a Hugging Face hint pointing at app
registration + ZERO_OAUTH_HUGGINGFACE_CLIENT_ID (HF ships no public client_id, so
it still requires that one env var by design).
feat(tui): interactive theme picker + color theme catalog (#354)

* feat(tui): interactive theme picker + color theme catalog

Bare `/theme` now opens a popup that live-previews each palette as the cursor
moves and applies on select (Esc reverts), matching /model and /effort. Adds ten
built-in color themes alongside the dark/light built-ins — dracula, nord, gruvbox,
tokyo-night, catppuccin, one-dark, solarized-dark, rose-pine, everforest, and
solarized-light — plus a reworked light palette. Every palette is contrast-audited
to WCAG AA; the contrast tests now loop the whole registry.

Palettes and an ordered registry live in a new internal/tui/theme_palettes.go (now
the sole home of hex literals); selection, the picker, /theme <name>, --theme, and
ZERO_THEME all resolve through it. The whole frame is painted with the active
theme's surface (tea.View.BackgroundColor) so every theme is legible on any
terminal — a light theme's dark text no longer lands invisibly on a dark terminal,
and color themes show their real surface.

The chosen theme persists to user config (preferences.theme) and is reapplied at
startup, below the --theme flag and ZERO_THEME.

* fix(tui): address CodeRabbit review on the theme catalog

- CHANGELOG: reconcile the --theme bullet with the named themes (was still
  documenting {auto|dark|light}).
- /theme usage string advertises the list and auto forms (/theme list is still
  accepted) so /help matches the command surface.
- Theme-persistence test parses the written config and asserts preferences.theme
  directly instead of a raw substring, so a wrong-key regression fails.
fix(tui): require a second Esc press to cancel a running turn (#352)

* fix(tui): require a second Esc press to cancel a running turn

A single stray Esc during an active run cancelled it instantly with no
chance to reconsider - e.g. a press meant to dismiss an overlay that had
already closed. Ctrl+C already guards app-exit with a double-press
confirmation (exitConfirmActive/exitConfirmSeq); Esc now gets its own
independent confirmation (cancelConfirmActive/cancelConfirmSeq) guarding
run-cancellation specifically, since the two are different actions with
different consequences armed by different keys.

Mirrors the existing seq-gated tea.Tick pattern: first Esc arms a 3s
window and shows "Press Esc again to cancel" in the footer; a second Esc
within the window cancels the run; letting it expire, or the run finishing
on its own, disarms without cancelling.

Updated the three existing tests that assumed single-press cancellation
(TestEscCancelsPendingRun -> TestEscRequiresSecondPressToCancelPendingRun,
TestEscCancellationLeavesVisibleMarker, TestEscCancelRecordsSessionError,
TestCancelledRunFlushesCheckpointSessionEvents) and added
TestEscCancelConfirmationExpires mirroring the Ctrl+C expiry test.

* fix: pre-push review findings on the Esc cancel-confirmation gate

Ran an adversarial review before opening the PR. Three independent
reviewers converged on the same root defect: unlike exitConfirmActive
(disarmed by any key other than Ctrl+C), cancelConfirmActive had no
"anything else disarms it" safety net, so it behaved as a plain 3s timer
rather than a true immediate-second-press gate. Concretely:

- Typing, Ctrl+O, or any other non-Esc key left it armed, so a later,
  unrelated Esc press could silently cancel the run.
- A mid-turn ask_user or permission prompt lands asynchronously and is
  checked earlier in the Esc handler than the cancel-confirm block, so it
  silently "stole" the confirming press (denying the prompt instead) while
  leaving cancelConfirmActive armed for a subsequent, unrelated Esc to act
  on.
- Mouse clicks resolving a permission prompt or entering a subchat had the
  same gap.

Fixed by mirroring the Ctrl+C pattern: any non-Esc key disarms it (model.go,
next to the existing exitConfirmAction reset), and any left/right mouse
click disarms it too (mouse.go — scoped to clicks, not hover/motion, since
motion fires continuously and would otherwise defeat the window whenever
the mouse sits over the terminal). Within the Esc handler itself, restructured
to capture whether this press was really a confirm *before* any of the
earlier branches (subchat, MCP wizard, ask-user, permission, picker,
suggestions, queued-message, detailed-transcript) can run, then disarm
unconditionally — so an Esc consumed by any of those no longer leaves a
stale confirmation for a later press to trip.

Also updated two now-stale help strings the review flagged: the `?`
overlay's Esc row and pickerBusyText()'s "press Esc to cancel" hint, both
of which still described the old single-press behavior.

Added TestEscCancelConfirmationDisarmsOnInterveningKey (mirrors the
existing Ctrl+C equivalent) and
TestEscCancelConfirmationDisarmsWhenStolenByAskUser covering the two
confirmed gaps.

* fix: address CodeRabbit review comments on PR #352

- model.go: the first Esc (arming the cancel confirmation) was clearing the
  composer draft immediately, even though nothing had actually been
  cancelled yet — a leftover from the old single-press behavior, where
  clearing the draft and cancelling the run happened atomically as one
  action. Now that cancellation is two presses, only the confirming second
  Esc (or a plain Esc with no run pending) clears the composer; arming
  preserves whatever the user was typing, mirroring how Ctrl+C already
  preserves a draft (TestCtrlCClearsComposerBeforeExitConfirmation).

- clipboard.go: routePaste (bracketed paste and right-click paste) never
  disarmed a stale cancelConfirmActive — it isn't a tea.KeyPressMsg, so it
  bypassed the generic "any non-Esc key disarms it" hook added in the
  previous commit. A paste is a deliberate action like typing or clicking,
  so it should disarm the confirmation too; otherwise a later, unrelated
  Esc could silently cancel the run.

New tests: TestEscArmingCancelConfirmationPreservesComposerDraft,
TestPasteDisarmsCancelConfirmation.
fix: cap unbounded exec_command output buffer to prevent OOM kill (#353)

* fix: cap unbounded exec_command output buffer to prevent OOM kill

execOutputBuffer.data accumulated every byte a backgrounded exec_command
session wrote, with no size cap, unlike buffer.recent which is correctly
bounded to recentExecOutputBytes for the /ps preview. drainString() only
clears data when the agent actually polls that session again — so a
long-lived background session nobody polls (e.g. a dev server left running
after the run that started it was cancelled) grows this buffer forever as
long as the process keeps writing, with no ceiling.

Traced this directly to a real crash: a session that had been running for
~5.5 hours (an earlier turn invoking swarm agents got cancelled mid-flight,
per that session's own event log) accumulated to ~42.7GB of compressed
memory, at which point macOS's memorystatus killed the process outright
("killing zero due to low-swap").

Fixed by capping data at maxExecOutputBufferBytes (2MiB), trimming from the
front like recent already does, and surfacing a one-time truncation notice
on the next drain so data loss is visible rather than silent.

* fix: pre-push review findings on the exec_command buffer-cap fix

Ran an adversarial review before opening the PR. It found the truncation
notice added alongside the buffer cap didn't actually work: prefixing
execOutputTruncatedMessage into drainString()'s text meant the notice
always sat ~2MiB before the end of the combined output, but the tool's
own downstream truncateExecOutput() keeps at most a 400KB tail (even at
the maximum allowed max_output_tokens) — so the notice was reliably
swallowed, or chopped into an unreadable fragment at smaller budgets.
Verified with direct reproductions against the real functions.

Fixed by moving the signal out of the text stream entirely:
- execOutputBuffer gains consumeTruncated() (read+reset, called once per
  collect()) and peekTruncated() (read-only, for status views) instead of
  injecting a marker into the drained bytes.
- collect() now returns (string, bool); both call sites thread the bool
  through to execToolResult, which sets meta["output_buffer_truncated"]
  and appends the notice to the response body *after* truncateExecOutput
  runs, so it can never be re-truncated or land in a discarded region.
- Also flagged: a session torn down without ever being polled again after
  truncation loses the signal entirely, since nothing drains/logs it on
  teardown. Full audit-trail logging felt like overkill for a soft
  transparency signal on top of a hard memory-safety fix, but exposed
  peekTruncated() on ExecSessionSnapshot and surfaced it in the /ps row
  (background_terminals.go) so it's visible any time a still-running
  session is checked — covers the common case (the review's own scenario:
  a long-lived dev server nobody's polling but that's still alive) even
  though a session reaped before ever being looked at is still a gap.

New tests: reworked TestExecOutputBufferCapsUndrainedData for the
consume/peek API, and TestExecToolResultSurfacesBufferTruncationOutsideByteBudget
reproducing the review's exact failure case (max_output_tokens=1) and
proving the notice now survives it.
revert(local): restore the original bright-lime accent color (#351)

Restores accent to #caff3f (the pre-PR#350 value), undoing the three-round
brightness reduction (#ade619 -> #8db620 -> #759523) merged in PR #350. Only
the accent token changes - the hover-highlight color (a separate amber
token) and every other PR #350 fix (subchat selection, drag-to-edge
auto-scroll, the dragging-flag fix) are untouched.

Full gate green. Local only - not pushed.
fix(tui): subchat mouse selection, hover highlighting, and drag-to-edge auto-scroll (#350)

* fix(local): subchat mouse selection + hidden plan panel + scroll-extend selection

Three bugs in the subagent/swarm drill-in (subchat) view and mouse text selection,
all from the same root: newer features (subchat's row-source swap, wheel-scroll)
were never integrated into the older selection/footer code.

1) Can't copy anything in the subchat view. transcriptLineAtMouse (and
   selectedTranscriptText, the copy-time text extraction) always hit-tested against
   m.transcript (the parent), never m.subchat.childRows, even while the screen was
   showing the child session. New transcriptHitTestSource() mirrors transcriptView's
   own branching (nav bar + child rows + full width vs pinned title bar + parent
   rows + sidebar-aware width) and is now the single source both functions use.

2) Plan panel shown above the composer inside the subchat view. footerView
   unconditionally rendered the PARENT run's pinned plan panel; only pendingAskUser
   was gated. Added a !m.subchat.active guard (m.plan belongs to the parent run,
   not whatever subagent/swarm session is being viewed).

3) Selection didn't extend across a scroll (reported as "stopped at the end of the
   screen"). transcriptSelection.cursor was only ever updated by a mouseMotion
   event; a wheel event is a distinct message type that never reached that code,
   so scrolling while selecting left the selection frozen at whatever line the
   mouse last physically moved over. New scrollChatExtendingSelection scrolls AND
   re-evaluates the cursor at the mouse's current position against the post-scroll
   viewport. Uses a new nearestTranscriptLineAtMouse (falls back to the closest
   visible selectable line) rather than an exact match, since the recomputed
   position can land exactly on a blank spacer row between messages after an
   odd-length scroll shifts text/spacer parity - an exact-match miss there must
   not silently no-op the extension.

Tests: subchat selection resolves the CHILD session's text, not the parent's; the
plan panel is absent from the footer during subchat; a selection's cursor bodyY
moves (extends) after a wheel-scroll instead of staying pinned. Full gate green
(73 pkg, -race).

* feat(local): highlight clickable rows on mouse hover

Moving the cursor over an interactive row now highlights it (accent underline)
before you click, across every clickable surface:
- specialist cards and collapse/expand toggle headers in the transcript
- AGENTS sidebar rows (swarm members)
- PLAN sidebar step rows
- permission-prompt options (reuses the EXISTING keyboard-cursor highlight by
  moving pendingPermission.cursor on hover, instead of new styling)

Requires switching the mouse-tracking mode from CellMotion (only reports motion
while a button is held) to AllMotion (reports idle cursor movement too) - the
existing 15ms mouse-event throttle already covers the added motion events.

hover.go: hoverTarget + mouseHover predicate + updateHoverTarget, which reuses
the SAME hit-testers and priority order as the existing click handlers so hover
and click never disagree about what's clickable.

Sidebar hover is resolved by STABLE IDENTITY (sessionID / stepIndex), not a
cached line offset: hoveredSidebarLineOffset re-matches the identity against a
freshly computed hit list on every render, so a row that's disappeared (a
swarm member's linger elapsed, a plan step completed) simply doesn't highlight
rather than a coincidentally-matching unrelated row lighting up. Transcript
hover stays bodyY-keyed (matching the existing selection-highlight convention)
with explicit clearHover() calls wherever bodyY numbering can shift without an
intervening mouse motion: wheel-scroll, PgUp/PgDn, window resize, and
transcript rebuilds (/clear, /resume, /rewind, /compact via resetFlushFrontier).

Adversarial review caught two real bugs before ship, both fixed:
- BLOCKER: plan-step hover stored the step's own index (0,1,2...) but the
  sidebar render treated it as a raw line offset into the rendered rows -
  every plan-step hover highlighted the wrong row (the AGENTS header/body).
  Fixed by resolving fresh at render time via the stable-identity redesign
  above, which also closes the related sidebar-drift issue.
- MAJOR: hover wasn't cleared on keyboard PgUp/PgDn scroll.

Tests: predicate correctness; hover resolves the right target across all 4
surfaces (specialist card, toggle row, sidebar agent, plan step, permission
option) with the correct priority order; hover changes the actual render
output (transcript + sidebar); hover clears on wheel-scroll and subchat exit;
a regression test proving hoveredSidebarLineOffset self-heals (no highlight)
when a hovered row's identity no longer resolves - the exact scenario the
blocker fix targets. Full gate green (73 pkg, -race).

* fix(local): soften hover color + auto-scroll a drag past the transcript edge

1) Hover highlight was brand-lime (bright, glaring against the near-black
   surface) and re-paints on every mouse movement. Switched to amber (an
   existing semantic token, "light orange") and dropped the underline per
   feedback.

2) Dragging a text selection past the top/bottom edge of the visible
   transcript now auto-scrolls toward that side and extends the selection to
   follow, matching the browser/editor "drag past the viewport edge" pattern.
   transcriptEdgeScrollDelta detects the drag is vertically outside the body
   rect (but still within its horizontal span, so it isn't just "off to the
   side" over the sidebar); dragToEdgeScroll scrolls one step and anchors the
   cursor to whichever line now sits at that edge of the NEW viewport -
   deliberately not a re-resolve of the drag's physical mouse position, which
   stays outside the body rect after scrolling (scrolling changes what content
   occupies a screen row, not the mouse's screen position) and would keep
   finding nothing.

   Extracted nearestTranscriptSelectableAt as the shared "closest selectable
   line to a target bodyY" core, now used by both nearestTranscriptLineAtMouse
   (target derived from a mouse position that may have landed on a spacer row)
   and dragToEdgeScroll (target derived directly from the viewport bound, no
   mouse position involved at all).

Tests: dragging past the top edge scrolls toward older content and extends the
cursor upward; the symmetric bottom-edge case scrolls toward newer content and
extends downward. Full gate green (73 pkg, -race).

* fix(local): smooth-glide the drag-to-edge auto-scroll instead of jumping

The initial edge-scroll implementation (previous commit) applied a single
chatWheelScrollLines (5-line) jump per raw mouse-motion event, which reads as
sudden/jerky since motion events during a real drag arrive in bursts, and
stops dead the instant the physical mouse holds still even while still parked
past the edge (a terminal only reports motion on actual cursor movement).

Replaced with a self-scheduling tea.Tick chain (dragEdgeScrollTickMsg, gated by
edgeScrollSeq mirroring the existing exitConfirmSeq/copyStatusSeq idiom) that
steps a small, fixed increment (dragEdgeScrollStep=1 line) on a short cadence
(dragEdgeScrollInterval=70ms) for as long as the drag holds past the edge,
independent of whether new raw motion events keep arriving. reducedMotion still
gets the original single-bigger-step-per-event behavior (no animated glide).

Adversarial review of the new self-perpetuating tick chain (the risk being an
orphaned/stuck chain) found one real bug: a keypress mid-drag clears
m.transcriptSelection.active directly (the KeyPressMsg handler in model.go)
without going through stopEdgeScroll, leaving edgeScrollDelta stale. The
in-flight tick itself terminates safely via its own liveness check - the bug
was that the STALE nonzero edgeScrollDelta then fooled startEdgeScroll's
"already running" fast path on the NEXT same-direction drag into silently doing
nothing (no immediate step, no scheduled tick) for that whole hold. Fixed at
the press site (transcript_selection.go's mouseLeftPress case): every fresh
press now resets glide state via stopEdgeScroll, so a new drag always starts
clean regardless of how the previous one ended - a single targeted fix rather
than chasing every place transcriptSelection can be cleared.

Tests: top/bottom edge glide starts and extends the cursor over several ticks
(a single small step can land on a blank spacer row between messages, same as
real usage); the chain stops when the drag returns to the body and a stale
in-flight tick after that is a safe no-op; the keypress-interrupt regression
(reproduces the adversarial review's finding, confirms the fix). Full gate
green (73 pkg, -race).

* fix(local): soften the brand-lime accent color across the whole UI

The accent color (#caff3f) was fully saturated at fairly high lightness
(HSL: L 62%, S 100%) - the kind of value that reads as neon/glaring
everywhere it filled a block or bold-text surface, not just the one spot
originally flagged: the composer's "typed" prompt glyph, the permission
popup's focused-option badge, and the text-selection highlight all use it,
plus the spinner, the brand chip, tool-card prompts, and more.

Rather than patch each of those consumers individually, softened the single
palette source (dark theme only; the light theme's accent is a separate,
already-darkened value for its own contrast needs, untouched) to L 50% / S
80% (#ade619) - still clearly on-brand lime, and contrast against both black
(onAccent text on accent fills) and the near-black panel stays far above
WCAG AA (~14:1 and ~13:1, both comfortably over the 4.5:1 floor).

Updated TestStreamingFadePaletteMonotonic's pinned RGB assertion (it checked
the fade ramp's first bucket equals the literal old accent bytes) to the new
values. Full gate green (73 pkg, -race; make lint/go vet clean except an
unrelated stray file that isn't part of this branch or git history at all).

* fix(local): darken the brand-lime accent further per live feedback

Two prior passes (#ade619 at L50/S80, #8db620 at L42/S70) were each tested
live against the original #caff3f via raw truecolor escape codes and
confirmed too subtle in turn. Settled at L36/S62 (#759523) - a noticeably
darker, more olive lime, confirmed against the original side by side.
Contrast vs black (onAccent) and the near-black panel stays comfortably
above WCAG AA (~6.1:1 and ~5.6:1). Updated the streaming-fade test's pinned
RGB assertion to match.

* fix: address PR #350 review comments and CI smoke test failures

Smoke tests (macOS + Ubuntu): the 4 new edge-glide tests implicitly relied
on m.reducedMotion being false, but mouseTestModel() inherits it from
defaultReducedMotion(), which forces true whenever colorprofile.NoTTY is
detected - true in CI's non-TTY test runners, false in a local interactive
dev shell. Set reducedMotion = false explicitly in each of the 4 tests so
they're deterministic regardless of environment. Verified by re-running
locally under ZERO_REDUCED_MOTION=1 (reproduces the CI condition) - passes.

CodeRabbit actionable comment: handleTranscriptSelectionMouse's mouseMotion
case gated only on transcriptSelection.active, which stays true through the
async copy-command grace window after release (a non-empty selection isn't
reset until transcriptCopiedMsg lands) - so a genuine hover motion arriving
in that window would be misrouted as a drag update. The suggested fix
(gate on msg's own Button field) turned out to be wrong in a way only a
full test run caught: TestTranscriptSelectionUpdatesOnGenericMotion is a
pre-existing, deliberate test - some terminals don't restate the button on
every motion event during a real drag, so trusting the per-event Button
field breaks those terminals. Fixed properly instead: added a `dragging`
field to transcriptSelectionState, tracking the app's own press/release
bracket (true at press, false at release) independent of active and
independent of any single event's Button field. mouseMotion now gates on
dragging.

CodeRabbit nitpicks: routed the two remaining raw `m.hover = hoverTarget{}`
subchat-exit assignments through the existing clearHover() helper, so hover
invalidation stays in one place. Left the third nitpick (hit-test layout
recomputed per hover-motion tick) as a documented follow-up per the
reviewer's own "trivial/poor tradeoff" framing - a proper per-frame memoized
cache needs correct invalidation on scroll/resize/content-change to avoid
reintroducing the exact staleness class of bug already fixed twice in this
branch, and isn't worth rushing.

New tests: TestTranscriptHoverAfterReleaseDoesNotMoveSelection (the actual
bug CodeRabbit found - a post-release hover must not alter the just-copied
selection). Full gate green (73 pkg, -race); TestTranscriptSelectionUpdatesOnGenericMotion
(the test the first fix attempt broke) verified still passing.
fix: agent runtime resilience — stream stalls, weak-model tool args, and sub-agent reliability (#349)

* fix(local): defeat the macOS stale-pooled-connection hang (transport + stall-retry)

Root cause (you confirmed it: both chatgpt AND ollama hung, only on macOS): providers
fell back to http.DefaultClient, whose pooled keep-alive connections get reused on a
later turn after the server/NAT silently dropped them. The model call is a POST
(non-idempotent), so Go won't auto-retry it on a fresh conn — it blocks forever.
macOS keeps dead pooled conns around longer than Linux, so it reproduced on macOS only.

1. providerio.HTTPClient now returns a shared, tuned transport (ResponseHeaderTimeout
   60s bounds a hung POST that gets no response; IdleConnTimeout 30s stops dead conns
   from lingering to be reused). Routed openai/codex through it too (anthropic/gemini
   already used HTTPClient). Slow first tokens / long reasoning are unaffected — the
   header timeout only bounds time-to-first-response-header, not the stream body.
2. Agent loop now retries a stream idle/stall timeout that produced NO output yet, on
   a fresh connection (capped + backoff). A partial-output turn is NOT retried (would
   duplicate). Recovers any stall that slips past the transport timeout.

Local only — not pushed.

* fix(local): tolerate concatenated tool-arg JSON + widen response-header timeout

1) Weak models (minimax-m3, glm) pack MULTIPLE concatenated top-level JSON objects
   into one tool-call arguments slot ({A}{B}), which json.Unmarshal rejects with
   'invalid character {' after top-level value' (~9 failed tool calls/session).
   New recoverableToolArguments returns the first JSON value ONLY when the payload is
   one value optionally followed by more WHOLE JSON values; it rejects a bad/truncated
   first value OR trailing NON-JSON garbage ({"x":1}xyz) so genuine corruption still
   errors (adversarial-review fix). decodeToolArguments uses it at the central dispatch
   (executeToolCall) so {A}{B} runs the first object; historySafeToolCalls uses the
   SAME helper so the replayed transcript records the recovered first object (not {}),
   keeping dispatch and history consistent. Truly-malformed JSON still hits the
   existing sanitize-to-{} + retry path. Trailing objects are dropped (the model
   re-issues on a later turn).

2) Raise the shared transport ResponseHeaderTimeout 60s -> 120s so a slow cloud proxy
   (ollama *:cloud) that withholds its 200 header until first token isn't wrongly
   aborted; still bounds a truly dead reused connection.

Local only — not pushed.

* feat(local): add /turns command + raise default maxTurns 30->50

Agentic multi-step runs (build + delegate + swarm + MCP + self-verify) routinely hit
the 30-turn ceiling mid-task and never reached the later steps; removing /mode earlier
also left NO interactive way to raise the budget.

- /turns [n]: per-session tool-turn budget setter (commandGroupSession), mirroring
  /selfcorrect. Empty/status shows the current budget; a positive int sets
  agentOptions.MaxTurns (read by the run at model.go); clamped to maxTurnsCeiling=500
  to guard against typos; invalid/non-positive shows usage without changing it.
- defaultMaxTurns 30 -> 50 (matches the old 'deep' preset). Raise per-run with /turns
  for long tasks (e.g. /turns 150 for a full acceptance run).

Local only — not pushed.

* fix(local): swarm reports failed members as failed + sub-agents inherit /turns budget

Issue B — a swarm member whose child exited non-zero (e.g. exit 4 / max-turns) was
recorded [done] (swarm_status '0 failed'), so the orchestrator — which can't see the
AGENTS panel — trusted incomplete work. The specialist launcher ignored
res.Result.Status; it now surfaces a StatusError result as a member FAILURE
(errors.New(report)) so the swarm marks it [failed]. Added Coordinator.FailWithSession
and switched the member watch path to it so a failed member keeps its session id
(still drillable) and its report rides along as the failure message.

Issue A — a member hit its OWN turn limit because /turns raised only the parent's
budget; children re-resolved config.json's default. New config.SetMaxTurnsEnv exports
ZERO_MAX_TURNS, read in applyEnv -> cfg.MaxTurns; /turns now exports it so spawned
sub-agents / swarm members (which inherit the env) run with the same budget. A
non-numeric/zero env value never clobbers the configured budget.

Tests: launcher non-zero-exit -> failed (+ session kept); SetMaxTurnsEnv round-trip
+ garbage-env guard; /turns exports + clamps the env. Full gate green (73 pkg).

Local only — not pushed.

* fix(local): corrective error for unknown specialist name + clamp ZERO_MAX_TURNS

1) A model that invents a specialist name (validator-runner, file-creator,
   file-writer — none registered) got an opaque 'specialist not found' and kept
   spawning doomed sub-agents. loadManifest now lists the available specialists and
   notes that 'worker' has shell/edit while explorer/code-review are read-only, so the
   model self-corrects to a capable specialist. New availableSpecialistList helper.

2) Defense-in-depth (review nit): applyEnv now clamps an inherited ZERO_MAX_TURNS to
   MaxTurnsCeiling, so a raw shell 'export ZERO_MAX_TURNS=999999' can't bypass the
   /turns ceiling. Ceiling promoted to config.MaxTurnsCeiling (single source of truth,
   referenced by the TUI /turns clamp).

Tests: unknown-name error lists worker/explorer/code-review; applyEnv clamps an
over-ceiling env value. Full gate green (73 pkg).

Local only — not pushed.

* fix(local): surface sub-agent kill signal instead of opaque exit -1

When a sub-agent child is terminated by a signal, command.Wait returns an ExitError
whose ExitCode() is -1, losing the cause. Capture ProcessState.String() (portable,
e.g. "signal: killed") into ChildRunResult.Signal and have BuildFinalResult render
it — "Subagent terminated by a signal (signal: killed) — killed before it finished.
Likely causes: the OS out-of-memory killer ... a timeout, or cancellation." — instead
of an opaque "Subagent failed (exit -1)". The message lists causes rather than
asserting OOM, since timeout/cancellation also SIGKILL the child. A captured signal
always surfaces even if a late run_end reported a clean exit. The background task
path (which can't carry the signal name) emits the same hint for a negative exit code.

* address CodeRabbit review on #349

- loop.go: gate stall-retry on a turn-level forwardedAnything flag (wrapped
  callbacks), so a retry never re-streams on top of output already forwarded earlier
  in the turn (e.g. across the reactive-compaction retry). New test covers a
  reasoning-then-stall (collected.Text empty but output forwarded).
- loop.go: route a reissued stream's non-stall error through the SAME recovery as
  the initial stream (image-rejection wrapping / context-limit compaction) via a
  shared recoverStreamError closure, instead of returning it raw.
- exec.go: drop the hardcoded worker/explorer/code-review guidance from the
  unknown-specialist error; rely on the dynamically-rendered available list (a
  custom registry may not have those names).
- streamer.go: kill-signal message lists OOM/timeout/cancellation evenhandedly
  instead of asserting OOM (the branch also covers timeouts/cancellations).
- launcher_specialist.go + exec.go: preserve the child SessionID on a post-start
  failure too, so FailWithSession keeps those failed members drillable.
- model.go: block /turns while a run is active (mid-run change would make the
  inherited ZERO_MAX_TURNS budget inconsistent for later-spawned sub-agents).
fix(tui): sub-agents inherit the parent's live provider after a /model switch (#348)

* fix(tui): sub-agents inherit the parent's live provider after a /model switch

Swarm members and Task sub-agents run as child 'zero exec' processes that re-resolve
the provider from config.json themselves — they're passed --model but never the
parent's provider. After switching provider/model in the TUI via /model (an in-memory
change), the child still resolved config.json's stale activeProvider, landed on a
provider whose credentials didn't match the live model, and failed auth in ~3s
(exit 3, 0 tool calls, 'API key missing or invalid / can't reach the provider') — so
the spawned agent appeared then instantly disappeared.

Export ZERO_PROVIDER (config.SetActiveProviderEnv) to the live provider name on a
/model provider switch. Child processes inherit the environment, and config
resolution already maps ZERO_PROVIDER -> activeProvider, so the child resolves the
SAME profile and its credentials (env key / stored key / OAuth) — covering all three
auth methods, for both Task and swarm (both spawn via the specialist executor).

Startup needs no export: the parent and child both read config's default, so they
already match; only an in-memory switch diverges.

* fix(config): clear ZERO_PROVIDER when switching to an unnamed/default profile

SetActiveProviderEnv("") now unsets ZERO_PROVIDER instead of leaving the previous
value in the environment. Switching from a named provider back to an unnamed/default
profile otherwise kept exporting the stale provider into child zero exec processes,
which would resolve the old credentials. Extended the round-trip test with the
stale-env regression case: seed a value, switch to blank, assert both os.Getenv and
applyEnv no longer see it.

Addresses CodeRabbit review on #348.
fix(providerio): bound heartbeat-but-no-output streams so they can't hang forever (#347)

* fix(providerio): bound heartbeat-but-no-output streams (content-stall watchdog)

A stalled-but-alive upstream hung the agent indefinitely: SSE keep-alives reset the
idle watchdog (intentionally — a heartbeating upstream isn't 'dead', and aborting it
killed healthy long requests), so a stream that heartbeats while producing nothing
never tripped the idle timeout and there was no other ceiling. Observed on both
chatgpt/gpt-5.x (Codex) and ollama minimax-m3 — different provider code, same shared
providerio SSE loop — so the fix belongs here, once, for every provider.

Add a second 'content' watchdog alongside the idle one: keep-alives still reset idle
(no regression for heartbeating connections), but only REAL data lines reset the
content watchdog. If no data arrives for streamContentStallFactor (2) × the idle
timeout, abort with ErrStreamStalled instead of hanging. A slow-but-producing stream
(data between heartbeats) keeps resetting content and is never killed.

Contained to internal/providers/providerio — no provider/caller changes.

* fix(providerio): surface ErrStreamStalled in callers + widen flaky test margins

Address review:
- All four provider stream handlers (openai, codex, anthropic, gemini) now treat
  ErrStreamStalled in the same branch as ErrStreamIdle, via a new
  providerio.StreamTimeoutMessage helper that gives the stall a distinct, accurate
  message (it reports the content window and does NOT claim the upstream stopped
  sending data — keep-alives were still arriving). Previously a stalled stream fell
  through to the generic provider-error path.
- Widen the content-watchdog test timing margins (idle 100ms, data/keepalive every
  30ms) so CI/GC jitter can't trip the idle watchdog and mask the content path.
- Add a StreamTimeoutMessage unit test.
test(providers): isolate the OAuth store in the chatgpt Codex routing test (#346)

TestNewRoutesChatGPTCatalogToCodexProvider asserts the chatgpt-account-id header is
empty when no OAuth login is stored, but never redirected the token store — so on a
developer machine with a real chatgpt login it read that login and failed (it still
passed in CI, where no token exists). Point ZERO_OAUTH_TOKENS_PATH at an empty temp
path, mirroring TestNewRoutesChatGPTCatalogWithStoredAccountID, so the test is
deterministic regardless of the developer's stored credentials.
fix: stream Codex reasoning + drop swarm agents on their own completion (#345)

Two agent-visibility fixes surfaced diagnosing a 20-minute gpt-5.5 step and an
'agents never disappear' report.

A) Codex Responses path streamed no reasoning, so a long thinking phase produced
   zero visible output and read as a hang (the activity clock never advanced).
   Root cause: the request never asked for a reasoning summary and the parser had
   no case for reasoning deltas. Now request reasoning.summary="auto" and forward
   response.reasoning_summary_text.delta as StreamEventReasoning — the existing TUI
   handler renders it live and refreshes the activity clock.

B) A finished swarm member stayed in the AGENTS panel until the whole turn ended.
   Now it drops once ITS OWN task completes (fade over the linger window, then
   remove), independent of the overall run — matching how finished specialists
   already behave. Running members and mid-flight collect are unaffected.
fix(swarm): constrain agent_type to the registered roster via a dynamic enum (#344)

* fix(swarm): constrain spawn/handoff agent_type to the registered roster via enum

swarm_spawn and swarm_handoff described agent_type / to_agent_type as a free-form
string with only an 'e.g. teammate, subagent' hint, so a model could pass an
unregistered type (e.g. 'worker') and only discover it was invalid from the runtime
'unknown agent type' error — wasting tool calls, especially on weaker models.

Set the parameter's enum dynamically from the live roster (Registry.AgentTypes()),
so the schema advertises the valid set (built-ins plus any user-registered agents)
up front and an invalid type can't be sent. Falls back to a free-form string when
the roster is unavailable, so the tool never advertises an empty, un-satisfiable
enum. The runtime 'available agent types: …' error is kept as a backstop.

* test(swarm): also assert handoff to_agent_type enum picks up a custom roster type

Address review: the custom-type recheck only re-read spawnTool, so a regression
leaving handoffTool on the built-in list would have passed.
fix(openai): always send message content so strict OpenAI-compatible servers accept it (#343)

Some OpenAI-compatible endpoints (e.g. glm-* on Ollama-cloud) reject a request whose
message 'content' is absent or null with HTTP 400 'invalid message content type:
<nil>'. The chat-completions mapper relied on 'content,omitempty', so a message with
empty text (a tool result, an assistant turn that only makes tool calls, or a
sub-agent that failed with no output) serialized with no content field at all.

- Drop omitempty on chatMessage.Content and always set it (to "" when there is no
  text), so contentless messages serialize as "content":"" instead of being
  dropped. Standard OpenAI/xAI/groq already tolerated the omission; this makes the
  strict servers work too.
- Skip a degenerate assistant turn that has neither text nor tool calls, mirroring
  the Anthropic/Gemini mappers (which already drop empty turns).

Fixes the failure seen on glm-5.2:cloud after a sub-agent failed with empty output.
Document source-build sandbox helpers (#342)

Clarify that Linux source builds need the zero-linux-sandbox helper on PATH for native sandboxing, while macOS does not need an extra helper and Windows can self-dispatch from zero.exe.

Also document optional release-style helper builds for Linux and Windows.

Tested: git diff --check
fix(opengateway): correct gateway host, make it the recommended default (#341)

OpenGateway pointed at gateway.gitlawb.com, which does not resolve
(NXDOMAIN), so every request failed with "no such host". The live gateway
is opengateway.gitlawb.com — a flat OpenAI-compatible endpoint
(/v1/chat/completions, Authorization: Bearer ogw_live_…) that smart-routes
by model id across its upstreams (xiaomi-mimo, minimax, qwen, google,
nvidia, z-ai).

- catalog: fix base URL to https://opengateway.gitlawb.com/v1, default model
  to mimo-v2.5-pro; add a Recommended descriptor field and hoist OpenGateway
  to the top of the catalog so it is the first/badged pick everywhere.
- models: replace the curated model list with the gateway's real upstream
  models; fix the stale model-discovery fallback host.
- providers catalog: sort recommended-first (CLI + snapshot) and render the
  ★ … (recommended) badge; same badge in the TUI /provider wizard and the
  setup onboarding list.
- providerhealth: OpenGateway's flat /v1/models 404s by design, so probe its
  public /health endpoint for connectivity instead of reporting a false fail.
- tests: update catalog order golden + transport/discovery expectations; add
  coverage for the recommended provider and the health-endpoint override.

Co-authored-by: Kevin Codex <zero@gitlawb.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
chore(launch): MIT license, windows-arm64 install guard, TUI TTY guard (#340)

* chore(launch): MIT license field, windows-arm64 install guard, TUI TTY guard

Three launch-readiness fixes the docs cleanup doesn't cover:

- package.json: set "license": "MIT" (was the placeholder "SEE LICENSE IN
  LICENSE"), matching the LICENSE file and the README badge.
- scripts/postinstall.mjs: skip gracefully on windows-arm64. (win32, arm64)
  resolves to a valid platform/arch but the release matrix ships no
  windows-arm64 artifact, so the installer would download a 404 and hard-fail
  npm install. Treat it like any unsupported target (warnSkip, exit 0) and point
  to the x64 build (which runs under emulation on Windows on ARM) or source.
- internal/tui/run.go: fail fast when stdin is not a terminal. The interactive
  shell otherwise blocks forever in the Bubble Tea event loop on piped/redirected
  input (e.g. `echo "" | zero`); now it prints guidance toward `zero exec` and
  exits non-zero. Dependency-free ModeCharDevice check (no x/term added).

Tests: windows-arm64 skips with exit 0; the interactive shell returns non-zero
(not a hang) on non-TTY stdin.

* fix(tui): use term.IsTerminal for the stdin guard; pin exit code in test

Address review on the no-TTY guard:
- Replace the os.Stdin.Stat()/ModeCharDevice heuristic with term.IsTerminal
  (github.com/charmbracelet/x/term, already in the module graph via bubbletea).
  It is a true TTY check — it rejects pipes, regular files, and non-terminal
  char devices like /dev/null — and fails closed: anything not a verified
  terminal blocks the interactive shell.
- The test now asserts the documented exit code 2 from the guard, not just a
  non-zero result, so it proves the stdin guard fired.
Clean up public release docs (#339)

Rewrite the README around the initial public-release user flow, add the logo asset, and refresh install/update documentation.

Remove internal planning, audit, design, and work-split documents from the public docs tree.

Update stale documentation references and workspace seed expectations to point at public docs.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/workspaceseed

Tested: git diff --check
feat(reasoning): typed per-provider reasoning capability from a models.dev catalog (#338)

* feat(reasoning): typed per-provider reasoning capability from a models.dev catalog

Providers describe reasoning control with incompatible concepts — OpenAI a
discrete effort enum (split by minor version), Anthropic and Gemini 2.5 a
thinking-token budget, some models only a thinking on/off toggle — which a flat
effort string cannot represent and a model-name heuristic cannot detect.

Add internal/reasoning: a Capability type (a model's reasoning flag plus its
typed Controls — effort/budget_tokens/toggle) and a Catalog that looks capability
up by provider + api model id. The data is an embedded, trimmed snapshot of the
community capability database (first-party providers only; routers excluded since
they carry generic/stale option lists), so detection is offline and exact instead
of guessed.

The package depends only on the standard library, so the model registry and
provider adapters can consume it without an import cycle. This change is purely
additive — nothing is wired into the live resolution path yet.

Tests pin the per-version ground truth (gpt-5 minimal-not-none, gpt-5.1
none-not-minimal, gpt-5.1-codex-max xhigh, gpt-5-pro locked to high; Anthropic
budget-only legacy vs effort-only newer with the budget removed; Gemini 2.5
budget/toggle vs Gemini 3 effort) and that every reasoning model Zero ships today
is covered by the snapshot.

* fix(reasoning): address review — presence-aware budget bounds, deep-copy lookup, first-party-only snapshot

- Control.Min/Max are now *int so an explicit bound is distinct from an omitted
  one: Gemini's `min: 0` ("thinking can be disabled") and Anthropic's missing
  max (unbounded) are preserved instead of both collapsing to 0. Budget() becomes
  BudgetControl() returning the control so callers read the pointers.
- Catalog.Lookup returns a deep copy (clone) of the matched Capability, so a
  caller can no longer mutate the shared embedded catalog through the returned
  Controls / Values slices or budget pointers.
- Drop the google-vertex section from the snapshot: it re-hosts third-party MaaS
  models (Anthropic/Moonshot/OpenAI/DeepSeek/Qwen/Meta), violating first-party
  -only. google (AI Studio) already covers first-party Gemini, so the gemini
  provider kind resolves there. Snapshot 158 -> 123 models, 16.8 KB.

Tests pin the explicit min: 0 preservation, the nil max on budget-only Anthropic
models, and that a mutation of a Lookup result does not leak into the catalog.

* fix(reasoning): address round-2 review — accessor deep-copy, max tier, provenance

- EffortControl/BudgetControl now return a cloned Control, so a caller holding a
  Capability that shares state with the catalog cannot mutate Min/Max pointers or
  the Values slice through an accessor result (CodeRabbit). Lookup already deep
  -copies; this closes the accessor path too.
- Add modelregistry.ReasoningEffortMax ("max") + accept it in ValidReasoningEffort,
  so the snapshot's "max" tier (e.g. gpt-5.1-codex-max, newer Anthropic) has a
  constant to map to. No curated model lists it yet.
- Snapshot provenance: add a _fetched date and a regeneration recipe (documented
  in catalog.go), so refreshes are reproducible/auditable.
- Document that Lookup takes the API model id (wire name), not the friendly
  registry id, and that the match is exact (no case-fold/prefix-strip).
- Record the source-of-truth intent in the package doc: this catalog is the
  intended authoritative source; modelregistry's name-pattern inference is demoted
  to a fallback when it is wired in (a later change). Rename the `cap` builtin
  shadow to `entry`.

Tests pin the accessor deep-copy isolation.
feat(tui): remove the /mode command (superseded by /model + /effort) (#337)

The /mode presets bundled a hardcoded Anthropic/Google model + reasoning effort +
turn budget, so on other providers (Ollama-cloud, xAI, GPT-5, custom) /mode would
switch to a model the user isn't authenticated to. With /model (any provider's
models) and /effort (reasoning effort) covering the same ground flexibly, /mode is
redundant in the TUI.

Removes the /mode slash command, its handler, the mode picker, and the dispatch +
stale comments; updates affected tests. The CLI `--mode` flag and internal/
modelregistry mode presets are kept (still used by headless exec).
Polish TUI transcript rendering (#334)

* Polish transcript rendering

Tighten transcript spacing, collapse noisy permission/tool rows, and render tool activity with cleaner action-oriented labels.

Improve code and diff rendering with markdown highlighting, cleaner command output blocks, and grouped exploration summaries.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/tui

Tested: git diff --check

* Fix grep exploration rendering on Windows

Keep search query text out of path normalization so regex escapes render consistently across platforms.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/tui

Tested: git diff --check

* Address transcript rendering review

Cache highlighted streaming markdown so closed code blocks are not re-lexed on every live render.

Tighten bare-code detection to avoid highlighting ordinary prose, restore manual permission audit rows, and make exploration details expandable.

Also align diff content/header predicates and use display-width truncation for compact tool output.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/tui

Tested: env GOCACHE=/tmp/zero-go-cache go test -race ./internal/tui

Tested: env GOCACHE=/tmp/zero-go-cache go vet ./...

Tested: git diff --check
fix(openai): forward reasoning effort to the Codex Responses API (#336)

The Codex provider speaks the Responses API, where reasoning_effort is nested
under `reasoning.effort` rather than sent as a top-level field. buildResponsesRequest
never set it, so a user's chosen effort was silently dropped for every Codex
model — the request always ran at the model default.

Add a `reasoning` object to the Responses request and populate it from the
request's effort, reusing the chat path's openAIReasoningEffort normalizer so
only API-accepted values (minimal/low/medium/high) are sent and an empty or
unsupported effort omits the field (no empty object, no 400).
fix(modelregistry): one source of truth for a model's reasoning efforts (#335)

The /effort picker and the run-time effort resolver disagreed about which
tiers a model supports. Registry.ReasoningEfforts falls back to name-based
inference (reasoningEffortsForModelName) when the catalog lists no efforts,
so the picker shows controls for proxy-served GPT-5 / Codex / o-series
models. EffectiveReasoningEffort read model.ReasoningEfforts directly and
never saw that fallback, so it coerced the same request to "none" — the
picker advertised a tier the resolver silently dropped.

Route both through a single effectiveReasoningEfforts helper so they can
never diverge. A model the catalog enumerates with no efforts but whose
name is a known reasoning family now has its requested effort honored end
to end; non-reasoning models still resolve to "none".

Also drop the orphaned, stale NOTE above forwardedReasoningEffort claiming
effort "is not yet forwarded" (it is) and restore the reasoningEffortNotice
doc comment to its own function.
feat: context-aware compaction + usage gauge for all models (#332)

* fix(agent): enable auto-compaction for all models, not just registered ones

Auto-compaction keys off the model's context window (enabled = ContextWindow > 0),
resolved only from the curated registry. Unregistered models — GPT-5/Codex, xAI,
Ollama-cloud, custom endpoints — resolved to 0, so both the proactive (~80%) and the
reactive post-overflow compaction were silently disabled and long sessions overflowed.

- TUI modelContextWindow now also consults live-discovered windows (accurate for
  proxy/custom models once /model has discovered them); unknown still returns 0 so
  display gauges show no guessed denominator.
- New modelregistry.AgentContextWindow applies a positive FallbackContextWindow (200k)
  ONLY on the compaction-enable path (TUI run + CLI exec/spec), so compaction is on for
  every model while display stays accurate-or-empty. Exact windows always win.

* feat(tui): show context usage (used / total + % gauge) for all models from launch

The sidebar/status-line context gauge only shows a total + fill % when the active
model's context window is known. For proxy/custom models (GPT-5/Codex, xAI, Ollama-
cloud) the window isn't in the registry, so it showed only a used-token count.

Warm model discovery for the active provider in Init() (background, non-blocking) so
the active model's window is learned at launch and the gauge renders 'used / total
tokens' + the fill % for every model — not just catalogued ones. Builds on the
discovered-window resolution from the compaction fix.

* fix(tui): address review — agent fallback on model-switch + active-provider window

- Apply modelregistry.AgentContextWindow to /model and /mode pre-switch compaction
  requests (TargetContextWindow), so the 'compaction for all models' behavior also
  covers undiscovered/custom switch targets, not just the active run.
- Scope the live-discovered context-window lookup to the active provider first
  (then others), so a model ID shared across providers resolves to the provider in
  use rather than an arbitrary match.
- Tighten the resolution test to compare against the registry's actual gpt-4.1
  window instead of != FallbackContextWindow.

* fix(cli): give provider-discovered context windows precedence in headless exec

Address the remaining review point: CLI exec/spec runs collapsed every uncatalogued
model to the 200k fallback, ignoring its real window. resolveAgentContextWindow now,
on a registry miss, queries the provider's live model list (resolving the credential
from inline/stored/env) to get the model's actual context window before falling back.
Discovery runs only on a registry miss (catalogued models pay no latency), is bounded
by a 5s timeout, and degrades to the fallback on any error so a headless run is never
blocked or failed.
feat(tui): dim the transcript backdrop behind overlays for visibility (#333)

Slash-command/file palettes (and pickers/wizards) were composited directly over the
live transcript with no separation, so the chat bled through around the box and the
overlay was hard to read. Add a scrim: when an overlay is open, dim the transcript
backdrop (strip each line's colors and re-render faint) before compositing the bright
overlay on top. Header and composer render separately and stay bright. Text is
preserved (just dimmed), so context remains readable behind the palette.
feat(tui): compact one-line /model switch confirmation (#331)

The model-switch confirmation printed a 6-7 line block (Switched model. / model: /
provider: / api model: / effort: / saved:). Collapse it to a single summary line —
'<model> · <provider>[ · effort …][ · saved]' — keeping the deprecation/redirect
notice line when present. Tests updated to the new format.
fix(model): expose reasoning effort for GPT-5 / Codex / o-series (#330)

/effort showed no controls for ChatGPT (GPT-5) because those models aren't in the
curated registry and the OpenAI catalog entries carry no reasoning efforts, so
Registry.ReasoningEfforts returned nil even though GPT-5 supports reasoning_effort.

Add a name-based fallback: when a model isn't enumerated with efforts, infer them for
known reasoning families — GPT-5 / gpt-5.x Codex (minimal/low/medium/high) and the
o-series (low/medium/high). Non-reasoning models (GPT-4.1/4o, local models) stay empty,
so /effort still hides controls where they don't apply.
feat: encrypted provider credentials + provider-aware /model (#329)

Encrypted credential storage
- internal/securefile: AES-256-GCM at-rest crypter (fail-closed, atomic, locked).
- internal/credstore: provider API-key store, keyring-first with an encrypted-file
  fallback; plaintext only via an explicit ZERO_CRED_STORAGE=file opt-out.
- Provider API keys no longer live in config.json: captured straight into the store
  from the wizard/CLI setup, and any existing inline plaintext key is migrated to the
  store on launch (fail-soft; stripped only after the store write succeeds).
- buildProvider and every model/provider switch reload the credential (stored key,
  env var, or OAuth bearer), so a stored-key provider always authenticates.
- `zero auth logout <provider>` now also removes the stored API key and its marker.

/model and /provider
- /model lists every authenticated provider (filtered to those with a usable
  credential), grouped per provider under section headers.
- Each provider's models are live-discovered (its real served models) rather than a
  static catalog; local providers show only the models actually pulled.
- Selecting a model from another provider switches provider and model together.
- /provider offers keep / replace / remove when a provider already has a stored key.

Gated throughout: go build, go vet ./..., go test ./... -race, lint.
feat(tui): tabbed ask_user questionnaire in the composer with suggested answers (#327)

* feat(tui): tabbed ask_user questionnaire rendered in the composer

Redesign the interactive ask_user prompt to match the requested mockup: when a
question is raised the composer text box becomes the questionnaire.

- Multi-question prompts render as a row of TABS (one per question + a trailing
  Confirm tab). Tab / Shift+Tab switch questions, answers are given in any order,
  and Enter on Confirm submits them all. A single-question prompt submits on
  answer (no Confirm step) and shows no tab row.
- Each option can carry a one-line DESCRIPTION (contract: per-option
  optionDescriptions, or option objects {label, description}); options render
  numbered with the description dimmer underneath and the recommended one tagged.
- Per-question optional `header` gives each tab a short title (falls back to a
  trimmed question).
- Rendered in the composer/footer region (footerView), replacing the text box
  while active, instead of a scrolling transcript card.
- Keys: Tab move · ↑↓ select · Enter confirm · Esc dismiss; a printable key in
  the picker drops into free-text; Esc from "type your own" returns to the picker;
  multi-select questions are free-text with the options shown as suggestions.
- Headless unaffected (zero exec never wires OnAskUser).

Removed the old single-question sequential state (cursor/typing/index,
renderFocusedAskUserPrompt, resolveAskUser). Tests rewritten for the tabbed flow
(picker default, type-your-own, multi-question tabs + Confirm, Esc dismiss,
descriptions render). make build / go vet / go test ./... -race / make lint green.

* fix(tui): ask_user questionnaire renders on the black terminal canvas

It was painting a gray panel background (styledBlockFill with zeroTheme.panel +
onPanel-wrapped foregrounds). Since the questionnaire replaces the composer, it
should match it: bare foregrounds on the terminal canvas (black) with the
composer's lineStrong border and no fill. The lime cursor/badge highlights and
the recommended tag stay.

* fix(tui): address PR review — schema/parser alignment, single-question Tab

- ask_user schema: options.items is declared as string, so advertise only the
  string form (descriptions go via the parallel optionDescriptions array). The
  parser stays object-tolerant defensively, but the schema no longer tells
  strict-schema providers to send objects it would reject.
- moveAskUserTab no-ops for single-question prompts (no tab strip / Confirm tab),
  so Tab/Shift+Tab can't move the prompt into the hidden Confirm state. Test added.
fix(tui): paint transcript selection once, not twice (#328)

Selecting text in the transcript lit up in two places: the real selection
plus a copy shifted right by the reading-column gutter (e.g. selecting "help"
also highlighted "today").

Root cause: assistant, user, and reasoning rows self-painted the selection
highlight in their render functions using the UNSHIFTED textStart, but the
selection points (anchor.x/cursor.x) are in the gutter-shifted screen
coordinate the mouse maps to. So the self-paint landed gutter cells off, and
finalizeTranscriptBodyRow then painted the highlight AGAIN at the correct
shifted position — two highlights, one gutter apart. The rendered/toolResult/
specialist rows were already converted to paint-once-at-finalize; these three
were left behind.

Fix: stop self-painting in renderSelectableUserRow, renderSelectableAssistantRow,
and renderSelectableReasoningBlock. They now return the canonical renderRow
output (already line-aligned with their selectable spans) and let
finalizeTranscriptBodyRow be the single painter, in the same shifted coordinate
the mouse uses. Removes the now-dead renderTranscriptSelectableText /
renderTranscriptSelectableMarkdownText helpers.

Regression test TestTranscriptSelectionPaintsHighlightOnceNotTwice selects a
sub-range of an assistant row and asserts the selection style is emitted exactly
once; it fails on the pre-fix code (painted 3x, including the gutter-shifted copy).
feat(tui): ask_user suggested answers with a recommended default (#326)

* feat(tui): suggested answers with a recommended default for ask_user

When the agent asks a clarifying question mid-task, it can now offer 2-4
suggested answers and mark one recommended; the interactive TUI renders a
selector (arrow keys, lime cursor, "(recommended)" tag) with the cursor resting
on the recommended option, plus a trailing "✎ Type my own answer…" entry that
drops into the existing free-text composer. Whichever the user picks — a
suggested option's text or their typed answer — flows through the same answer
channel the agent loop already waits on.

Optional and backward-compatible: a question with no options renders the plain
free-text prompt exactly as before. Headless `zero exec` is unaffected (it never
wires OnAskUser; the non-interactive best-assumption fallback stands).

- contract: agent.AskUserQuestion / tools.AskUserQuestion gain Recommended;
  the tool schema advertises optional options + recommended; parser keeps
  recommended only when it resolves to one of the options (canonical text).
- system prompt: tells the model it MAY supply options + a recommended one.
- TUI: pendingAskUserPrompt gains cursor/typing; ask_user_prompt.go holds the
  selector logic mirroring permission_prompt.go; renderFocusedAskUserPrompt
  renders the picker or the free-text prompt.

Tests: selector defaults to recommended and returns its text; "type my own"
falls back to free-text and returns the typed text; no-options stays plain
free-text. make build / go vet / go test ./... -race / make lint green.

* fix(tui): ask_user — single input, Esc steps back from "type my own"

Two UX fixes from interactive testing:

- No double display: the focused ask card no longer echoes the in-progress
  free-text answer (it was shown both inside the card AND in the composer text
  box). The composer is now the single input; the card just shows the question
  and a hint. renderFocusedAskUserPrompt no longer takes the input string.

- Esc from "type my own" returns to the selector for that question instead of
  cancelling the whole questionnaire (escapeAskUser); a question with no options,
  or the selector itself, still cancels on Esc as before.

Tests: type-my-own asserts the card does not echo the typed text and the hint
flips to "type your own answer"; new test covers Esc returning to the selector
(no cancel, no answer delivered) then selecting a suggested option.

* fix(tui): ask_user review fixes — multi-select, selector typing, dead code

Address the three confirmed findings from the code review:

- multi-select no longer silently narrowed to one option: a single-pick
  selector cannot represent MultiSelect, so a multi-select question now renders
  as free-text with its options surfaced as suggestions; the user types one or
  more and the answer is returned verbatim (syncQuestionState; escapeAskUser and
  the renderer updated to match).

- typing in selector mode no longer discarded: a printable keystroke while the
  selector is showing flips into free-text and captures the key (model.go key
  capture), instead of accumulating in a hidden input that Enter then overrode
  with the highlighted option.

- removed dead submitAskUserAnswer (the Enter handler now routes through
  confirmAskUser; the orphan had no callers).

Tests: multi-select falls back to free-text and returns the typed answer;
a printable key in the selector switches to free-text and is captured. Full
gate green (build / vet / go test ./... -race / make lint).

* fix(tui): address PR review — element-wise option compare, clearer Esc copy

- ask_user_test: compare option slices with slices.Equal instead of
  strings.Join, so the parser test can't be fooled by ["A,B"] vs ["A","B"]
  or nil vs [""].
- ask_user prompt: the Esc hint said "skip", which reads like "skip this
  question" on a multi-question prompt even though Esc ends the rest of the
  questionnaire (remaining answered by best-assumption). Reworded to "skip the
  rest" in the selector and free-text hints; "type my own" k…
The FILES roster was fed only by changedFiles on write_file/edit_file/
apply_patch results — but agents that scaffold through exec_command/bash
(npm create, heredoc writes) or delegate to subagents produce no such
results, so a whole build could touch dozens of files and the panel
stayed empty.

Ask git instead: Init takes a baseline `git status --porcelain
--untracked-files=all` snapshot (pre-existing dirt never shows), and a
re-sweep after each command-tool result and at turn end merges any newly
dirty paths into the roster, with a diffstat from `git diff HEAD
--numstat` for tracked files. Untracked-files=all matters: plain
porcelain collapses a new directory to "dir/", which is useless as a
FILES row. Sweeps are single-flight, time-boxed, and latch off in
non-git workspaces. A git-only file has no edit cards, so its drill-in
opens directly on the full-file view.

feat(tui): FILES sidebar section with click-to-select and file drill-in

The right context sidebar gains a FILES section between PLAN and
ACTIVITY: the workspace files the session has touched, newest first,
with an A/M/✗ badge, an aggregated +added/−removed diffstat, and a
pulsing row for the file whose write is streaming right now. The roster
is recovered on demand from tool-result rows' changedFiles (persisted to
the session payload and restored on rehydrate), so it survives /resume
and can never drift from the transcript — the same derive-from-rows
pattern the swarm AGENTS roster uses.

Clicking a row selects the file: its row gets an accent ▸, its edit
cards tint accent in the chat, and the transcript scrolls to the most
recent one. A second click (or any FILES click while the view is open)
opens a drill-in reusing the subchat pattern — the chat column body
swaps to the file's stacked full-depth edit cards ("edit N of M"), f
toggles to the syntax-highlighted on-disk file with ▎ markers on
session-added lines, d back to diff, Esc returns to the chat at its
saved scroll position; a second Esc clears the selection. The body swap
happens inside transcriptBodyItems and the nav bar replaces the pinned
title bar, so the scroll engine, viewport, and mouse hit-testing stay
consistent for free.

fix(oauth): make xAI / Hugging Face OAuth actually launch from the wizard (#355)

The provider wizard offered "Sign in with OAuth" for xAI and Hugging Face, but
clicking did nothing: the login managers were built without an env, so the preset
opt-in (ZERO_OAUTH_ALLOW_PRESETS) read as unset, ResolveConfig errored before any
browser step, and the error was never rendered on the provider list. Only ChatGPT
worked, because its login path force-enables presets.

Add ManagerOptions.AllowPresets, which layers the opt-in onto the manager env
(snapshotting the process environment so ZERO_OAUTH_<NAME>_* overrides survive
envValue's hermetic-map rule) without the operator exporting the flag. Set it on
every user-initiated OAuth manager: the wizard loopback login, the device-code
prepare/complete, the post-login token refresh, the runtime resolver that
authenticates model calls, and `zero auth login`. This fixes xAI end to end (it
ships a public client_id, so the browser now opens).

Also surface a failed OAuth attempt on the provider list (renderProviderStep) so
the click is no longer a silent no-op, with a Hugging Face hint pointing at app
registration + ZERO_OAUTH_HUGGINGFACE_CLIENT_ID (HF ships no public client_id, so
it still requires that one env var by design).
feat(tui): interactive theme picker + color theme catalog (#354)

* feat(tui): interactive theme picker + color theme catalog

Bare `/theme` now opens a popup that live-previews each palette as the cursor
moves and applies on select (Esc reverts), matching /model and /effort. Adds ten
built-in color themes alongside the dark/light built-ins — dracula, nord, gruvbox,
tokyo-night, catppuccin, one-dark, solarized-dark, rose-pine, everforest, and
solarized-light — plus a reworked light palette. Every palette is contrast-audited
to WCAG AA; the contrast tests now loop the whole registry.

Palettes and an ordered registry live in a new internal/tui/theme_palettes.go (now
the sole home of hex literals); selection, the picker, /theme <name>, --theme, and
ZERO_THEME all resolve through it. The whole frame is painted with the active
theme's surface (tea.View.BackgroundColor) so every theme is legible on any
terminal — a light theme's dark text no longer lands invisibly on a dark terminal,
and color themes show their real surface.

The chosen theme persists to user config (preferences.theme) and is reapplied at
startup, below the --theme flag and ZERO_THEME.

* fix(tui): address CodeRabbit review on the theme catalog

- CHANGELOG: reconcile the --theme bullet with the named themes (was still
  documenting {auto|dark|light}).
- /theme usage string advertises the list and auto forms (/theme list is still
  accepted) so /help matches the command surface.
- Theme-persistence test parses the written config and asserts preferences.theme
  directly instead of a raw substring, so a wrong-key regression fails.
fix(tui): require a second Esc press to cancel a running turn (#352)

* fix(tui): require a second Esc press to cancel a running turn

A single stray Esc during an active run cancelled it instantly with no
chance to reconsider - e.g. a press meant to dismiss an overlay that had
already closed. Ctrl+C already guards app-exit with a double-press
confirmation (exitConfirmActive/exitConfirmSeq); Esc now gets its own
independent confirmation (cancelConfirmActive/cancelConfirmSeq) guarding
run-cancellation specifically, since the two are different actions with
different consequences armed by different keys.

Mirrors the existing seq-gated tea.Tick pattern: first Esc arms a 3s
window and shows "Press Esc again to cancel" in the footer; a second Esc
within the window cancels the run; letting it expire, or the run finishing
on its own, disarms without cancelling.

Updated the three existing tests that assumed single-press cancellation
(TestEscCancelsPendingRun -> TestEscRequiresSecondPressToCancelPendingRun,
TestEscCancellationLeavesVisibleMarker, TestEscCancelRecordsSessionError,
TestCancelledRunFlushesCheckpointSessionEvents) and added
TestEscCancelConfirmationExpires mirroring the Ctrl+C expiry test.

* fix: pre-push review findings on the Esc cancel-confirmation gate

Ran an adversarial review before opening the PR. Three independent
reviewers converged on the same root defect: unlike exitConfirmActive
(disarmed by any key other than Ctrl+C), cancelConfirmActive had no
"anything else disarms it" safety net, so it behaved as a plain 3s timer
rather than a true immediate-second-press gate. Concretely:

- Typing, Ctrl+O, or any other non-Esc key left it armed, so a later,
  unrelated Esc press could silently cancel the run.
- A mid-turn ask_user or permission prompt lands asynchronously and is
  checked earlier in the Esc handler than the cancel-confirm block, so it
  silently "stole" the confirming press (denying the prompt instead) while
  leaving cancelConfirmActive armed for a subsequent, unrelated Esc to act
  on.
- Mouse clicks resolving a permission prompt or entering a subchat had the
  same gap.

Fixed by mirroring the Ctrl+C pattern: any non-Esc key disarms it (model.go,
next to the existing exitConfirmAction reset), and any left/right mouse
click disarms it too (mouse.go — scoped to clicks, not hover/motion, since
motion fires continuously and would otherwise defeat the window whenever
the mouse sits over the terminal). Within the Esc handler itself, restructured
to capture whether this press was really a confirm *before* any of the
earlier branches (subchat, MCP wizard, ask-user, permission, picker,
suggestions, queued-message, detailed-transcript) can run, then disarm
unconditionally — so an Esc consumed by any of those no longer leaves a
stale confirmation for a later press to trip.

Also updated two now-stale help strings the review flagged: the `?`
overlay's Esc row and pickerBusyText()'s "press Esc to cancel" hint, both
of which still described the old single-press behavior.

Added TestEscCancelConfirmationDisarmsOnInterveningKey (mirrors the
existing Ctrl+C equivalent) and
TestEscCancelConfirmationDisarmsWhenStolenByAskUser covering the two
confirmed gaps.

* fix: address CodeRabbit review comments on PR #352

- model.go: the first Esc (arming the cancel confirmation) was clearing the
  composer draft immediately, even though nothing had actually been
  cancelled yet — a leftover from the old single-press behavior, where
  clearing the draft and cancelling the run happened atomically as one
  action. Now that cancellation is two presses, only the confirming second
  Esc (or a plain Esc with no run pending) clears the composer; arming
  preserves whatever the user was typing, mirroring how Ctrl+C already
  preserves a draft (TestCtrlCClearsComposerBeforeExitConfirmation).

- clipboard.go: routePaste (bracketed paste and right-click paste) never
  disarmed a stale cancelConfirmActive — it isn't a tea.KeyPressMsg, so it
  bypassed the generic "any non-Esc key disarms it" hook added in the
  previous commit. A paste is a deliberate action like typing or clicking,
  so it should disarm the confirmation too; otherwise a later, unrelated
  Esc could silently cancel the run.

New tests: TestEscArmingCancelConfirmationPreservesComposerDraft,
TestPasteDisarmsCancelConfirmation.
fix: cap unbounded exec_command output buffer to prevent OOM kill (#353)

* fix: cap unbounded exec_command output buffer to prevent OOM kill

execOutputBuffer.data accumulated every byte a backgrounded exec_command
session wrote, with no size cap, unlike buffer.recent which is correctly
bounded to recentExecOutputBytes for the /ps preview. drainString() only
clears data when the agent actually polls that session again — so a
long-lived background session nobody polls (e.g. a dev server left running
after the run that started it was cancelled) grows this buffer forever as
long as the process keeps writing, with no ceiling.

Traced this directly to a real crash: a session that had been running for
~5.5 hours (an earlier turn invoking swarm agents got cancelled mid-flight,
per that session's own event log) accumulated to ~42.7GB of compressed
memory, at which point macOS's memorystatus killed the process outright
("killing zero due to low-swap").

Fixed by capping data at maxExecOutputBufferBytes (2MiB), trimming from the
front like recent already does, and surfacing a one-time truncation notice
on the next drain so data loss is visible rather than silent.

* fix: pre-push review findings on the exec_command buffer-cap fix

Ran an adversarial review before opening the PR. It found the truncation
notice added alongside the buffer cap didn't actually work: prefixing
execOutputTruncatedMessage into drainString()'s text meant the notice
always sat ~2MiB before the end of the combined output, but the tool's
own downstream truncateExecOutput() keeps at most a 400KB tail (even at
the maximum allowed max_output_tokens) — so the notice was reliably
swallowed, or chopped into an unreadable fragment at smaller budgets.
Verified with direct reproductions against the real functions.

Fixed by moving the signal out of the text stream entirely:
- execOutputBuffer gains consumeTruncated() (read+reset, called once per
  collect()) and peekTruncated() (read-only, for status views) instead of
  injecting a marker into the drained bytes.
- collect() now returns (string, bool); both call sites thread the bool
  through to execToolResult, which sets meta["output_buffer_truncated"]
  and appends the notice to the response body *after* truncateExecOutput
  runs, so it can never be re-truncated or land in a discarded region.
- Also flagged: a session torn down without ever being polled again after
  truncation loses the signal entirely, since nothing drains/logs it on
  teardown. Full audit-trail logging felt like overkill for a soft
  transparency signal on top of a hard memory-safety fix, but exposed
  peekTruncated() on ExecSessionSnapshot and surfaced it in the /ps row
  (background_terminals.go) so it's visible any time a still-running
  session is checked — covers the common case (the review's own scenario:
  a long-lived dev server nobody's polling but that's still alive) even
  though a session reaped before ever being looked at is still a gap.

New tests: reworked TestExecOutputBufferCapsUndrainedData for the
consume/peek API, and TestExecToolResultSurfacesBufferTruncationOutsideByteBudget
reproducing the review's exact failure case (max_output_tokens=1) and
proving the notice now survives it.
revert(local): restore the original bright-lime accent color (#351)

Restores accent to #caff3f (the pre-PR#350 value), undoing the three-round
brightness reduction (#ade619 -> #8db620 -> #759523) merged in PR #350. Only
the accent token changes - the hover-highlight color (a separate amber
token) and every other PR #350 fix (subchat selection, drag-to-edge
auto-scroll, the dragging-flag fix) are untouched.

Full gate green. Local only - not pushed.
fix(tui): subchat mouse selection, hover highlighting, and drag-to-edge auto-scroll (#350)

* fix(local): subchat mouse selection + hidden plan panel + scroll-extend selection

Three bugs in the subagent/swarm drill-in (subchat) view and mouse text selection,
all from the same root: newer features (subchat's row-source swap, wheel-scroll)
were never integrated into the older selection/footer code.

1) Can't copy anything in the subchat view. transcriptLineAtMouse (and
   selectedTranscriptText, the copy-time text extraction) always hit-tested against
   m.transcript (the parent), never m.subchat.childRows, even while the screen was
   showing the child session. New transcriptHitTestSource() mirrors transcriptView's
   own branching (nav bar + child rows + full width vs pinned title bar + parent
   rows + sidebar-aware width) and is now the single source both functions use.

2) Plan panel shown above the composer inside the subchat view. footerView
   unconditionally rendered the PARENT run's pinned plan panel; only pendingAskUser
   was gated. Added a !m.subchat.active guard (m.plan belongs to the parent run,
   not whatever subagent/swarm session is being viewed).

3) Selection didn't extend across a scroll (reported as "stopped at the end of the
   screen"). transcriptSelection.cursor was only ever updated by a mouseMotion
   event; a wheel event is a distinct message type that never reached that code,
   so scrolling while selecting left the selection frozen at whatever line the
   mouse last physically moved over. New scrollChatExtendingSelection scrolls AND
   re-evaluates the cursor at the mouse's current position against the post-scroll
   viewport. Uses a new nearestTranscriptLineAtMouse (falls back to the closest
   visible selectable line) rather than an exact match, since the recomputed
   position can land exactly on a blank spacer row between messages after an
   odd-length scroll shifts text/spacer parity - an exact-match miss there must
   not silently no-op the extension.

Tests: subchat selection resolves the CHILD session's text, not the parent's; the
plan panel is absent from the footer during subchat; a selection's cursor bodyY
moves (extends) after a wheel-scroll instead of staying pinned. Full gate green
(73 pkg, -race).

* feat(local): highlight clickable rows on mouse hover

Moving the cursor over an interactive row now highlights it (accent underline)
before you click, across every clickable surface:
- specialist cards and collapse/expand toggle headers in the transcript
- AGENTS sidebar rows (swarm members)
- PLAN sidebar step rows
- permission-prompt options (reuses the EXISTING keyboard-cursor highlight by
  moving pendingPermission.cursor on hover, instead of new styling)

Requires switching the mouse-tracking mode from CellMotion (only reports motion
while a button is held) to AllMotion (reports idle cursor movement too) - the
existing 15ms mouse-event throttle already covers the added motion events.

hover.go: hoverTarget + mouseHover predicate + updateHoverTarget, which reuses
the SAME hit-testers and priority order as the existing click handlers so hover
and click never disagree about what's clickable.

Sidebar hover is resolved by STABLE IDENTITY (sessionID / stepIndex), not a
cached line offset: hoveredSidebarLineOffset re-matches the identity against a
freshly computed hit list on every render, so a row that's disappeared (a
swarm member's linger elapsed, a plan step completed) simply doesn't highlight
rather than a coincidentally-matching unrelated row lighting up. Transcript
hover stays bodyY-keyed (matching the existing selection-highlight convention)
with explicit clearHover() calls wherever bodyY numbering can shift without an
intervening mouse motion: wheel-scroll, PgUp/PgDn, window resize, and
transcript rebuilds (/clear, /resume, /rewind, /compact via resetFlushFrontier).

Adversarial review caught two real bugs before ship, both fixed:
- BLOCKER: plan-step hover stored the step's own index (0,1,2...) but the
  sidebar render treated it as a raw line offset into the rendered rows -
  every plan-step hover highlighted the wrong row (the AGENTS header/body).
  Fixed by resolving fresh at render time via the stable-identity redesign
  above, which also closes the related sidebar-drift issue.
- MAJOR: hover wasn't cleared on keyboard PgUp/PgDn scroll.

Tests: predicate correctness; hover resolves the right target across all 4
surfaces (specialist card, toggle row, sidebar agent, plan step, permission
option) with the correct priority order; hover changes the actual render
output (transcript + sidebar); hover clears on wheel-scroll and subchat exit;
a regression test proving hoveredSidebarLineOffset self-heals (no highlight)
when a hovered row's identity no longer resolves - the exact scenario the
blocker fix targets. Full gate green (73 pkg, -race).

* fix(local): soften hover color + auto-scroll a drag past the transcript edge

1) Hover highlight was brand-lime (bright, glaring against the near-black
   surface) and re-paints on every mouse movement. Switched to amber (an
   existing semantic token, "light orange") and dropped the underline per
   feedback.

2) Dragging a text selection past the top/bottom edge of the visible
   transcript now auto-scrolls toward that side and extends the selection to
   follow, matching the browser/editor "drag past the viewport edge" pattern.
   transcriptEdgeScrollDelta detects the drag is vertically outside the body
   rect (but still within its horizontal span, so it isn't just "off to the
   side" over the sidebar); dragToEdgeScroll scrolls one step and anchors the
   cursor to whichever line now sits at that edge of the NEW viewport -
   deliberately not a re-resolve of the drag's physical mouse position, which
   stays outside the body rect after scrolling (scrolling changes what content
   occupies a screen row, not the mouse's screen position) and would keep
   finding nothing.

   Extracted nearestTranscriptSelectableAt as the shared "closest selectable
   line to a target bodyY" core, now used by both nearestTranscriptLineAtMouse
   (target derived from a mouse position that may have landed on a spacer row)
   and dragToEdgeScroll (target derived directly from the viewport bound, no
   mouse position involved at all).

Tests: dragging past the top edge scrolls toward older content and extends the
cursor upward; the symmetric bottom-edge case scrolls toward newer content and
extends downward. Full gate green (73 pkg, -race).

* fix(local): smooth-glide the drag-to-edge auto-scroll instead of jumping

The initial edge-scroll implementation (previous commit) applied a single
chatWheelScrollLines (5-line) jump per raw mouse-motion event, which reads as
sudden/jerky since motion events during a real drag arrive in bursts, and
stops dead the instant the physical mouse holds still even while still parked
past the edge (a terminal only reports motion on actual cursor movement).

Replaced with a self-scheduling tea.Tick chain (dragEdgeScrollTickMsg, gated by
edgeScrollSeq mirroring the existing exitConfirmSeq/copyStatusSeq idiom) that
steps a small, fixed increment (dragEdgeScrollStep=1 line) on a short cadence
(dragEdgeScrollInterval=70ms) for as long as the drag holds past the edge,
independent of whether new raw motion events keep arriving. reducedMotion still
gets the original single-bigger-step-per-event behavior (no animated glide).

Adversarial review of the new self-perpetuating tick chain (the risk being an
orphaned/stuck chain) found one real bug: a keypress mid-drag clears
m.transcriptSelection.active directly (the KeyPressMsg handler in model.go)
without going through stopEdgeScroll, leaving edgeScrollDelta stale. The
in-flight tick itself terminates safely via its own liveness check - the bug
was that the STALE nonzero edgeScrollDelta then fooled startEdgeScroll's
"already running" fast path on the NEXT same-direction drag into silently doing
nothing (no immediate step, no scheduled tick) for that whole hold. Fixed at
the press site (transcript_selection.go's mouseLeftPress case): every fresh
press now resets glide state via stopEdgeScroll, so a new drag always starts
clean regardless of how the previous one ended - a single targeted fix rather
than chasing every place transcriptSelection can be cleared.

Tests: top/bottom edge glide starts and extends the cursor over several ticks
(a single small step can land on a blank spacer row between messages, same as
real usage); the chain stops when the drag returns to the body and a stale
in-flight tick after that is a safe no-op; the keypress-interrupt regression
(reproduces the adversarial review's finding, confirms the fix). Full gate
green (73 pkg, -race).

* fix(local): soften the brand-lime accent color across the whole UI

The accent color (#caff3f) was fully saturated at fairly high lightness
(HSL: L 62%, S 100%) - the kind of value that reads as neon/glaring
everywhere it filled a block or bold-text surface, not just the one spot
originally flagged: the composer's "typed" prompt glyph, the permission
popup's focused-option badge, and the text-selection highlight all use it,
plus the spinner, the brand chip, tool-card prompts, and more.

Rather than patch each of those consumers individually, softened the single
palette source (dark theme only; the light theme's accent is a separate,
already-darkened value for its own contrast needs, untouched) to L 50% / S
80% (#ade619) - still clearly on-brand lime, and contrast against both black
(onAccent text on accent fills) and the near-black panel stays far above
WCAG AA (~14:1 and ~13:1, both comfortably over the 4.5:1 floor).

Updated TestStreamingFadePaletteMonotonic's pinned RGB assertion (it checked
the fade ramp's first bucket equals the literal old accent bytes) to the new
values. Full gate green (73 pkg, -race; make lint/go vet clean except an
unrelated stray file that isn't part of this branch or git history at all).

* fix(local): darken the brand-lime accent further per live feedback

Two prior passes (#ade619 at L50/S80, #8db620 at L42/S70) were each tested
live against the original #caff3f via raw truecolor escape codes and
confirmed too subtle in turn. Settled at L36/S62 (#759523) - a noticeably
darker, more olive lime, confirmed against the original side by side.
Contrast vs black (onAccent) and the near-black panel stays comfortably
above WCAG AA (~6.1:1 and ~5.6:1). Updated the streaming-fade test's pinned
RGB assertion to match.

* fix: address PR #350 review comments and CI smoke test failures

Smoke tests (macOS + Ubuntu): the 4 new edge-glide tests implicitly relied
on m.reducedMotion being false, but mouseTestModel() inherits it from
defaultReducedMotion(), which forces true whenever colorprofile.NoTTY is
detected - true in CI's non-TTY test runners, false in a local interactive
dev shell. Set reducedMotion = false explicitly in each of the 4 tests so
they're deterministic regardless of environment. Verified by re-running
locally under ZERO_REDUCED_MOTION=1 (reproduces the CI condition) - passes.

CodeRabbit actionable comment: handleTranscriptSelectionMouse's mouseMotion
case gated only on transcriptSelection.active, which stays true through the
async copy-command grace window after release (a non-empty selection isn't
reset until transcriptCopiedMsg lands) - so a genuine hover motion arriving
in that window would be misrouted as a drag update. The suggested fix
(gate on msg's own Button field) turned out to be wrong in a way only a
full test run caught: TestTranscriptSelectionUpdatesOnGenericMotion is a
pre-existing, deliberate test - some terminals don't restate the button on
every motion event during a real drag, so trusting the per-event Button
field breaks those terminals. Fixed properly instead: added a `dragging`
field to transcriptSelectionState, tracking the app's own press/release
bracket (true at press, false at release) independent of active and
independent of any single event's Button field. mouseMotion now gates on
dragging.

CodeRabbit nitpicks: routed the two remaining raw `m.hover = hoverTarget{}`
subchat-exit assignments through the existing clearHover() helper, so hover
invalidation stays in one place. Left the third nitpick (hit-test layout
recomputed per hover-motion tick) as a documented follow-up per the
reviewer's own "trivial/poor tradeoff" framing - a proper per-frame memoized
cache needs correct invalidation on scroll/resize/content-change to avoid
reintroducing the exact staleness class of bug already fixed twice in this
branch, and isn't worth rushing.

New tests: TestTranscriptHoverAfterReleaseDoesNotMoveSelection (the actual
bug CodeRabbit found - a post-release hover must not alter the just-copied
selection). Full gate green (73 pkg, -race); TestTranscriptSelectionUpdatesOnGenericMotion
(the test the first fix attempt broke) verified still passing.
fix: agent runtime resilience — stream stalls, weak-model tool args, and sub-agent reliability (#349)

* fix(local): defeat the macOS stale-pooled-connection hang (transport + stall-retry)

Root cause (you confirmed it: both chatgpt AND ollama hung, only on macOS): providers
fell back to http.DefaultClient, whose pooled keep-alive connections get reused on a
later turn after the server/NAT silently dropped them. The model call is a POST
(non-idempotent), so Go won't auto-retry it on a fresh conn — it blocks forever.
macOS keeps dead pooled conns around longer than Linux, so it reproduced on macOS only.

1. providerio.HTTPClient now returns a shared, tuned transport (ResponseHeaderTimeout
   60s bounds a hung POST that gets no response; IdleConnTimeout 30s stops dead conns
   from lingering to be reused). Routed openai/codex through it too (anthropic/gemini
   already used HTTPClient). Slow first tokens / long reasoning are unaffected — the
   header timeout only bounds time-to-first-response-header, not the stream body.
2. Agent loop now retries a stream idle/stall timeout that produced NO output yet, on
   a fresh connection (capped + backoff). A partial-output turn is NOT retried (would
   duplicate). Recovers any stall that slips past the transport timeout.

Local only — not pushed.

* fix(local): tolerate concatenated tool-arg JSON + widen response-header timeout

1) Weak models (minimax-m3, glm) pack MULTIPLE concatenated top-level JSON objects
   into one tool-call arguments slot ({A}{B}), which json.Unmarshal rejects with
   'invalid character {' after top-level value' (~9 failed tool calls/session).
   New recoverableToolArguments returns the first JSON value ONLY when the payload is
   one value optionally followed by more WHOLE JSON values; it rejects a bad/truncated
   first value OR trailing NON-JSON garbage ({"x":1}xyz) so genuine corruption still
   errors (adversarial-review fix). decodeToolArguments uses it at the central dispatch
   (executeToolCall) so {A}{B} runs the first object; historySafeToolCalls uses the
   SAME helper so the replayed transcript records the recovered first object (not {}),
   keeping dispatch and history consistent. Truly-malformed JSON still hits the
   existing sanitize-to-{} + retry path. Trailing objects are dropped (the model
   re-issues on a later turn).

2) Raise the shared transport ResponseHeaderTimeout 60s -> 120s so a slow cloud proxy
   (ollama *:cloud) that withholds its 200 header until first token isn't wrongly
   aborted; still bounds a truly dead reused connection.

Local only — not pushed.

* feat(local): add /turns command + raise default maxTurns 30->50

Agentic multi-step runs (build + delegate + swarm + MCP + self-verify) routinely hit
the 30-turn ceiling mid-task and never reached the later steps; removing /mode earlier
also left NO interactive way to raise the budget.

- /turns [n]: per-session tool-turn budget setter (commandGroupSession), mirroring
  /selfcorrect. Empty/status shows the current budget; a positive int sets
  agentOptions.MaxTurns (read by the run at model.go); clamped to maxTurnsCeiling=500
  to guard against typos; invalid/non-positive shows usage without changing it.
- defaultMaxTurns 30 -> 50 (matches the old 'deep' preset). Raise per-run with /turns
  for long tasks (e.g. /turns 150 for a full acceptance run).

Local only — not pushed.

* fix(local): swarm reports failed members as failed + sub-agents inherit /turns budget

Issue B — a swarm member whose child exited non-zero (e.g. exit 4 / max-turns) was
recorded [done] (swarm_status '0 failed'), so the orchestrator — which can't see the
AGENTS panel — trusted incomplete work. The specialist launcher ignored
res.Result.Status; it now surfaces a StatusError result as a member FAILURE
(errors.New(report)) so the swarm marks it [failed]. Added Coordinator.FailWithSession
and switched the member watch path to it so a failed member keeps its session id
(still drillable) and its report rides along as the failure message.

Issue A — a member hit its OWN turn limit because /turns raised only the parent's
budget; children re-resolved config.json's default. New config.SetMaxTurnsEnv exports
ZERO_MAX_TURNS, read in applyEnv -> cfg.MaxTurns; /turns now exports it so spawned
sub-agents / swarm members (which inherit the env) run with the same budget. A
non-numeric/zero env value never clobbers the configured budget.

Tests: launcher non-zero-exit -> failed (+ session kept); SetMaxTurnsEnv round-trip
+ garbage-env guard; /turns exports + clamps the env. Full gate green (73 pkg).

Local only — not pushed.

* fix(local): corrective error for unknown specialist name + clamp ZERO_MAX_TURNS

1) A model that invents a specialist name (validator-runner, file-creator,
   file-writer — none registered) got an opaque 'specialist not found' and kept
   spawning doomed sub-agents. loadManifest now lists the available specialists and
   notes that 'worker' has shell/edit while explorer/code-review are read-only, so the
   model self-corrects to a capable specialist. New availableSpecialistList helper.

2) Defense-in-depth (review nit): applyEnv now clamps an inherited ZERO_MAX_TURNS to
   MaxTurnsCeiling, so a raw shell 'export ZERO_MAX_TURNS=999999' can't bypass the
   /turns ceiling. Ceiling promoted to config.MaxTurnsCeiling (single source of truth,
   referenced by the TUI /turns clamp).

Tests: unknown-name error lists worker/explorer/code-review; applyEnv clamps an
over-ceiling env value. Full gate green (73 pkg).

Local only — not pushed.

* fix(local): surface sub-agent kill signal instead of opaque exit -1

When a sub-agent child is terminated by a signal, command.Wait returns an ExitError
whose ExitCode() is -1, losing the cause. Capture ProcessState.String() (portable,
e.g. "signal: killed") into ChildRunResult.Signal and have BuildFinalResult render
it — "Subagent terminated by a signal (signal: killed) — killed before it finished.
Likely causes: the OS out-of-memory killer ... a timeout, or cancellation." — instead
of an opaque "Subagent failed (exit -1)". The message lists causes rather than
asserting OOM, since timeout/cancellation also SIGKILL the child. A captured signal
always surfaces even if a late run_end reported a clean exit. The background task
path (which can't carry the signal name) emits the same hint for a negative exit code.

* address CodeRabbit review on #349

- loop.go: gate stall-retry on a turn-level forwardedAnything flag (wrapped
  callbacks), so a retry never re-streams on top of output already forwarded earlier
  in the turn (e.g. across the reactive-compaction retry). New test covers a
  reasoning-then-stall (collected.Text empty but output forwarded).
- loop.go: route a reissued stream's non-stall error through the SAME recovery as
  the initial stream (image-rejection wrapping / context-limit compaction) via a
  shared recoverStreamError closure, instead of returning it raw.
- exec.go: drop the hardcoded worker/explorer/code-review guidance from the
  unknown-specialist error; rely on the dynamically-rendered available list (a
  custom registry may not have those names).
- streamer.go: kill-signal message lists OOM/timeout/cancellation evenhandedly
  instead of asserting OOM (the branch also covers timeouts/cancellations).
- launcher_specialist.go + exec.go: preserve the child SessionID on a post-start
  failure too, so FailWithSession keeps those failed members drillable.
- model.go: block /turns while a run is active (mid-run change would make the
  inherited ZERO_MAX_TURNS budget inconsistent for later-spawned sub-agents).
fix(tui): sub-agents inherit the parent's live provider after a /model switch (#348)

* fix(tui): sub-agents inherit the parent's live provider after a /model switch

Swarm members and Task sub-agents run as child 'zero exec' processes that re-resolve
the provider from config.json themselves — they're passed --model but never the
parent's provider. After switching provider/model in the TUI via /model (an in-memory
change), the child still resolved config.json's stale activeProvider, landed on a
provider whose credentials didn't match the live model, and failed auth in ~3s
(exit 3, 0 tool calls, 'API key missing or invalid / can't reach the provider') — so
the spawned agent appeared then instantly disappeared.

Export ZERO_PROVIDER (config.SetActiveProviderEnv) to the live provider name on a
/model provider switch. Child processes inherit the environment, and config
resolution already maps ZERO_PROVIDER -> activeProvider, so the child resolves the
SAME profile and its credentials (env key / stored key / OAuth) — covering all three
auth methods, for both Task and swarm (both spawn via the specialist executor).

Startup needs no export: the parent and child both read config's default, so they
already match; only an in-memory switch diverges.

* fix(config): clear ZERO_PROVIDER when switching to an unnamed/default profile

SetActiveProviderEnv("") now unsets ZERO_PROVIDER instead of leaving the previous
value in the environment. Switching from a named provider back to an unnamed/default
profile otherwise kept exporting the stale provider into child zero exec processes,
which would resolve the old credentials. Extended the round-trip test with the
stale-env regression case: seed a value, switch to blank, assert both os.Getenv and
applyEnv no longer see it.

Addresses CodeRabbit review on #348.
fix(providerio): bound heartbeat-but-no-output streams so they can't hang forever (#347)

* fix(providerio): bound heartbeat-but-no-output streams (content-stall watchdog)

A stalled-but-alive upstream hung the agent indefinitely: SSE keep-alives reset the
idle watchdog (intentionally — a heartbeating upstream isn't 'dead', and aborting it
killed healthy long requests), so a stream that heartbeats while producing nothing
never tripped the idle timeout and there was no other ceiling. Observed on both
chatgpt/gpt-5.x (Codex) and ollama minimax-m3 — different provider code, same shared
providerio SSE loop — so the fix belongs here, once, for every provider.

Add a second 'content' watchdog alongside the idle one: keep-alives still reset idle
(no regression for heartbeating connections), but only REAL data lines reset the
content watchdog. If no data arrives for streamContentStallFactor (2) × the idle
timeout, abort with ErrStreamStalled instead of hanging. A slow-but-producing stream
(data between heartbeats) keeps resetting content and is never killed.

Contained to internal/providers/providerio — no provider/caller changes.

* fix(providerio): surface ErrStreamStalled in callers + widen flaky test margins

Address review:
- All four provider stream handlers (openai, codex, anthropic, gemini) now treat
  ErrStreamStalled in the same branch as ErrStreamIdle, via a new
  providerio.StreamTimeoutMessage helper that gives the stall a distinct, accurate
  message (it reports the content window and does NOT claim the upstream stopped
  sending data — keep-alives were still arriving). Previously a stalled stream fell
  through to the generic provider-error path.
- Widen the content-watchdog test timing margins (idle 100ms, data/keepalive every
  30ms) so CI/GC jitter can't trip the idle watchdog and mask the content path.
- Add a StreamTimeoutMessage unit test.
test(providers): isolate the OAuth store in the chatgpt Codex routing test (#346)

TestNewRoutesChatGPTCatalogToCodexProvider asserts the chatgpt-account-id header is
empty when no OAuth login is stored, but never redirected the token store — so on a
developer machine with a real chatgpt login it read that login and failed (it still
passed in CI, where no token exists). Point ZERO_OAUTH_TOKENS_PATH at an empty temp
path, mirroring TestNewRoutesChatGPTCatalogWithStoredAccountID, so the test is
deterministic regardless of the developer's stored credentials.
fix: stream Codex reasoning + drop swarm agents on their own completion (#345)

Two agent-visibility fixes surfaced diagnosing a 20-minute gpt-5.5 step and an
'agents never disappear' report.

A) Codex Responses path streamed no reasoning, so a long thinking phase produced
   zero visible output and read as a hang (the activity clock never advanced).
   Root cause: the request never asked for a reasoning summary and the parser had
   no case for reasoning deltas. Now request reasoning.summary="auto" and forward
   response.reasoning_summary_text.delta as StreamEventReasoning — the existing TUI
   handler renders it live and refreshes the activity clock.

B) A finished swarm member stayed in the AGENTS panel until the whole turn ended.
   Now it drops once ITS OWN task completes (fade over the linger window, then
   remove), independent of the overall run — matching how finished specialists
   already behave. Running members and mid-flight collect are unaffected.
fix(swarm): constrain agent_type to the registered roster via a dynamic enum (#344)

* fix(swarm): constrain spawn/handoff agent_type to the registered roster via enum

swarm_spawn and swarm_handoff described agent_type / to_agent_type as a free-form
string with only an 'e.g. teammate, subagent' hint, so a model could pass an
unregistered type (e.g. 'worker') and only discover it was invalid from the runtime
'unknown agent type' error — wasting tool calls, especially on weaker models.

Set the parameter's enum dynamically from the live roster (Registry.AgentTypes()),
so the schema advertises the valid set (built-ins plus any user-registered agents)
up front and an invalid type can't be sent. Falls back to a free-form string when
the roster is unavailable, so the tool never advertises an empty, un-satisfiable
enum. The runtime 'available agent types: …' error is kept as a backstop.

* test(swarm): also assert handoff to_agent_type enum picks up a custom roster type

Address review: the custom-type recheck only re-read spawnTool, so a regression
leaving handoffTool on the built-in list would have passed.
fix(openai): always send message content so strict OpenAI-compatible servers accept it (#343)

Some OpenAI-compatible endpoints (e.g. glm-* on Ollama-cloud) reject a request whose
message 'content' is absent or null with HTTP 400 'invalid message content type:
<nil>'. The chat-completions mapper relied on 'content,omitempty', so a message with
empty text (a tool result, an assistant turn that only makes tool calls, or a
sub-agent that failed with no output) serialized with no content field at all.

- Drop omitempty on chatMessage.Content and always set it (to "" when there is no
  text), so contentless messages serialize as "content":"" instead of being
  dropped. Standard OpenAI/xAI/groq already tolerated the omission; this makes the
  strict servers work too.
- Skip a degenerate assistant turn that has neither text nor tool calls, mirroring
  the Anthropic/Gemini mappers (which already drop empty turns).

Fixes the failure seen on glm-5.2:cloud after a sub-agent failed with empty output.
Document source-build sandbox helpers (#342)

Clarify that Linux source builds need the zero-linux-sandbox helper on PATH for native sandboxing, while macOS does not need an extra helper and Windows can self-dispatch from zero.exe.

Also document optional release-style helper builds for Linux and Windows.

Tested: git diff --check
fix(opengateway): correct gateway host, make it the recommended default (#341)

OpenGateway pointed at gateway.gitlawb.com, which does not resolve
(NXDOMAIN), so every request failed with "no such host". The live gateway
is opengateway.gitlawb.com — a flat OpenAI-compatible endpoint
(/v1/chat/completions, Authorization: Bearer ogw_live_…) that smart-routes
by model id across its upstreams (xiaomi-mimo, minimax, qwen, google,
nvidia, z-ai).

- catalog: fix base URL to https://opengateway.gitlawb.com/v1, default model
  to mimo-v2.5-pro; add a Recommended descriptor field and hoist OpenGateway
  to the top of the catalog so it is the first/badged pick everywhere.
- models: replace the curated model list with the gateway's real upstream
  models; fix the stale model-discovery fallback host.
- providers catalog: sort recommended-first (CLI + snapshot) and render the
  ★ … (recommended) badge; same badge in the TUI /provider wizard and the
  setup onboarding list.
- providerhealth: OpenGateway's flat /v1/models 404s by design, so probe its
  public /health endpoint for connectivity instead of reporting a false fail.
- tests: update catalog order golden + transport/discovery expectations; add
  coverage for the recommended provider and the health-endpoint override.

Co-authored-by: Kevin Codex <zero@gitlawb.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
chore(launch): MIT license, windows-arm64 install guard, TUI TTY guard (#340)

* chore(launch): MIT license field, windows-arm64 install guard, TUI TTY guard

Three launch-readiness fixes the docs cleanup doesn't cover:

- package.json: set "license": "MIT" (was the placeholder "SEE LICENSE IN
  LICENSE"), matching the LICENSE file and the README badge.
- scripts/postinstall.mjs: skip gracefully on windows-arm64. (win32, arm64)
  resolves to a valid platform/arch but the release matrix ships no
  windows-arm64 artifact, so the installer would download a 404 and hard-fail
  npm install. Treat it like any unsupported target (warnSkip, exit 0) and point
  to the x64 build (which runs under emulation on Windows on ARM) or source.
- internal/tui/run.go: fail fast when stdin is not a terminal. The interactive
  shell otherwise blocks forever in the Bubble Tea event loop on piped/redirected
  input (e.g. `echo "" | zero`); now it prints guidance toward `zero exec` and
  exits non-zero. Dependency-free ModeCharDevice check (no x/term added).

Tests: windows-arm64 skips with exit 0; the interactive shell returns non-zero
(not a hang) on non-TTY stdin.

* fix(tui): use term.IsTerminal for the stdin guard; pin exit code in test

Address review on the no-TTY guard:
- Replace the os.Stdin.Stat()/ModeCharDevice heuristic with term.IsTerminal
  (github.com/charmbracelet/x/term, already in the module graph via bubbletea).
  It is a true TTY check — it rejects pipes, regular files, and non-terminal
  char devices like /dev/null — and fails closed: anything not a verified
  terminal blocks the interactive shell.
- The test now asserts the documented exit code 2 from the guard, not just a
  non-zero result, so it proves the stdin guard fired.
Clean up public release docs (#339)

Rewrite the README around the initial public-release user flow, add the logo asset, and refresh install/update documentation.

Remove internal planning, audit, design, and work-split documents from the public docs tree.

Update stale documentation references and workspace seed expectations to point at public docs.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/workspaceseed

Tested: git diff --check
feat(reasoning): typed per-provider reasoning capability from a models.dev catalog (#338)

* feat(reasoning): typed per-provider reasoning capability from a models.dev catalog

Providers describe reasoning control with incompatible concepts — OpenAI a
discrete effort enum (split by minor version), Anthropic and Gemini 2.5 a
thinking-token budget, some models only a thinking on/off toggle — which a flat
effort string cannot represent and a model-name heuristic cannot detect.

Add internal/reasoning: a Capability type (a model's reasoning flag plus its
typed Controls — effort/budget_tokens/toggle) and a Catalog that looks capability
up by provider + api model id. The data is an embedded, trimmed snapshot of the
community capability database (first-party providers only; routers excluded since
they carry generic/stale option lists), so detection is offline and exact instead
of guessed.

The package depends only on the standard library, so the model registry and
provider adapters can consume it without an import cycle. This change is purely
additive — nothing is wired into the live resolution path yet.

Tests pin the per-version ground truth (gpt-5 minimal-not-none, gpt-5.1
none-not-minimal, gpt-5.1-codex-max xhigh, gpt-5-pro locked to high; Anthropic
budget-only legacy vs effort-only newer with the budget removed; Gemini 2.5
budget/toggle vs Gemini 3 effort) and that every reasoning model Zero ships today
is covered by the snapshot.

* fix(reasoning): address review — presence-aware budget bounds, deep-copy lookup, first-party-only snapshot

- Control.Min/Max are now *int so an explicit bound is distinct from an omitted
  one: Gemini's `min: 0` ("thinking can be disabled") and Anthropic's missing
  max (unbounded) are preserved instead of both collapsing to 0. Budget() becomes
  BudgetControl() returning the control so callers read the pointers.
- Catalog.Lookup returns a deep copy (clone) of the matched Capability, so a
  caller can no longer mutate the shared embedded catalog through the returned
  Controls / Values slices or budget pointers.
- Drop the google-vertex section from the snapshot: it re-hosts third-party MaaS
  models (Anthropic/Moonshot/OpenAI/DeepSeek/Qwen/Meta), violating first-party
  -only. google (AI Studio) already covers first-party Gemini, so the gemini
  provider kind resolves there. Snapshot 158 -> 123 models, 16.8 KB.

Tests pin the explicit min: 0 preservation, the nil max on budget-only Anthropic
models, and that a mutation of a Lookup result does not leak into the catalog.

* fix(reasoning): address round-2 review — accessor deep-copy, max tier, provenance

- EffortControl/BudgetControl now return a cloned Control, so a caller holding a
  Capability that shares state with the catalog cannot mutate Min/Max pointers or
  the Values slice through an accessor result (CodeRabbit). Lookup already deep
  -copies; this closes the accessor path too.
- Add modelregistry.ReasoningEffortMax ("max") + accept it in ValidReasoningEffort,
  so the snapshot's "max" tier (e.g. gpt-5.1-codex-max, newer Anthropic) has a
  constant to map to. No curated model lists it yet.
- Snapshot provenance: add a _fetched date and a regeneration recipe (documented
  in catalog.go), so refreshes are reproducible/auditable.
- Document that Lookup takes the API model id (wire name), not the friendly
  registry id, and that the match is exact (no case-fold/prefix-strip).
- Record the source-of-truth intent in the package doc: this catalog is the
  intended authoritative source; modelregistry's name-pattern inference is demoted
  to a fallback when it is wired in (a later change). Rename the `cap` builtin
  shadow to `entry`.

Tests pin the accessor deep-copy isolation.
feat(tui): remove the /mode command (superseded by /model + /effort) (#337)

The /mode presets bundled a hardcoded Anthropic/Google model + reasoning effort +
turn budget, so on other providers (Ollama-cloud, xAI, GPT-5, custom) /mode would
switch to a model the user isn't authenticated to. With /model (any provider's
models) and /effort (reasoning effort) covering the same ground flexibly, /mode is
redundant in the TUI.

Removes the /mode slash command, its handler, the mode picker, and the dispatch +
stale comments; updates affected tests. The CLI `--mode` flag and internal/
modelregistry mode presets are kept (still used by headless exec).
Polish TUI transcript rendering (#334)

* Polish transcript rendering

Tighten transcript spacing, collapse noisy permission/tool rows, and render tool activity with cleaner action-oriented labels.

Improve code and diff rendering with markdown highlighting, cleaner command output blocks, and grouped exploration summaries.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/tui

Tested: git diff --check

* Fix grep exploration rendering on Windows

Keep search query text out of path normalization so regex escapes render consistently across platforms.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/tui

Tested: git diff --check

* Address transcript rendering review

Cache highlighted streaming markdown so closed code blocks are not re-lexed on every live render.

Tighten bare-code detection to avoid highlighting ordinary prose, restore manual permission audit rows, and make exploration details expandable.

Also align diff content/header predicates and use display-width truncation for compact tool output.

Tested: env GOCACHE=/tmp/zero-go-cache go test ./internal/tui

Tested: env GOCACHE=/tmp/zero-go-cache go test -race ./internal/tui

Tested: env GOCACHE=/tmp/zero-go-cache go vet ./...

Tested: git diff --check
fix(openai): forward reasoning effort to the Codex Responses API (#336)

The Codex provider speaks the Responses API, where reasoning_effort is nested
under `reasoning.effort` rather than sent as a top-level field. buildResponsesRequest
never set it, so a user's chosen effort was silently dropped for every Codex
model — the request always ran at the model default.

Add a `reasoning` object to the Responses request and populate it from the
request's effort, reusing the chat path's openAIReasoningEffort normalizer so
only API-accepted values (minimal/low/medium/high) are sent and an empty or
unsupported effort omits the field (no empty object, no 400).
fix(modelregistry): one source of truth for a model's reasoning efforts (#335)

The /effort picker and the run-time effort resolver disagreed about which
tiers a model supports. Registry.ReasoningEfforts falls back to name-based
inference (reasoningEffortsForModelName) when the catalog lists no efforts,
so the picker shows controls for proxy-served GPT-5 / Codex / o-series
models. EffectiveReasoningEffort read model.ReasoningEfforts directly and
never saw that fallback, so it coerced the same request to "none" — the
picker advertised a tier the resolver silently dropped.

Route both through a single effectiveReasoningEfforts helper so they can
never diverge. A model the catalog enumerates with no efforts but whose
name is a known reasoning family now has its requested effort honored end
to end; non-reasoning models still resolve to "none".

Also drop the orphaned, stale NOTE above forwardedReasoningEffort claiming
effort "is not yet forwarded" (it is) and restore the reasoningEffortNotice
doc comment to its own function.
feat: context-aware compaction + usage gauge for all models (#332)

* fix(agent): enable auto-compaction for all models, not just registered ones

Auto-compaction keys off the model's context window (enabled = ContextWindow > 0),
resolved only from the curated registry. Unregistered models — GPT-5/Codex, xAI,
Ollama-cloud, custom endpoints — resolved to 0, so both the proactive (~80%) and the
reactive post-overflow compaction were silently disabled and long sessions overflowed.

- TUI modelContextWindow now also consults live-discovered windows (accurate for
  proxy/custom models once /model has discovered them); unknown still returns 0 so
  display gauges show no guessed denominator.
- New modelregistry.AgentContextWindow applies a positive FallbackContextWindow (200k)
  ONLY on the compaction-enable path (TUI run + CLI exec/spec), so compaction is on for
  every model while display stays accurate-or-empty. Exact windows always win.

* feat(tui): show context usage (used / total + % gauge) for all models from launch

The sidebar/status-line context gauge only shows a total + fill % when the active
model's context window is known. For proxy/custom models (GPT-5/Codex, xAI, Ollama-
cloud) the window isn't in the registry, so it showed only a used-token count.

Warm model discovery for the active provider in Init() (background, non-blocking) so
the active model's window is learned at launch and the gauge renders 'used / total
tokens' + the fill % for every model — not just catalogued ones. Builds on the
discovered-window resolution from the compaction fix.

* fix(tui): address review — agent fallback on model-switch + active-provider window

- Apply modelregistry.AgentContextWindow to /model and /mode pre-switch compaction
  requests (TargetContextWindow), so the 'compaction for all models' behavior also
  covers undiscovered/custom switch targets, not just the active run.
- Scope the live-discovered context-window lookup to the active provider first
  (then others), so a model ID shared across providers resolves to the provider in
  use rather than an arbitrary match.
- Tighten the resolution test to compare against the registry's actual gpt-4.1
  window instead of != FallbackContextWindow.

* fix(cli): give provider-discovered context windows precedence in headless exec

Address the remaining review point: CLI exec/spec runs collapsed every uncatalogued
model to the 200k fallback, ignoring its real window. resolveAgentContextWindow now,
on a registry miss, queries the provider's live model list (resolving the credential
from inline/stored/env) to get the model's actual context window before falling back.
Discovery runs only on a registry miss (catalogued models pay no latency), is bounded
by a 5s timeout, and degrades to the fallback on any error so a headless run is never
blocked or failed.
feat(tui): dim the transcript backdrop behind overlays for visibility (#333)

Slash-command/file palettes (and pickers/wizards) were composited directly over the
live transcript with no separation, so the chat bled through around the box and the
overlay was hard to read. Add a scrim: when an overlay is open, dim the transcript
backdrop (strip each line's colors and re-render faint) before compositing the bright
overlay on top. Header and composer render separately and stay bright. Text is
preserved (just dimmed), so context remains readable behind the palette.
feat(tui): compact one-line /model switch confirmation (#331)

The model-switch confirmation printed a 6-7 line block (Switched model. / model: /
provider: / api model: / effort: / saved:). Collapse it to a single summary line —
'<model> · <provider>[ · effort …][ · saved]' — keeping the deprecation/redirect
notice line when present. Tests updated to the new format.
fix(model): expose reasoning effort for GPT-5 / Codex / o-series (#330)

/effort showed no controls for ChatGPT (GPT-5) because those models aren't in the
curated registry and the OpenAI catalog entries carry no reasoning efforts, so
Registry.ReasoningEfforts returned nil even though GPT-5 supports reasoning_effort.

Add a name-based fallback: when a model isn't enumerated with efforts, infer them for
known reasoning families — GPT-5 / gpt-5.x Codex (minimal/low/medium/high) and the
o-series (low/medium/high). Non-reasoning models (GPT-4.1/4o, local models) stay empty,
so /effort still hides controls where they don't apply.
feat: encrypted provider credentials + provider-aware /model (#329)

Encrypted credential storage
- internal/securefile: AES-256-GCM at-rest crypter (fail-closed, atomic, locked).
- internal/credstore: provider API-key store, keyring-first with an encrypted-file
  fallback; plaintext only via an explicit ZERO_CRED_STORAGE=file opt-out.
- Provider API keys no longer live in config.json: captured straight into the store
  from the wizard/CLI setup, and any existing inline plaintext key is migrated to the
  store on launch (fail-soft; stripped only after the store write succeeds).
- buildProvider and every model/provider switch reload the credential (stored key,
  env var, or OAuth bearer), so a stored-key provider always authenticates.
- `zero auth logout <provider>` now also removes the stored API key and its marker.

/model and /provider
- /model lists every authenticated provider (filtered to those with a usable
  credential), grouped per provider under section headers.
- Each provider's models are live-discovered (its real served models) rather than a
  static catalog; local providers show only the models actually pulled.
- Selecting a model from another provider switches provider and model together.
- /provider offers keep / replace / remove when a provider already has a stored key.

Gated throughout: go build, go vet ./..., go test ./... -race, lint.
feat(tui): tabbed ask_user questionnaire in the composer with suggested answers (#327)

* feat(tui): tabbed ask_user questionnaire rendered in the composer

Redesign the interactive ask_user prompt to match the requested mockup: when a
question is raised the composer text box becomes the questionnaire.

- Multi-question prompts render as a row of TABS (one per question + a trailing
  Confirm tab). Tab / Shift+Tab switch questions, answers are given in any order,
  and Enter on Confirm submits them all. A single-question prompt submits on
  answer (no Confirm step) and shows no tab row.
- Each option can carry a one-line DESCRIPTION (contract: per-option
  optionDescriptions, or option objects {label, description}); options render
  numbered with the description dimmer underneath and the recommended one tagged.
- Per-question optional `header` gives each tab a short title (falls back to a
  trimmed question).
- Rendered in the composer/footer region (footerView), replacing the text box
  while active, instead of a scrolling transcript card.
- Keys: Tab move · ↑↓ select · Enter confirm · Esc dismiss; a printable key in
  the picker drops into free-text; Esc from "type your own" returns to the picker;
  multi-select questions are free-text with the options shown as suggestions.
- Headless unaffected (zero exec never wires OnAskUser).

Removed the old single-question sequential state (cursor/typing/index,
renderFocusedAskUserPrompt, resolveAskUser). Tests rewritten for the tabbed flow
(picker default, type-your-own, multi-question tabs + Confirm, Esc dismiss,
descriptions render). make build / go vet / go test ./... -race / make lint green.

* fix(tui): ask_user questionnaire renders on the black terminal canvas

It was painting a gray panel background (styledBlockFill with zeroTheme.panel +
onPanel-wrapped foregrounds). Since the questionnaire replaces the composer, it
should match it: bare foregrounds on the terminal canvas (black) with the
composer's lineStrong border and no fill. The lime cursor/badge highlights and
the recommended tag stay.

* fix(tui): address PR review — schema/parser alignment, single-question Tab

- ask_user schema: options.items is declared as string, so advertise only the
  string form (descriptions go via the parallel optionDescriptions array). The
  parser stays object-tolerant defensively, but the schema no longer tells
  strict-schema providers to send objects it would reject.
- moveAskUserTab no-ops for single-question prompts (no tab strip / Confirm tab),
  so Tab/Shift+Tab can't move the prompt into the hidden Confirm state. Test added.
fix(tui): paint transcript selection once, not twice (#328)

Selecting text in the transcript lit up in two places: the real selection
plus a copy shifted right by the reading-column gutter (e.g. selecting "help"
also highlighted "today").

Root cause: assistant, user, and reasoning rows self-painted the selection
highlight in their render functions using the UNSHIFTED textStart, but the
selection points (anchor.x/cursor.x) are in the gutter-shifted screen
coordinate the mouse maps to. So the self-paint landed gutter cells off, and
finalizeTranscriptBodyRow then painted the highlight AGAIN at the correct
shifted position — two highlights, one gutter apart. The rendered/toolResult/
specialist rows were already converted to paint-once-at-finalize; these three
were left behind.

Fix: stop self-painting in renderSelectableUserRow, renderSelectableAssistantRow,
and renderSelectableReasoningBlock. They now return the canonical renderRow
output (already line-aligned with their selectable spans) and let
finalizeTranscriptBodyRow be the single painter, in the same shifted coordinate
the mouse uses. Removes the now-dead renderTranscriptSelectableText /
renderTranscriptSelectableMarkdownText helpers.

Regression test TestTranscriptSelectionPaintsHighlightOnceNotTwice selects a
sub-range of an assistant row and asserts the selection style is emitted exactly
once; it fails on the pre-fix code (painted 3x, including the gutter-shifted copy).
feat(tui): ask_user suggested answers with a recommended default (#326)

* feat(tui): suggested answers with a recommended default for ask_user

When the agent asks a clarifying question mid-task, it can now offer 2-4
suggested answers and mark one recommended; the interactive TUI renders a
selector (arrow keys, lime cursor, "(recommended)" tag) with the cursor resting
on the recommended option, plus a trailing "✎ Type my own answer…" entry that
drops into the existing free-text composer. Whichever the user picks — a
suggested option's text or their typed answer — flows through the same answer
channel the agent loop already waits on.

Optional and backward-compatible: a question with no options renders the plain
free-text prompt exactly as before. Headless `zero exec` is unaffected (it never
wires OnAskUser; the non-interactive best-assumption fallback stands).

- contract: agent.AskUserQuestion / tools.AskUserQuestion gain Recommended;
  the tool schema advertises optional options + recommended; parser keeps
  recommended only when it resolves to one of the options (canonical text).
- system prompt: tells the model it MAY supply options + a recommended one.
- TUI: pendingAskUserPrompt gains cursor/typing; ask_user_prompt.go holds the
  selector logic mirroring permission_prompt.go; renderFocusedAskUserPrompt
  renders the picker or the free-text prompt.

Tests: selector defaults to recommended and returns its text; "type my own"
falls back to free-text and returns the typed text; no-options stays plain
free-text. make build / go vet / go test ./... -race / make lint green.

* fix(tui): ask_user — single input, Esc steps back from "type my own"

Two UX fixes from interactive testing:

- No double display: the focused ask card no longer echoes the in-progress
  free-text answer (it was shown both inside the card AND in the composer text
  box). The composer is now the single input; the card just shows the question
  and a hint. renderFocusedAskUserPrompt no longer takes the input string.

- Esc from "type my own" returns to the selector for that question instead of
  cancelling the whole questionnaire (escapeAskUser); a question with no options,
  or the selector itself, still cancels on Esc as before.

Tests: type-my-own asserts the card does not echo the typed text and the hint
flips to "type your own answer"; new test covers Esc returning to the selector
(no cancel, no answer delivered) then selecting a suggested option.

* fix(tui): ask_user review fixes — multi-select, selector typing, dead code

Address the three confirmed findings from the code review:

- multi-select no longer silently narrowed to one option: a single-pick
  selector cannot represent MultiSelect, so a multi-select question now renders
  as free-text with its options surfaced as suggestions; the user types one or
  more and the answer is returned verbatim (syncQuestionState; escapeAskUser and
  the renderer updated to match).

- typing in selector mode no longer discarded: a printable keystroke while the
  selector is showing flips into free-text and captures the key (model.go key
  capture), instead of…
@coderabbitai

coderabbitai Bot commented Jul 2, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

Adds a FILES sidebar section aggregating files touched by tool results and a git status sweep, a drill-in file view with diff/full rendering modes, hover and click wiring, render-cache/tint updates for selected files, and supporting transcriptRow.changedFiles data plumbing, with accompanying unit tests.

Changes

FILES sidebar and file drill-in feature

Layer / File(s) Summary
changedFiles data plumbing
internal/tui/transcript.go, internal/tui/session.go, internal/tui/model.go
Adds changedFiles []string to transcriptRow, populated live from tool results and rehydrated from session payloads via a new payloadStringSlice decoder.
Git sweep detection
internal/tui/files_git_sweep.go, internal/tui/files_git_sweep_test.go, internal/tui/model.go
Adds gitSweepCmd running git status --porcelain and git diff --numstat, parsing/baseline logic, gating via maybeGitSweep, and message handling in the model, with unit and real-repo tests.
Touched files aggregation and sidebar
internal/tui/files_panel.go, internal/tui/files_panel_test.go, internal/tui/sidebar.go, internal/tui/model.go
Builds a touchedFiles() roster from transcript rows and git sweep results, renders the FILES sidebar section with badges/diffstats/pulse row, computes clickable hit regions, and supports file selection/scroll-to-card.
Hover and selection tint
internal/tui/hover.go, internal/tui/sidebar.go, internal/tui/render_cache.go, internal/tui/rendering.go
Adds hoverFileRow hover kind, sidebar hover offset mapping, and border tinting plus render-cache key updates for rows touching the selected file.
File drill-in view
internal/tui/file_view.go, internal/tui/file_view_test.go, internal/tui/files_git_sweep_test.go
Implements fileViewState, open/exit/mode-switch lifecycle, nav bar, diff-mode edit-card rendering, full-mode on-disk rendering with gutter markers, and changed-line parsing.
Model wiring for file view
internal/tui/model.go, internal/tui/transcript_selection.go
Wires key handling (d/f toggle, Esc exit), pinned title bar swap, transcript body swap, and closes the file view before subchat/plan-step navigation.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • Gitlawb/zero#83: Both PRs modify the TUI's transcript-row/tool-result metadata and card rendering pipeline that the file-view/diff-mode relies on.
  • Gitlawb/zero#300: Both PRs modify the two-column context sidebar plumbing that the FILES-sidebar drill-in builds on.
  • Gitlawb/zero#350: Both PRs modify the TUI hover system, with this PR extending hover prioritization for FILES rows.

Suggested reviewers: Vasanthdev2004, gnanam1990

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is clearly related to the main change: adding a FILES sidebar panel.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
internal/tui/file_view_test.go (1)

99-134: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No coverage for the fileViewMaxLines truncation path.

TestFileViewFullBody covers a 2-line file; there's no test asserting that a file exceeding fileViewMaxLines actually gets truncated with the "… N more lines" trailer. Given the unbounded-read concern flagged in file_view.go, a regression test here would both document intent and catch it if the read path changes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tui/file_view_test.go` around lines 99 - 134, Add a regression test
around TestFileViewFullBody that exercises the truncation branch in
renderFileViewFull: create a file with more than fileViewMaxLines lines, open it
through openFileView and setFileViewMode(fileViewFull), then assert the rendered
output ends with the “... N more lines” trailer and only includes up to
fileViewMaxLines visible lines. Use the existing fileViewMaxLines and
renderFileViewFull symbols so the test documents and protects the truncation
behavior.
internal/tui/file_view.go (1)

209-224: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Trimmed-text matching will over-mark common lines.

fileViewChangedLines keys on trimmed line text across the whole file, so any short/common added line (}, return nil, blank-after-trim, etc.) will also mark every identical pre-existing line elsewhere in the file — for curly-brace-heavy code this could light up unrelated lines throughout the file, diluting the signal the gutter marker is meant to give. The doc comment already flags this as an accepted approximation, so this is a nice-to-have rather than a blocker — e.g. skipping trivial/very-short lines from the changed set would cut most of the noise cheaply.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tui/file_view.go` around lines 209 - 224, The current
fileViewChangedLines approximation is too broad because it keys on trimmed text,
so common short additions like braces or return nil can over-mark unrelated
lines in fileViewResultRows. Update fileViewChangedLines to avoid adding
trivial/very-short trimmed lines to the changed set, keeping the gutter markers
focused on meaningful additions while preserving the existing plus-line
filtering logic.
internal/tui/transcript_selection.go (1)

1271-1281: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding tests for the FILES click-routing logic.

This branch adds new click-state logic (select vs. open/switch based on fileView.active/selectedFile), and the sibling exitFileView()-before-navigation additions (Lines 1253, 1266) codify an important mutual-exclusion invariant. No test coverage for handleTranscriptSelectionMouse accompanies this layer's files. Given the branching complexity (first-click-select vs. click-while-open vs. click-on-selected), a few table-driven cases would guard against regressions here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tui/transcript_selection.go` around lines 1271 - 1281, The new FILES
click-routing branch in handleTranscriptSelectionMouse needs test coverage to
lock in the select-vs-open behavior. Add table-driven tests around
handleTranscriptSelectionMouse (and, if needed,
fileRowAtMouse/selectFile/openFileView) covering first click on an unselected
file, click on the already-selected file, and any click while fileView.active is
true. Also verify the mutual-exclusion behavior introduced by exitFileView()
before navigation by asserting the expected state transitions and returned
actions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/tui/files_git_sweep_test.go`:
- Line 173: Replace the literal nil Context passed to gitSweepCmd in the git
sweep tests with a real context instance to satisfy SA1012. Update each affected
call site in the test code to use a proper Context value, and add the context
import in the test file so the existing gitSweepCmd helper still receives a
valid context argument.
- Around line 37-45: The TestParseGitNumstat case is using a rename string that
does not match real `git diff --numstat` output, so it is not exercising the
actual rename parsing path. Update the test data in `TestParseGitNumstat` to use
a real numstat rename format (for example the `=>` style that `parseGitNumstat`
should handle, including brace-compressed renames if relevant) and keep the
existing assertions aligned with the `parseGitNumstat` behavior so the rename
case is properly covered.

In `@internal/tui/files_git_sweep.go`:
- Around line 121-142: `parseGitNumstat` is using the wrong rename format, so
renamed files from `git diff --numstat` keep a mismatched path and end up with
zeroed diffstat. Update `parseGitNumstat` to recognize numstat rename paths that
use ` => ` (including brace-compressed forms) instead of relying only on
`cutRename`, and normalize the resulting path before storing it in `stats`. Also
adjust the related test coverage so it uses the real numstat rename shape,
ensuring the lookup in `gitSweepCmd` matches the porcelain-derived file path.

---

Nitpick comments:
In `@internal/tui/file_view_test.go`:
- Around line 99-134: Add a regression test around TestFileViewFullBody that
exercises the truncation branch in renderFileViewFull: create a file with more
than fileViewMaxLines lines, open it through openFileView and
setFileViewMode(fileViewFull), then assert the rendered output ends with the
“... N more lines” trailer and only includes up to fileViewMaxLines visible
lines. Use the existing fileViewMaxLines and renderFileViewFull symbols so the
test documents and protects the truncation behavior.

In `@internal/tui/file_view.go`:
- Around line 209-224: The current fileViewChangedLines approximation is too
broad because it keys on trimmed text, so common short additions like braces or
return nil can over-mark unrelated lines in fileViewResultRows. Update
fileViewChangedLines to avoid adding trivial/very-short trimmed lines to the
changed set, keeping the gutter markers focused on meaningful additions while
preserving the existing plus-line filtering logic.

In `@internal/tui/transcript_selection.go`:
- Around line 1271-1281: The new FILES click-routing branch in
handleTranscriptSelectionMouse needs test coverage to lock in the select-vs-open
behavior. Add table-driven tests around handleTranscriptSelectionMouse (and, if
needed, fileRowAtMouse/selectFile/openFileView) covering first click on an
unselected file, click on the already-selected file, and any click while
fileView.active is true. Also verify the mutual-exclusion behavior introduced by
exitFileView() before navigation by asserting the expected state transitions and
returned actions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b8ecc461-5025-435d-bf4d-f28dc54fd3b8

📥 Commits

Reviewing files that changed from the base of the PR and between 02f0c09 and 1fdbcc0.

📒 Files selected for processing (14)
  • internal/tui/file_view.go
  • internal/tui/file_view_test.go
  • internal/tui/files_git_sweep.go
  • internal/tui/files_git_sweep_test.go
  • internal/tui/files_panel.go
  • internal/tui/files_panel_test.go
  • internal/tui/hover.go
  • internal/tui/model.go
  • internal/tui/render_cache.go
  • internal/tui/rendering.go
  • internal/tui/session.go
  • internal/tui/sidebar.go
  • internal/tui/transcript.go
  • internal/tui/transcript_selection.go

Comment on lines +37 to +45
func TestParseGitNumstat(t *testing.T) {
stats := parseGitNumstat("12\t3\tweb/app.js\n-\t-\tassets/logo.png\n4\t0\told.go => pkg/new.go\n1\t1\tR\told.go -> pkg/new.go\n")
if got := stats["web/app.js"]; got != [2]int{12, 3} {
t.Errorf("web/app.js = %v, want [12 3]", got)
}
if _, ok := stats["assets/logo.png"]; ok {
t.Error("binary '-' entries must be skipped")
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Rename test doesn't exercise real numstat format.

Complements the parseGitNumstat finding in files_git_sweep.go: this line uses " -> " (porcelain's delimiter) inside a numstat-shaped string, which isn't how git diff --numstat actually renders renames (" => ", optionally brace-compressed). Worth replacing with a case that matches real numstat output once the parser is fixed, so the rename path is actually covered.

-	stats := parseGitNumstat("12\t3\tweb/app.js\n-\t-\tassets/logo.png\n4\t0\told.go => pkg/new.go\n1\t1\tR\told.go -> pkg/new.go\n")
+	stats := parseGitNumstat("12\t3\tweb/app.js\n-\t-\tassets/logo.png\n4\t0\told.go => pkg/new.go\n2\t1\tsrc/{old.js => new.js}\n")
+	if got := stats["pkg/new.go"]; got != [2]int{4, 0} {
+		t.Errorf("renamed file = %v, want [4 0]", got)
+	}
+	if got := stats["src/new.js"]; got != [2]int{2, 1} {
+		t.Errorf("brace-compressed rename = %v, want [2 1]", got)
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestParseGitNumstat(t *testing.T) {
stats := parseGitNumstat("12\t3\tweb/app.js\n-\t-\tassets/logo.png\n4\t0\told.go => pkg/new.go\n1\t1\tR\told.go -> pkg/new.go\n")
if got := stats["web/app.js"]; got != [2]int{12, 3} {
t.Errorf("web/app.js = %v, want [12 3]", got)
}
if _, ok := stats["assets/logo.png"]; ok {
t.Error("binary '-' entries must be skipped")
}
}
func TestParseGitNumstat(t *testing.T) {
stats := parseGitNumstat("12\t3\tweb/app.js\n-\t-\tassets/logo.png\n4\t0\told.go => pkg/new.go\n2\t1\tsrc/{old.js => new.js}\n")
if got := stats["web/app.js"]; got != [2]int{12, 3} {
t.Errorf("web/app.js = %v, want [12 3]", got)
}
if _, ok := stats["assets/logo.png"]; ok {
t.Error("binary '-' entries must be skipped")
}
if got := stats["pkg/new.go"]; got != [2]int{4, 0} {
t.Errorf("renamed file = %v, want [4 [0]]", got)
}
if got := stats["src/new.js"]; got != [2]int{2, 1} {
t.Errorf("brace-compressed rename = %v, want [2 1]", got)
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tui/files_git_sweep_test.go` around lines 37 - 45, The
TestParseGitNumstat case is using a rename string that does not match real `git
diff --numstat` output, so it is not exercising the actual rename parsing path.
Update the test data in `TestParseGitNumstat` to use a real numstat rename
format (for example the `=>` style that `parseGitNumstat` should handle,
including brace-compressed renames if relevant) and keep the existing assertions
aligned with the `parseGitNumstat` behavior so the rename case is properly
covered.

run("commit", "-q", "-m", "seed")
write("pre-existing.txt", "dirt\n") // dirty BEFORE the TUI "opens"

baseline := gitSweepCmd(nil, dir, true)().(gitSweepMsg)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Pass a real context instead of nil (SA1012).

Static analysis flags gitSweepCmd(nil, ...) at these three call sites. gitSweepCmd itself tolerates it (substitutes context.Background()), but staticcheck's own guidance is to never pass a literal nil Context.

🔧 Proposed fix
-	baseline := gitSweepCmd(nil, dir, true)().(gitSweepMsg)
+	baseline := gitSweepCmd(context.Background(), dir, true)().(gitSweepMsg)
...
-	sweep := gitSweepCmd(nil, dir, false)().(gitSweepMsg)
+	sweep := gitSweepCmd(context.Background(), dir, false)().(gitSweepMsg)
...
-	if msg := gitSweepCmd(nil, t.TempDir(), false)().(gitSweepMsg); msg.ok {
+	if msg := gitSweepCmd(context.Background(), t.TempDir(), false)().(gitSweepMsg); msg.ok {

(needs "context" added to the import block)

Also applies to: 182-182, 198-198

🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 173-173: SA1012: do not pass a nil Context, even if a function permits it; pass context.TODO if you are unsure about which Context to use

(staticcheck)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tui/files_git_sweep_test.go` at line 173, Replace the literal nil
Context passed to gitSweepCmd in the git sweep tests with a real context
instance to satisfy SA1012. Update each affected call site in the test code to
use a proper Context value, and add the context import in the test file so the
existing gitSweepCmd helper still receives a valid context argument.

Source: Linters/SAST tools

Comment on lines +121 to +142
// parseGitNumstat parses `git diff --numstat` output ("added\tdeleted\tpath")
// into path → [added, deleted]. Binary files report "-" and are skipped.
func parseGitNumstat(out string) map[string][2]int {
stats := map[string][2]int{}
for _, line := range strings.Split(out, "\n") {
parts := strings.SplitN(line, "\t", 3)
if len(parts) != 3 {
continue
}
adds, errA := strconv.Atoi(parts[0])
dels, errD := strconv.Atoi(parts[1])
if errA != nil || errD != nil {
continue
}
path := parts[2]
if to, _, found := cutRename(path); found {
path = to
}
stats[unquoteGitPath(path)] = [2]int{adds, dels}
}
return stats
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

parseGitNumstat never resolves real rename lines — diffstat for renamed files silently stays 0/0.

git diff --numstat renders renames with " => " (optionally brace-compressed, e.g. src/{old.js => new.js}), not the " -> " that git status --porcelain uses. cutRename here only recognizes " -> ", so a real numstat rename line like "12\t3\told.go => pkg/new.go" never matches: path stays the whole raw string, and stats["old.go => pkg/new.go"] never lines up with the porcelain-derived files[i].path ("pkg/new.go") used for the lookup in gitSweepCmd. The result is a silently wrong (zeroed) diffstat for any renamed-and-modified file the sweep discovers — not a crash, but it undermines the diffstat this section exists to show.

Worth noting the accompanying test doesn't catch this: it fabricates "1\t1\tR\told.go -> pkg/new.go" (using " -> ", which isn't how numstat actually formats renames) to force cutRename to fire, rather than testing the real " => " shape.

🔧 Proposed fix: recognize numstat's own rename delimiter
+// cutNumstatRename resolves `git diff --numstat`'s rename shape, either the
+// full "old => new" form or the brace-compressed "dir/{old => new}/tail" form.
+func cutNumstatRename(path string) string {
+	if start := strings.Index(path, "{"); start >= 0 {
+		if end := strings.Index(path[start:], "}"); end >= 0 {
+			end += start
+			if arrow := strings.Index(path[start:end], " => "); arrow >= 0 {
+				arrow += start
+				return path[:start] + path[arrow+4:end] + path[end+1:]
+			}
+		}
+	}
+	if idx := strings.Index(path, " => "); idx >= 0 {
+		return path[idx+4:]
+	}
+	return path
+}
+
 func parseGitNumstat(out string) map[string][2]int {
 	stats := map[string][2]int{}
 	for _, line := range strings.Split(out, "\n") {
 		parts := strings.SplitN(line, "\t", 3)
 		if len(parts) != 3 {
 			continue
 		}
 		adds, errA := strconv.Atoi(parts[0])
 		dels, errD := strconv.Atoi(parts[1])
 		if errA != nil || errD != nil {
 			continue
 		}
-		path := parts[2]
-		if to, _, found := cutRename(path); found {
-			path = to
-		}
-		stats[unquoteGitPath(path)] = [2]int{adds, dels}
+		path := cutNumstatRename(parts[2])
+		stats[unquoteGitPath(path)] = [2]int{adds, dels}
 	}
 	return stats
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// parseGitNumstat parses `git diff --numstat` output ("added\tdeleted\tpath")
// into path → [added, deleted]. Binary files report "-" and are skipped.
func parseGitNumstat(out string) map[string][2]int {
stats := map[string][2]int{}
for _, line := range strings.Split(out, "\n") {
parts := strings.SplitN(line, "\t", 3)
if len(parts) != 3 {
continue
}
adds, errA := strconv.Atoi(parts[0])
dels, errD := strconv.Atoi(parts[1])
if errA != nil || errD != nil {
continue
}
path := parts[2]
if to, _, found := cutRename(path); found {
path = to
}
stats[unquoteGitPath(path)] = [2]int{adds, dels}
}
return stats
}
// cutNumstatRename resolves `git diff --numstat`'s rename shape, either the
// full "old => new" form or the brace-compressed "dir/{old => new}/tail" form.
func cutNumstatRename(path string) string {
if start := strings.Index(path, "{"); start >= 0 {
if end := strings.Index(path[start:], "}"); end >= 0 {
end += start
if arrow := strings.Index(path[start:end], " => "); arrow >= 0 {
arrow += start
return path[:start] + path[arrow+4:end] + path[end+1:]
}
}
}
if idx := strings.Index(path, " => "); idx >= 0 {
return path[idx+4:]
}
return path
}
// parseGitNumstat parses `git diff --numstat` output ("added\tdeleted\tpath")
// into path → [added, deleted]. Binary files report "-" and are skipped.
func parseGitNumstat(out string) map[string][2]int {
stats := map[string][2]int{}
for _, line := range strings.Split(out, "\n") {
parts := strings.SplitN(line, "\t", 3)
if len(parts) != 3 {
continue
}
adds, errA := strconv.Atoi(parts[0])
dels, errD := strconv.Atoi(parts[1])
if errA != nil || errD != nil {
continue
}
path := cutNumstatRename(parts[2])
stats[unquoteGitPath(path)] = [2]int{adds, dels}
}
return stats
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/tui/files_git_sweep.go` around lines 121 - 142, `parseGitNumstat` is
using the wrong rename format, so renamed files from `git diff --numstat` keep a
mismatched path and end up with zeroed diffstat. Update `parseGitNumstat` to
recognize numstat rename paths that use ` => ` (including brace-compressed
forms) instead of relying only on `cutRename`, and normalize the resulting path
before storing it in `stats`. Also adjust the related test coverage so it uses
the real numstat rename shape, ensuring the lookup in `gitSweepCmd` matches the
porcelain-derived file path.

@kevincodex1 kevincodex1 closed this Jul 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant