mapWeeklyCredits treated an absent creditUsagePercent as a confirmed protobuf
zero whenever the weekly period matched billing bounds, so unified-billing
accounts whose credits view never reports the percent showed a confident 0%
and short-circuited the monthly fallback (#15740). Those payloads emit
onDemandUsed/prepaidBalance zeros, which disproves the "encoder drops zeros"
premise.
Resolution order is now: reported percent → monthly used/monthlyLimit pair as
a monthly window → synthetic 0 only when the payload emits no usage scalars at
all and the weekly period is confirmed → unavailable with an explicit reason
the Accounts pane surfaces.
Rebased onto current main from nwparker/grok-usage-percent-fallback (#15878).
Fixes#15740
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
* feat(minimax): endpoint selector, API key auth, weekly usage window (#14264)
The MiniMax (MiniMax) Coding Plan usage fetch was hardcoded to the
overseas platform (platform.minimax.io) and a single 5h session
window, so users on the CN endpoint (www.minimaxi.com) got nothing.
Three changes:
- Add `minimaxEndpoint` (`overseas`|`cn`) and
`minimaxApiKeyConfigured` settings fields with sensible defaults
that preserve current behavior. The CN endpoint also accepts an
API key (safeStorage-encrypted via a new
`minimax-api-key-store.ts` + IPC pair) for users without a
browser session cookie. Status-bar visibility now OR's both
credential flags.
- Cookie-jar origin now tracks the active endpoint. Previously
cookies were stored under the overseas origin and silently
dropped when the user picked CN — fixed by threading
`endpointMode` through the request context, the manual cookie
header path, and the cookie-jar clear.
- Parse the weekly window in addition to the 5h session and
surface both as per-window chips (`5h [bar] 10% wk [bar] 20%`).
The status bar's compact section prefers the session window; the
popover keeps the existing `Session` / `Weekly` labels. The
MiniMax fetcher is split into three files (data / parse / main)
to stay under the 300-line cap.
i18n is scoped to the Settings-page text (en + zh only); the 5H/7D
duration shorthands stay English across locales by project convention.
Tests: 9 new/updated files; cookies + API key exercised end-to-end
via the rate-limit service with the upstream-refactored test files
(`service-minimax-usage.test.ts`,
`web-preload-api-settings.test.ts`,
`web-preload-api-agent-providers.test.ts`,
`service-test-harness.ts`, and the runtime-home / reset-credit
fixtures).
Refs #14264
* Keep merge formatting scoped to MiniMax
* Keep MiniMax credential status in rate-limit test fixtures
* Use the China console origin for MiniMax request referer
---------
Co-authored-by: Neil <4138956+nwparker@users.noreply.github.com>
* test: wait for rendered tabs and handle busy close confirmation
* test: wait for create-menu item click actionability
* test: settle initial terminal focus before create-menu actions
* test: capture menu focus events for Linux CI diagnosis
* test: remove menu diagnostics after identifying deferred layout focus
* test: check Markdown menu dismissal after editor readiness
* fix: fence browser recovery to attach inventory placements
* refactor: name the attach-inventory fence and make its test deterministic
Extract the placement check into isPlacedAsObservedAtAttach so the recovery
filter stays a flat list of named predicates, and document that omitting
pagePlacementsAtAttach recovers against unfenced live state.
Replace the 30-microtask drain in the post-attach regression with the handler's
own completion: attach only settles after recovery returns, so awaiting the
dispatch orders the assertions instead of guessing at a microtask count.
Verified by forcing the fence open: both regressions fail (the post-attach one
in 60ms on a retired placement) and the other 27 still pass.
* test: settle the attach handler even when the regression fails early
The barrier ran inline, so a waitFor timeout or the placement guard left the
attach handler parked on a promise nothing awaited. Hoist it into settleAttach
and call it from a finally as well; cleanup is guarded and the dispatch promise
is already settled, so the second call is a no-op.
* fix: release floating terminal WebGL contexts while closed
* test: pin retention polarity through a real PaneManager
Replace the prototype-surgery fake with a constructed PaneManager so the
suspend path exercises real constructor state, and add the retain-branch
case so an inverted default cannot pass silently.
De-shadow `window` in the system-resume e2e main-process callback.
* perf(worktrees): stop worktree teardown replacing arrays and maps it never touched
Removing a worktree fires three store writes through
removed-worktree-renderer-teardown.ts, and each handed back a fresh reference
even when it removed nothing:
- remove-worktree-store-cleanup filtered openFiles unconditionally. #19058 gave
the ~50 record maps in this file identity preservation and missed the one plain
array; the sibling purge path already had the guard this copies.
openFiles is selected whole by the editor panel, file explorer and git-status
polling.
- shutdownWorktreeBrowsers spread-then-deleted browserTabsByWorktree and
activeBrowserTabIdByWorktree; both now go through omitRecordKeys.
- markShutdownPending rebuilt suppressedPtyExitIds and pendingPtyShutdownIds even
with no guard ids at all, which is the normal case when the panes already
exited. It now returns early, and skips the suppressed map when every id is
already true.
Same contents, same keys removed; only the reference is reused when nothing
changed.
* fix(test): use AppState['openFiles'][number] instead of a nonexistent module
The test imported OpenFile from shared/editor-types, which does not exist. Vitest
passed because a type-only import is erased at runtime; CI typecheck caught it.
I had run tsc before adding this file and never re-ran it.
* refactor(terminals): reuse copyOnWriteRecord in markShutdownPending and pin its identity contract
boundRecentlyRetiredAgentStatusPaneKeys always rebuilt the record, replacing
its reference even when nothing changed; a probe counted 1,099 such writes
across the store suite. Return the existing record when no key would be
evicted and the additions are already its tail in the same relative order.
Key-set equality is deliberately NOT enough: re-adding a key must move it to
the tail because that LRU order decides which key the cap evicts next.
Share the LRU bound with boundRecentlyClosedAgentStatusTabIds, which had the
same always-rebuild shape.
* fix: recognize working WSL1 without a WSL2 kernel
* fix: recognize unsigned Windows missing-kernel status
* fix(wsl): fold the missing-kernel guest probe into wsl-availability
The separate wsl-missing-kernel-probe module failed three CI gates: it was
not in the web typecheck project (TS6307), it added a new direct wsl.exe
spawn outside wsl-runner, and its `catch { return false }` tripped the
probe-failure-semantics ratchet.
wsl-availability.ts already owns the answer and is already on the invocation
allowlist, so the probe lives there now. A guest probe that cannot spawn
keeps the real --status failure instead of minting a fresh negative, which
is what the ratchet exists to prevent -- and is the more correct semantics.
* fix: avoid credit deadlock during large SSH PTY recovery
* test: restore bounded SSH flood recovery coverage
* test(relay): pin the recovery fence to the accepted checkpoint
The oversized-tail cases asserted that the drain completes, but not that
recoveryEndSu lands on the checkpoint, so passing the pre-rotation snapshot
(which carries the old client's window and a stale creditedEndSu) fenced
below the checkpoint and still passed. Assert the fence value, narrow
boundedPtyRecoveryEnd to the three fields it reads, and cover the exact
one-window boundary that separates a live drain from an ordinary fence.
* fix: preserve session publication during runtime terminal fallback
* refactor(runtime): align fallback epoch comment and test preamble
Match the file's `// Why:` comment convention on the inherited
publication epoch, and drop a redundant duplicate mocks import in the
lineage regression test while keeping the required side-effect order.
No behavior change.
* fix: settle remote terminal insertion in the calling client
* refactor: share one anchor insertion path for local and remote terminals
Extract the created-tab-after-anchor reorder that the local terminal IPC
bridge already carried into insertUnifiedTabAfterAnchor, and settle the
remote placement through it instead of a second copy.
Also repairs two anchor-resolution gaps in the settlement:
- keep an exact unified tab id (legacy leaf-keyed anchors, browser and
editor tabs) instead of collapsing every anchor to a terminal parent,
which could mint a `web-terminal-<browser tab>` id that matches nothing
- fall back to the anchor's own group when the requested group was closed
while the mirrored tab was still in flight
* fix: preserve renderer browser publication during client-hosted page updates
* refactor: drop the now-dead publicationEpoch selection argument
applyBrowserSessionTabSelection took a publicationEpoch and wrote it over
the epoch the spread snapshot already carried. Its only production caller
now passes snapshot.publicationEpoch, so the parameter is a no-op whose
only remaining power is to reintroduce the epoch rotation this PR fixes.
Remove it, and collapse the repeated prototype-cast boilerplate in the new
reconciliation test into one helper.
No behavior change.
* fix: keep reconcile from publishing a browser row twice
The retention filter partitioned existing rows by placement kind, so its
disjointness from the live build relied on a non-local invariant: that the
page registry only ever stores client placements and that server tabs are
empty while no offscreen backend exists. Drop ids the live build already
published instead, so a duplicate row is impossible by construction rather
than by coincidence.
* fix: stop the browser reconcile republishing on a pure reordering
headlessBrowserTabsUnchanged compares by array index, so rebuilding the live
list renderer-first read an interleaved snapshot as changed and republished
with a bumped version and rebuilt tab groups for no semantic change - the
same churn this branch exists to remove.
Key the live set by id and emit it in the order the snapshot already had.
Keying also makes uniqueness unconditional rather than resting on the page
registry only ever storing client placements.
* fix: preserve paired host sessions during startup residue cleanup
* refactor(persistence): tighten the paired-host retention pass
Dedupe the owner-key -> repo-id extraction the retention and seeding
passes both needed, and name the `runtime:*` check instead of repeating
the parse three times.
Reach the session walker directly by exporting
`addWorkspaceSessionWorktreeOwners` rather than fabricating a
`{ workspaceSession }` state slice to get at it.
Correct the docstrings: `runtime:*` also covers a serving host's own
partition, and the "authoritative removal" they promised has no product
caller on a paired client today, so say what the exemption actually
costs.
Add a survived-load assertion to the explicit-removal test, which
otherwise passed against the pre-fix sweep -- the partition was already
empty before the removal ran.
No behavior change beyond the docs and the test assertion.
* fix: preserve terminal command probes across control frames
* refactor(terminal): make the command-probe output flag explicit
Hoist the duplicated Output/OutputSpan predicate in the binary frame
handler, and require carriesOutput on recordInbound so no future call
site can silently disarm the command-response probe by omitting it.
Rework the control-frame regression into a named table so the
fit-override and driver-changed cases send valid event payloads instead
of stubs that returned before dispatch.
* fix: preserve overlays during terminal mounting and layout
* fix(terminal): stop a dismissed overlay from blocking pane focus
Overlay primitives animate out (data-[state=closed]:animate-out, up to
300ms on sheets), so a dismissed dialog stays mounted and painted well
past the point it should stop owning focus. The rAF-deferred focus in
activateTabAndFocusPane lands inside that window, so revealing an agent
from the dashboard drawer or a menu left the terminal unfocused.
Treat data-state="closed" as gone, matching the [data-state="open"]
convention already used by AgentDashboardDrawer and useWorkspaceBoardPanel.
Also revert unrelated comment churn on scheduleRevealRepaint and note the
new focus consumer in the hasVisibleOverlay doc comment.
* refactor(terminal): scope the dismissed-overlay rule to pane focus
Gate the data-state="closed" exclusion behind an ignoreDismissed option
that only focusPanePreservingOverlays passes, leaving Escape semantics
for the four existing hasVisibleOverlay callers unchanged.
The focus race this fixes is specific to deferred focus (activateTabAndFocusPane
defers by one rAF, landing inside the overlay's exit animation). Escape is
synchronous and does not need the rule: Radix's useEscapeKeydown is capture
phase, so every Escape caller runs while data-state is still "open".
Avoids any behavior change on the Settings Escape path, which unlike the
other three callers is bubble phase on document with no ordering guarantee.
* fix: avoid starting browser helpers just to reset absent sessions
* refactor(browser): tighten the session-reset skip guard and its tests
Drop the platform and absolute-path guards: ownsSocketDirectory is already
false on Windows and for inherited directories, and an Orca-derived directory
is always absolute. Fold the empty-name and traversal checks into agent-browser's
own session-name rule.
Stop lstat state leaking between lifecycle tests, and pin the probed socket path
so the skip test cannot pass on an unwired mock.
* fix: open editor rename after context menu releases focus
* refactor(editor): tighten rename focus-handoff comments and test setup
Correct the rename-input focus comment that still credited the animation
frame with outrunning menu teardown, clarify why the rename now runs from
onCloseAutoFocus, and fold the repeated menu-close invocation in the tab
tests into one helper.
* fix: keep macOS shell ownership proof within recovery budget
* fix: parse the shell-proof column set with its own anchored parser
The narrower macOS capture (`pid ppid pgid tpgid stat command`) was fed to the
shared lenient parser, whose optional tty/start pair has no `tty=` column left
to absorb it. It then eats the head of any argv shaped `python 3 app.py`
(parsing command as `app.py`, tty as `/usr/bin/python`), and turns a
command-less row into a garbage pid/stat pair. Either can flip a shell
ownership verdict, which is what gates dead-TUI recovery.
Give the column set a named constant and a parser anchored to exactly those
six columns, beside its `CHEAP_PS_ARGS` sibling. A capture that yields no rows
now raises `empty_capture` rather than reading as a machine with no processes.
Update the `confirmShellForegroundProcess` fixtures from the 4-column legacy
shape to the 6 columns the darwin reader actually emits; that describe block
already forces `platform=darwin`, so the stale fixtures were failing.
* fix(cmd-j): pass browser tab ownership into palette search
* test(cmd-j): cover restored browser recency in the ownership regression
The same unifiedTabsByWorktree map that establishes host ownership also
feeds lastActiveAt, which orders Open Tabs and renders the row's session
age. That half of the fix had no coverage, so assert it alongside the
execution host.
* fix(terminal): preserve ordinary foreground command names
* refactor(terminal): reuse the non-shell foreground check in inspection
Fold the duplicated isShellProcess call into one binding shared by the
ordinary-name fallback and hasChildProcesses. No behavior change; the
focused daemon inspection suites still pass.
* fix(native-chat): auto-rename the workspace on a structured chat's first turn
Structured native chat (Claude and Codex) never reached the first-work
workspace rename. The orchestrator has a single production caller, the
agent-hook server listener, and structured sessions never set
ORCA_PANE_KEY, so no hook event could ever be attributed to one. The
renderer knew this and suppressed pendingFirstAgentMessageRename for
structured launches at three sites, which also closed the gate the
folder-workspace title rename depends on.
The host's status feed already computes the exact edge: status 'working'
with a latestPrompt normalized the same way the hook payload is, and a
workspaceId that IS the worktree id. Publish that projection to the host,
thread it out to the runtime, and hand it to the same orchestrator the
hook path uses.
Re-projections of state the host already knew (restore, an arriving
subscriber) are flagged as replays and map to the orchestrator's existing
isReplay gate, so a host restart cannot rename off a stale journal.
One host and one journal serve both providers, so this covers Claude and
Codex together.
Verified in a live Electron instance, worktrees created through the real
composer and prompts sent through the real chat composer:
Codex langouste -> retry-helper-exponential-backoff
Claude prowfish -> parse-csv-headers
* fix(native-chat): preserve first-work rename across runtime and queued turns
* fix(native-chat): skip branch rename for folder projects
---------
Co-authored-by: Merge Sim <sim@local>
* fix(windows): reject stale parent PID links in exit snapshots
* refactor(windows): share the walk's pid index in the stale-link filter
Resolve parent links through the same index the descendant walk builds, so a
table that repeats a pid answers both the same way, and drop the non-null
assertion on the walk by keeping the "cannot see" null contract.
Pin the two filter branches nothing exercised: the root surviving its own
recycled ppid, and the root's start bounding a link whose claimed parent
denied its creation time.
* test(windows): pin the root creation-time floor and its tie
The floor clause survived deletion: for a chain of timestamped rows the
per-parent check already enforces order transitively, so it only does work
below a row that denied its creation time -- admitted unchecked, and its
children then find no parent time to compare against either. Cover that chain
with a child at the root's exact timestamp, which a same-millisecond spawn
produces routinely, and one that predates the root.
Also pin that pruning a link drops the unidentified rows beneath it from the
count, since a retained one would cap the verdict at unverifiable over a
process the root never owned.
Record why ties pass, what the floor is for, and the clock monotonicity the
filter assumes.
* docs(windows): say why the pid index is shared with the walk
The index is not reused across the two calls -- the walk indexes the filtered
array -- so name the actual reason: a repeated pid must resolve first-wins, the
way the walk resolves it, rather than last-wins as a Map over the rows would.
* docs(windows): describe why both pid lookups share one index
* docs(windows): put each pruning rationale on the code it justifies
---------
Co-authored-by: Merge Sim <sim@local>
* feat(chat): show turn-scoped activity tail
* fix(chat): keep turn activity broad
* feat(chat): surface provider activity in turn tail
* fix(chat): keep reasoning headline as activity and widen redaction
A Codex reasoning summary streams as a bold headline followed by body text.
Folding the whole summary into the tail leaked literal ** markers and body
prose; only the first non-empty line is activity copy, and an unterminated
bold header mid-stream is unwrapped too.
Redaction used a hyphen for GitHub token prefixes (they use an underscore),
and missed fine-grained GitHub tokens, AWS access key ids, JWTs, URL
userinfo passwords, and bare token= values.
* fix(chat): wait for a complete reasoning headline
A bold headline still streaming has no closing marker yet; holding the
previous activity copy until it lands avoids flashing a half word.
* refactor(chat): drop bespoke secret redaction from activity copy
Reference agent hosts render provider-derived status text unredacted;
this table was the only one of its kind and its GitHub pattern matched
no real token. Bounding and the reasoning-headline extraction stay.
* Bound provider headline updates and clear activity on reconnect
---------
Co-authored-by: Merge Sim <sim@local>
* fix(native-chat): settle a structured send the provider proves it received after the ack window
A send waits a bounded window for the provider to echo the message it was given.
On timeout the dispatch resolves `unknown`. The echo that arrives later IS matched
— `recoverLateIdentity` uses it to repair the session's turn identity — but nothing
tells the journal, and `unknown` is terminal there. The submission stays unknown for
the life of the session.
Two consequences, both reachable on any ordinary session:
- The composer renders "Message delivery is unconfirmed." with a Retry, forever,
for a message that was delivered and answered.
- Retry redispatches, because the host only replays a recorded outcome unless
`retryUnknown` is set, which that button is the only thing that sets. So the
banner is a duplicate delivery armed and waiting for a click — and a user who
believes the banner and resends is doing exactly that by hand.
Every send made while a turn is already running takes this path: the provider does
not echo a queued message until the running turn ends, which is far past the 10s
ack window. Sends made while idle are unaffected, which is why this reads as
intermittent.
Carry the `clientMessageId` on the dispatch waiter and settle the journal
submission `accepted` when the late echo proves delivery. Deliberately unfenced
against the dispatch sequence: that fence decides which turn owns the identity,
while delivery is settled either way. Already-terminal rows are untouched.
* fix(native-chat): persist late dispatch receipts before session close
---------
Co-authored-by: Merge Sim <sim@local>
* fix: restore the full sidebar agent row for structured native chat
The host status feed projected only state, prompt, and agent type, so a
structured Claude/Codex row fell back to the tab title and the agent-type
label where a hook-reported row shows the running tool, the agent's last
message, and the model.
Project the tool line and the newest assistant prose from the journal, and
take the model from the session record's acknowledged options. The tool scan
stops at the live turn's lifecycle row and only runs while a turn is running,
so an abandoned call from a crashed turn is never reported as live work. The
assistant line is bounded to the shared preview cap rather than the hook
field's 8 KB body: a streamed reply re-projects on every journal checkpoint,
and the row renders one line of it.
* fix: keep structured session status current
---------
Co-authored-by: Merge Sim <sim@local>
* fix(ui): contain source control header actions in narrow sidebars
* fix(ui): preserve source control headings and conflict status at narrow widths
* chore(ui): rely on shared section toggle padding
* feat(native-chat): offer the link-action popover for chat links
A plain click on an http(s) link in a native chat transcript opened the
system browser outright, ignoring the link-routing preference the same
link honors in the terminal. Chat now shows the terminal's destination
popover, with the modifier chords routing straight to a destination.
The popover, its request type, the destination policy and the routed open
move out of terminal-pane so both surfaces share one implementation; the
catalog keys keep their original namespace because they carry shipped
translations. Chat resolves its link owner from the session workspace
(runtime, then SSH, unresolved stays unknown) so a remote transcript only
offers Orca Browser when that host's managed browser route is eligible.
The existing toggle now governs both surfaces, so it is retitled; with it
off a chat link still opens on a plain click instead of going dead.
* Fix native chat link popover lifecycle and keyboard anchoring
* test(native-chat): use one store mock for link actions
* fix: update reliability gate for shared link popover tests
---------
Co-authored-by: Merge Sim <sim@local>
* Refactor Cmd+J ranking to semantic-first ordering with activity bucketin
Replaces the old score-based ranking with a semantic-first contract that
compares destination, recovery, word match, coverage, strength, and placement
before using age buckets and recency to break ties. Adds explicit field roles
(primary, secondary, alias, container), identity encoding, and activity-based
bucketing so recent activity never overrides semantic relevance. Removes the
substring-elision deduplication of secondary fields. This fixes the fixture
where titles like "atlas-follow-up.md" beat recently active "Clarify Atlas
action items".
* Encode palette IDs and display secondary matches as badge
- Structured identity encoding for consistent ID handling
- Badge+tooltip reduces clutter of additional secondary matches
- Reorder activation to refocus group after state updates
* Encode tab palette identities to resolve collisions across hosts and wor
- Use composite keys (executionHostId, worktreeId, tabId) to uniquely identify tabs
- Validate tab accessibility before activation to prevent mutation on invalid state
- Extract getActivatableBrowserWorkspaceTab for consistent browser workspace validation
- Refactor workspace tab validation with stricter collision and ownership checks
- Remove unused comparePaletteActivity and mergeCandidateSummaries functions
* Update palette identity tests to use encodePaletteIdentity
Replace manual command-item ID construction with encodePaletteIdentity()
to include host and worktree context, ensuring tests match the encoding
scheme. Also adjust component styling (flex-1→flex-auto) and make
HighlightedText highlight class customizable for secondary match badges.
* rm design doc
* Use stable field identity and field objects for ranking optimization
- Add proofIdentity field to enable consistent tiebreaking in matches
- Pass field objects in FieldHit instead of fieldId strings
- Encode metric keys as numbers via bitwise operations
- Eliminate document lookups for field coverage calculation
* Reject hostless tabs when worktree IDs are ambiguous
When worktree IDs collide across hosts, hostless tabs cannot be safely
attributed. Refuse activation to prevent accidental host switching.
Improve badge accessibility by keeping it out of tab order and
exposing secondary matches through screen reader text only.
* Improve cmd-j palette ranking with token-count tiebreakers and identity
Add containerOnlyTokenCount and recoveryTokenCount fields to distinguish
entities when match quality is equal, enabling better ranking of results
that rely on container fields or recovery mechanisms. Cache paletteIdentity
in search results to avoid repeated encoding during sorting. Extract omnibox
field filtering and open-tab capping into reusable functions. Optimize
evidence-unit iteration to only process matched units. Strengthen worktree
ambiguity checks to reject hostless tabs when IDs collide across hosts.
* Add clarifying comments to palette ranking retention logic
- Document why capPaletteSection retains the selected match
- Explain retainedResultId's role in keeping keyboard selection visible
- Clarify secondaryMatches exposes additional match offsets
* Centralize palette identity and unify host ownership resolution
- Compute palette identity at search result level instead of constructing ad-hoc
- Include folder workspaces in palette ownership via getPaletteOwnershipWorktreeIds
- Add duplicate detection to filter colliding tab, page, and file IDs
- Refine ranking with containerOnly metric and source-order tiebreakers
- Improve secondary matches badge accessibility for keyboard users
* Route same-target SSH worktrees through paired runtime owners
- Centralize worktree palette identity resolution via getPaletteWorktreeIdentity
and getPaletteWorktreeExecutionHostId, which use runtimeOwnerEnvironmentId when
present instead of physical hostId
- Deduplicate worktrees by palette identity to keep same-target SSH worktrees
distinct when paired with different runtime environments
- Replace scattered getWorktreeHostIdentity calls with new palette-specific
resolution functions across palette components and search logic
- Fix accessibility: move badge out of tab order, expose extra matches through
row text instead of interactive tooltip
* fix static analysis
* fix(native-chat): stop seeding a stray terminal beside a chat create
A native-chat worktree create activates with `providesInitialSurface: true`,
meaning "I open my own primary surface, don't seed a shell". Activation only
honoured that when there was no other activation work, so any repo returning a
setup script fell through to `ensureWorktreeHasInitialTerminal`, which created a
bare terminal purely to act as the primary tab before giving setup its own tab.
The user landed on `Terminal 1` + `Setup` + `Claude Chat`.
The bare terminal was never needed for a new-tab setup: `queueSetupAndIssueCommands`
only uses the primary tab there to restore focus to it.
Forward `providesInitialSurface` into seeding as `callerProvidesSurface`, and skip
the shell when the launch work needs no host tab. A terminal is still seeded when
something has to attach to it: a startup command, issue automation, a split-mode
setup script, `createNewTerminalForStartup`, or configured default tabs.
* Fix background native chat setup terminal seeding
* Avoid passive terminal seeding during native chat launch
---------
Co-authored-by: Merge Sim <sim@local>
* perf(store): detect Zustand rerender churn the current audit cannot see
The app-store-performance audit only understood inline selectors passed to a
hook imported literally as `useAppStore`, so three shapes went unlinted:
- a selector referenced by name (`useAppStore(selectRows)`), including one
hoisted below its call site — resolved now via a Program:exit pass
- the sibling store hooks (`usePluginPanelsStore` and friends), matched by the
use<Name>Store convention on local imports; React's `useSyncExternalStore`
matches that shape and is excluded
- a fresh reference nested inside a `useShallow` projection, which is the worst
case of the three: the comparator runs on every write and can never match, so
the memo silently buys nothing
`no-nested-fresh-under-shallow` covers the last one. `src` is clean against all
four rules today, so this is a ratchet rather than a cleanup.
The write side stays undecidable statically — whether a `set()` reallocated for
nothing depends on the payload — so it gets a runtime probe instead.
withStoreIdentityChurnProbe counts writes that replace a field's reference while
its value stays equal, and can name the calling site. Cost when disarmed is one
boolean load per write, matching react-commit-cascade-write-probe.
* perf(store): scope the churn probe's scan to the write's own keys
recordWrite iterated Object.keys of the full post-write state, so the armed cost
scaled with the store's top-level field count (hundreds) rather than the size of
the write. `set(partial)` merges, so no field outside the partial can have changed.
The wrapper now resolves a functional updater itself and iterates the resolved
partial's keys. Same function, same argument, called once — there is a test
pinning that, since calling it twice would double any work a slice does inside
its own updater. A replace write drops absent fields, so that path still scans
every field.
Disarmed cost is unchanged: one boolean load.
* perf(store): follow a selector one hop into its helper
Review feedback: both the lint rule and the manual sweep it was checked against
only looked at the inline selector body, so neither could see a fresh allocation
made inside a helper the selector calls — and delegating to a module-scope helper
is the idiomatic shape here. Two methods sharing a blind spot is not corroboration.
The two fresh-reference rules now resolve a single hop into a module-scope helper.
The predicate used across that hop is deliberately stricter than the inline one:
it requires EVERY returned expression to allocate unconditionally, so the common
`cache.get(k) ?? buildFresh(state)` identity-caching shape is not flagged. An
unresolvable helper is left alone rather than guessed at.
Still zero hits across 20,330 files, so this stays a ratchet.
* perf(store): keep the churn probe off the shipped write path
Review hardening for the churn probe and the widened lint rules.
Probe: it no longer resolves a functional updater itself. Zustand keeps sole
ownership of when and with what argument an updater runs, so the middleware
cannot double-invoke it or hand it a stale state. Object partials still scope
the scan to the write's own keys; updater and replace writes fall back to the
full field list, which costs one Object.is per untouched field and nothing
more, since the deep compare only runs on replaced references.
store/index.ts installs the probe only when import.meta.env.DEV or
e2eConfig.exposeStore is set, the same gate as __store exposure. Nothing in the
app arms it, so a shipped build was paying a wrapper frame per write for a
diagnostic it could never read. The cascade probe stays unconditional because
crash telemetry arms it in the field.
Site capture now skips any *-probe.ts frame; under the real composition the
first non-node_modules frame was the cascade probe's wrapper, so every churn
was attributed to react-commit-cascade-write-probe.ts:32 instead of the caller.
Plugin: named-selector recording is restricted to module scope. A
component-local `const selectRows = ...` used to overwrite the entry for a
same-named imported selector and flag an unrelated useAppStore(selectRows).
The any-branch and every-branch allocation predicates are one function with a
flag, the Object.* static list is a Set, and import recording is a single pass.
Tests: updater called once with live state, identical-state writes ignored,
disarmed path forwards exact arguments without calling get(), full composition
with the cascade probe (no drop, no double, correct site), and the
module-scope shadowing case for the plugin.
* perf(terminals): keep shutdown maps' identity when there is nothing to clear
commitTerminalShutdownState spread nine maps unconditionally. Sleeping a worktree
whose panes already exited is the normal case and clears nothing, so each map came
back with a new identity and identical contents.
ptyIdsByTabId is the costly one: six components select it whole, and
selectLivePtyIdsForWorktree memoizes per sidebar card on its identity, so churning
it rebuilt that record once per card. It also wrote a fresh [] for every tab even
when the entry was already an empty array.
Every map now uses the copy-on-write shape the four unread/input maps in this same
function already had.
Two correctness points the guards encode:
- an absent ptyIdsByTabId key is NOT an empty array; the spread this replaces
created the key, so only an already-empty entry may be skipped
- an absent pendingPtyShutdownIds owner count meant `delete` of a missing key,
which changed nothing, so those are skipped rather than copied
- a layout whose ptyIdsByLeafId is already empty keeps its entry instead of
getting a fresh {} with the same value
* refactor(terminals): fold the shutdown maps' copy-on-write into one record helper
Nine hand-rolled lazy-clone blocks become copyOnWriteRecord: delete of an absent
key is a no-op there, so the identity guard lives in one place. The two guards
that are not plain deletes stay explicit — ptyIdsByTabId must still create an
absent entry, and pendingPtyShutdownIds only decrements an existing owner count.
* style: format the shutdown identity test with oxfmt
Committed with --no-verify, so the pre-commit formatter never ran on it.