Commit Graph
10482 Commits
Author SHA1 Message Date
OrcaWinandm4air 102402e41e fix(deps): update DOMPurify sanitizer hardening (#19377)
Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
2026-09-07 17:43:28 -07:00
OrcaWinandm4air b8f6c7cabe fix(deps): update react-i18next for TypeScript 7 and parser fixes (#19378)
Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
2026-09-07 17:43:18 -07:00
OrcaWinandm4air a4e5106e14 chore(docs): patch brace expansion resource exhaustion fixes (#19382)
Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
2026-09-07 17:42:55 -07:00
OrcaWinandm4air 1dae024ab2 chore(mobile): patch xmldom security fixes in plist tooling (#19380)
Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
2026-09-07 17:42:48 -07:00
OrcaWinandm4air 91fbc1529a fix(deps): harden cloud HTTP and WebSocket dependencies (#19362)
Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
2026-09-07 17:42:37 -07:00
OrcaWinandm4air cfd59f2ca0 fix(deps): update desktop parser security dependencies (#19361)
Co-authored-by: m4air <m4air@m4airs-MacBook-Air.local>
2026-09-07 17:42:29 -07:00
Brennan BensonandMerge Sim 3b8128df04 fix(orchestration): index per-PTY mailbox reservation cleanup (#19390)
Co-authored-by: Merge Sim <sim@local>
2026-09-07 17:42:23 -07:00
Neil 588240043e fix(sidebar): reveal collapsed workspaces without clearing filters (#19398) 2026-09-07 17:14:54 -07:00
Brennan BensonandMerge Sim 9f044031fc fix(native-chat): render compaction notices, plan documents, and images (#19228)
* fix(native-chat): render compaction notices, plan documents, and images

* fix(native-chat): avoid repeating notice text in details

* fix(native-chat): journal canonical and legacy compaction events

* test: add digest to native chat notice payload fixture

* chore(native-chat): drop the planning doc from the PR

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 16:21:47 -07:00
Neil 2265fce591 chore(mobile): remove stale max-lines exceptions (#19366) 2026-09-07 14:54:18 -07:00
Brennan BensonandMerge Sim d0506bf5de feat(native-chat): add execution details and tool row identity (#19226)
* feat(native-chat): annotate tool rows with execution and source details

* fix(native-chat): require explicit MCP identity for tool annotations

* test: add required state to MCP projection fixture

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 13:51:47 -07:00
Brennan BensonandMerge Sim 0b3af9ddbc Show native chat message timestamps on hover and keyboard focus (#19218)
Co-authored-by: Merge Sim <sim@local>
2026-09-07 13:46:21 -07:00
Jinwoo Hong bcd4076dd1 fix(relay): never cache a region hint from a one-region catalog (#19349)
* fix(relay): never cache a region hint from a one-region catalog

The director lists only regions with a serving cell, so a roll wave shortens the
catalog to one entry. The resolver required only every *listed* region to be
measured, so that lone region won against nothing and was cached for 24 h: a US
desktop refreshing while US cells rolled published asia-east2 for a day, the
incident #19233 was written to end. Now fewer listed regions than the fleet serves
withholds the hint (1 h no-hint TTL), the same outcome as an unmeasurable peer.

* test(relay): give the unstable-probe case a two-region catalog so it has one cause
2026-09-07 16:44:33 -04:00
Jinwoo Hong d936d8da82 revert(mobile): pull the relay connect-speed mobile pass pending a smaller, verified re-land (#19348)
* Revert "feat(mobile): time relay dial stages so diagnostics say where a slow connect went (#19245)"

This reverts commit 83b1558ecc.

* Revert "perf(mobile): race the direct and relay dials from t=0 on every reconnect (#19308)"

This reverts commit ceafdcad2f.

* Revert "feat(mobile): draw the last known tab strip while a session reconnects (mobile pass) (#19281)"

This reverts commit 643571def6.

* Revert "perf(mobile): open a session with parallel startup RPCs and a pre-warmed terminal engine (#19260)"

This reverts commit c37413271e.

* Revert "perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (mobile pass) (#19280)"

This reverts commit e628090ad4.

* chore: keep the react-doctor suppression for the startup timers

The pattern it covers (a variable number of timers cleared through one cleanup)
predates #19260 and is unchanged by the revert; dropping the entry only re-exposed
a pre-existing finding to the changed-code gate.
2026-09-07 16:44:26 -04:00
Brennan BensonandMerge Sim 6a47d2831f fix(native-chat): scope composer file drops to the pane that received them (#19328)
* fix(native-chat): scope composer file drops to the pane that received them

A native OS file drop resolving to `target: 'composer'` carried no pane
identity, so the window-wide payload was attached by every mounted composer.
Because inactive chat tabs stay mounted (hidden), one drop populated every
chat pane's attachment cache, and those chips replayed whenever the user
returned to a tab they never dropped into. The workspace-creation composer
and chat composers also leaked into each other, since neither could tell
which surface actually received the drop.

Composer drops now carry a `scopeKey` the way a terminal drop carries its
tab and pane leaf id: the composer publishes its pane key as
`data-composer-scope-key`, the preload harvests it during the composedPath
walk, and each composer attaches only its own. The workspace composer's
last-wins ownership stack now claims unscoped payloads only.

* test(native-chat): supersede the bug-asserting drop repro with the scoping test

The repro that landed on main asserts the pre-fix behavior (a drop reaching
every mounted composer), so it fails once drops are scoped to the pane that
received them. Its scoping cases now live in
native-chat-composer-drop-scope.test.tsx, which keeps its editor-target
control case verbatim and adds coverage for unscoped composers and a scope
key published inside the drop-target marker.

* test(native-chat): cover workspace composer drop isolation

* fix(native-chat): authorize external attachment paths before preview

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 13:34:23 -07:00
Brennan BensonandMerge Sim 5cefb440bf fix(native-chat): stop an unanswered host from reading as one that refuses structured chat (#19321)
* fix(native-chat): stop an unanswered host from reading as one that refuses structured chat

`readLocalRuntimeCapabilities()` returned `[]` both before the first status probe
landed and after one failed, so "not asked yet" and "host says no" were the same
value. Every structured-chat launch route consumed it, and an unprobed host was
routed to legacy chat exactly as a refusing one is.

Keep the two apart: the cache holds `null` until a probe succeeds, a failed probe
leaves it `null` rather than emptying it, and the launch route names the case with
its own blocker instead of borrowing `runtime-capability`.

No routing outcome changes — both cases still decline structured chat. The point is
that the reason is now truthful, which is what the routing work needs to build on:
once a launch can target a runtime peer, capabilities come from that host, and an
unanswered remote must not be indistinguishable from one that refuses.

`hostCapabilities` on the launch route stays local-only at every call site; a
per-target resolver replaces it when the route learns to reach a peer.

* test: cover unknown runtime capability lifecycle and launch fallback

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 13:25:40 -07:00
Jinjing 1d1b73c408 Defer inactive browser pages across worktree switches (#19326)
* Defer inactive browser tabs while retaining their viewport slots

Restore worktrees and tabs on demand instead of mounting the full tree.
Only render active pages and those required by automation, mobile drivers,
or remote viewers. Inactive panes stay deferred with persistent viewport
slots so their webview guests survive chrome unmounts, reducing memory
overhead when opening workspaces with many tabs.

* Defer browser pages until active and recover if evicted

Pages defer rendering until active, then retain state when inactive.
Add recovery logic to restore guests evicted by workspace memory
pressure when pages are reactivated.

* Stop retaining browser content when worktree is inactive

- Browser panes and pages now unmount when their worktree transitions to inactive, except for pages claimed by automation/mobile/viewer consumers
- Prevents unwanted restoration of all hidden browser tabs when switching between worktrees
- Tests verify proper cleanup at scale and correct page lifecycle across worktree switches

* Preserve document-preview guests when switching browser tab profiles

Document previews use a fixed partition and should not be recreated when
the profile changes. Only URL-based pages need their webviews destroyed
and rebuilt with the new profile. Includes test coverage.

* Create browser pages cold to defer guest initialization

Pages created in the background now start with loading: false, since they
don't own a guest until first shown. Only live guests can report loading
status, so background tabs sit idle until activation triggers navigation.

* Prevent document preview from swallowing pointer events during drag

Move webview registration to attachDocPreviewWebview before append,
ensuring it's enrolled in drag passthrough before becoming hittable.
When a document preview tab remounts mid-drag, the previous hook-based
enrollment landed too late. Also refactor mountEligible into
isBrowserPagePanePaintable for clarity.
2026-09-07 12:20:27 -07:00
Brennan BensonandMerge Sim ce4a3a4186 feat(chat): add structured session rewind backend (#19235)
* feat(chat): add structured session rewind backend

* fix(chat): make interrupted session rewinds recover safely

* fix(native-chat): negotiate rewind runtime capability

* fix(native-chat): consolidate remaining adapter imports

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 12:20:24 -07:00
Jinjing 9fed61e5c2 Persist agents sidebar search visibility as pairing-local preference (#19313)
* Persist agents sidebar search field visibility as pairing-local preferen

- Add `agentsShowSearch` to workspace UI state with default on
- Include in pairing-local fields so preference syncs across clients
- Convert search from menu action to checkbox menu item for explicit toggle
- Update activity thread options menu to reflect checkbox state
- Add localization strings across all supported languages
- Update RPC schemas and preference persistence layer
- Includes readiness validation reports confirming feature is clean

* rm review

* fix documentation
2026-09-07 11:27:40 -07:00
Jinwoo Hong 83b1558ecc feat(mobile): time relay dial stages so diagnostics say where a slow connect went (#19245)
* feat(mobile): time relay dial stages so diagnostics say where a slow connect went

A 10s connect was unattributable from a shared report. Relay dial stages carried
no timestamps, so nothing could tell "the cell never answered relay-hello" from
"the E2EE handshake was slow", and the per-state dweltMs the client already
computed went only to console.log — invisible without a debug build.

RelayDialStageTracker now stamps each stage entry from a monotonic clock
(performance.now where present, wall clock otherwise) and returns the duration of
the stage it just left. The session logs one entry per stage, and settles the
in-flight stage on connect, failure, or close, so a dial that dies mid-way still
names the stage it never finished. dweltMs joins the same buffer as a structured
field instead of console.

Durations ride the existing per-host log buffer and its cap, so memory is
unchanged and no new storage appears. The report derives two lines from them: the
latest dial's stage breakdown (a reconnect loop must not average away the attempt
being reported) and total dwell per connection state. Both are numbers and
closed-enum names, and the entries still pass through the existing redaction.

* fix(mobile): never let a diagnostics sink break a dial, and pin timing names to their enums

Review follow-ups on the dial-stage timing work.

The stage timing emitted on the confirm's success path ran inside the try that
calls fail(), so an onLog sink that threw would have turned a good connect into a
failed session. The same hazard existed on the direct path, where the dwell emit
sits in publish() ahead of the listener loop and the connect waiters. Both sink
calls are now isolated: a broken sink loses a log line and nothing else.

The persisted-log validator accepted any string as a timing name, and the report
echoes that name unredacted. Names are now checked against the closed enum for
their kind, backed by Record<Union, true> tables so adding a stage or a state
breaks the build rather than silently widening what a corrupted store can inject.

Entry volume: every reconnect cycle walks four connection states, so logging each
one would roughly double what a slow-connect report holds against the unchanged
200-entry per-host cap. Transitions under 100ms are therefore not buffered. They
cannot be where a slow connect spent its time, and console still shows all of
them. States that flap slowly, which is the case support cares about, still land
in the log.

RpcClientConnectionState takes an optional clock so dwell thresholds are testable
without sleeping.

* fix(mobile): reject a negative stored stage duration when hydrating the log

A persisted timing only had to be finite to survive hydration, so a corrupted
`ms: -1` reached the diagnostics report, where the dial summary sums the stage
durations and a negative would subtract from the total. Producers clamp at 0
(`elapsedMs`), so anything below it is corruption. 0 itself still hydrates: a
stage the dial passes through instantly is real.

* refactor(mobile): move the relay liveness profile out of the session so the dial log fits

* fix(mobile): never let the liveness-timeout log line keep a dead relay connected

* test(mobile): prove the throwing timeout sink was actually reached
2026-09-07 13:52:15 -04:00
Jinwoo Hong ceafdcad2f perf(mobile): race the direct and relay dials from t=0 on every reconnect (#19308)
* perf(mobile): race the direct and relay dials from t=0 on every reconnect

A foreground reconnect gave the direct dial a fixed 2.5s head start, and while
that dial sat in 'connecting'/'handshaking' the supervisor refused to open a
relay socket at all. A phone that is off the LAN paid the full head start on
every reconnect and got nothing for it, and a phone whose relay dropped could
only return to the LAN through three hysteresis probes.

Both dials now start together and the first authenticated socket is adopted
through the existing migrateTo cutover. Nothing about the migration machinery
changes: only who is allowed to start a dial.

- The relay dial now yields to a live session and to nothing else. An unfinished
  direct dial is progress on the other runner, not a reason to stand still.
- The direct return probe grows a second adoption policy. Against a live relay
  hysteresis still has to prove direct stable; during a reconnect there is no
  session to protect, so an authenticated direct socket wins outright. probeNow
  pre-empts a pending 15s tick so that dial starts with the relay dial, not
  after it, and the dial itself no longer waits for the operation mutex — a
  relay dial holding it is exactly the case the race exists for.
- A loser closes and books nothing. The relay dial withdraws inside migrateTo
  and returns 'aborted', so no backoff is booked against it; a direct socket
  that loses leaves the promotion streak untouched. Only a reconnect that both
  paths lose books a failure, once, on the relay cadence.

Kept: the 30s background grace and the foreground gate, because a backgrounded
phone must not open a billed relay splice; the shared failure cooldown, because
a genuine relay failure still has to be paced; the hysteresis dwell after a
migration, because it is what stops a marginal LAN flapping a healthy session.

The accepted cost is one relay socket per reconnect for a phone that is on its
LAN. It closes as soon as the direct path authenticates, before the resume
confirm, because migrateTo only checks the abort predicate after E2EE auth.

Tests that encoded the removed rules:
- 'fails over when the direct retry loop publishes reconnecting' asserted no
  relay dial while direct was handshaking. The failover now precedes the direct
  client giving up, so it asserts the dial instead of its absence.
- 'does not spend a queued relay retry while direct authentication is
  progressing' encoded the block outright; it now asserts the retry runs on the
  failure cadence while a handshake drags on.
- The four grace-race cases move to mobile-endpoint-reconnect-race.test.ts as
  t=0, direct-wins, background/resume and both-lose cases.
- Five relay-bookkeeping cases now state their premise with unreachableDirect.
  They describe a phone with no LAN, which used to be implicit and is now
  load-bearing: with a reachable LAN the direct socket wins those reconnects.

* fix(mobile): withdraw a lost relay dial pre-handshake and damp blip races

Review follow-up to 4e31130471. Racing both paths from t=0 was correct but
charged the LAN case twice: once per reconnect in cell work, and again whenever
the LAN flapped.

Withdraw before the handshake. migrateTo only consults its abort predicate after
E2EE authentication, so a dial that had already lost still made the cell reserve
a splice and the desktop finish a key exchange. The establisher now watches the
logical client across the dial and closes the cell socket the moment direct
authenticates. In the common window, after relay-auth is on the wire and before
the hello lands, nothing of the key exchange has started, so the withdrawal
costs the desktop nothing. The dial still reports itself aborted and still books
nothing. The watch is dropped once migrateTo returns, because past the cutover
this session is the active path and a later direct promotion must not read as a
reason to close the client's own socket.

Damp races that a blip started. relayDialAllowed yields only to a live session
and a lost race books nothing, so a flapping LAN drove one cell socket per blip
with only the relay's per-host rate limiter as a backstop, and reaching that
limiter would have converted a benign race into a booked relay failure. After a
race is lost to direct, the next unforced race is suppressed for 2s, doubling
per consecutive loss to a 30s cap. This is not backoff and is kept separate from
it: a forced replacement is never damped, a relay dial that wins clears the
streak, and a foreground resume clears it too, so the path the user is watching
never waits. The window arms its own lapse timer, so a LAN that dies inside the
window still reaches relay without a new trigger.

A superseded cutover no longer escapes probe() as an unhandled rejection. Only
the probe timer calls it, and it discards the promise, so the routine end of a
lost race would have surfaced as one.

Credential rotation moves to MobileRelayCredentialRefresh. The supervisor
crossed the 300-line cap; rotation is a self-contained responsibility that only
runs over a live direct connection, so it splits cleanly instead of taking a
max-lines bump.

* fix(mobile): end a damper window as soon as the direct path is really gone

Round-2 review follow-up to 9a21da4326. The damper armed its window when direct
won the race, and nothing shortened it. A LAN that died inside that window left
the phone waiting out the whole thing, up to 30s at the cap, with only a log
line to show for it. My previous commit body claimed the path the user watches
never waits; that was true only of a foreground resume, and it is corrected
here.

Losing the direct path now collapses the wait to a 250ms floor, so the next
recovery races almost at once. The floor is not zero because the reason the
damper exists is a LAN that drops and comes straight back, and a disconnect is
how such a blip begins. So the rest of the window is kept aside rather than
spent: if direct returns inside the floor it was a blip and the window resumes,
and if the floor lapses with direct still gone it was an outage and the held
window is void. Without the second half, one blip would have bought a flapping
LAN a free pass on every race that followed, which is the case the damper was
added for.

The streak itself is untouched by the clamp. A LAN that flaps all afternoon
still escalates toward the cap; only the current wait is cut short.

record() now takes the same forceReplacement guard as suppresses(), so a forced
replacement that stands down cannot grow the streak or be read as a loss to
direct. A lease rotation or a reconsidered network change is not a LAN that
flapped.

Also documents that a genuine relay failure deliberately does not reset the
streak, and that the damper and the failure backoff serialize rather than stack:
a damped attempt never reaches the dial that would book a cooldown.

* fix(test): give the direct-probe fixture the race-era hooks

The phase-1 probe test predates canDial and adoptsOutright, so its hooks
literal threw at the first dial. These cases model a live relay session.

* docs(mobile): say why a finished credential refresh races relay instead of waiting on direct
2026-09-07 13:45:51 -04:00
Jinwoo Hong 5857357fcf feat(relay): log the region probe and name the assigned cell (#19307)
* feat(relay): log the region probe and name the assigned cell

A desktop silently pinned itself to a far relay region for a day and every
phone connect paid the round trip. Nothing in the desktop logs said which
regions were probed, what they measured, why one was rejected, or which cell
the host landed on, so the only way to diagnose it was a bench harness.

The resolver now emits one line per outcome. A refresh carries every region's
probe origins, the discarded warm-up, the kept samples, the minimum, the
spread, and a verdict, then the chosen region or no-hint with the reason it
withheld one. Cache hits, diagnostic overrides, and a director that cannot
list its regions each get their own line so a quiet run is never ambiguous.
Self-heal logs the cached region, the best measured region, the assigned
cell's round trip, and whether it kept or deleted the cache. Only a refresh
reports a catalog failure; a self-heal never chose a region, so a line saying
it withheld a hint would be a lie.

Relay status now carries the assigned cell so the pairing panel can name it.
The field is optional because an offline host holds no assignment and the web
client answers from a stub that never has one.

Splitting catalog fetching out of the preference module keeps both files
inside the line budget without a lint disable.

* fix(relay): drop the assigned cell from statuses not served on it

The origin pool publishes offline while it still holds the assignment it is
about to rotate, so the panel kept naming a cell nothing was served from. The
same class of bug hid a second instance: the coordinator republishes
registered right after the broker announces its cell, and that republish
carried no cell, blanking the value moments after it was set. The cell would
never have reached the panel in the real flow.

Deriving the cell from the status at each publisher removes both. The rule
lives beside the status type because it defines when the optional field is
populated, and the coordinator reads the owned broker's endpoint rather than
trusting a call site to remember to pass it.

* i18n: add the relay cell label to the English catalog

* test(relay): audit the relocated region catalog fetch call site

* fix(relay): report a self-heal whose catalog request failed instead of staying silent
2026-09-07 13:45:48 -04:00
Jinwoo Hong 643571def6 feat(mobile): draw the last known tab strip while a session reconnects (mobile pass) (#19281)
* feat(mobile): draw the last known tab strip while a session reconnects

Reopening a workspace the phone has already visited threw away everything
it knew. The route clears its tabs on mount, so until the reconnect lands
and the first snapshot is applied the session screen has an empty header
and a bare spinner, even though the strip it is about to be handed is the
one it drew a minute ago.

Persist the four fields the strip actually draws -- id, type, title, agent
-- per host and workspace, and add a reconnecting-with-cache shape to the
route state so those rows render immediately, disabled, under the ids the
live snapshot will reuse. Live tabs always outrank the cache, so a
mid-session drop keeps its mounted terminals; an exhausted retry loop or a
rejected pairing outranks it the other way, because a strip the user cannot
reach is worse than the existing offline affordance. With nothing cached
the screen behaves exactly as before.

The body stays a placeholder. Replaying stored scrollback into the terminal
WebView would double-render the same rows once the live stream replays them,
so the strip is the cached content and the body waits for the stream.

* fix(mobile): keep shell titles and unpaired hosts out of the cached tab strip

Review of the reconnect strip cache found two ways it leaked.

A terminal's title is whatever the shell last set, which is routinely the
command line: a psql URL with an inline password, a curl with a bearer
token. Both fit well inside the 64-character cap and both were written to
plaintext AsyncStorage verbatim. Browser tabs carried their page title the
same way. Terminals and browsers now collapse to a fixed label, with a
resolved agent naming itself because that lookup is a closed enum. The rule
lives in the storage module rather than its caller, so it holds for entries
an older build already wrote, and a tab type this build cannot draw is
dropped instead of having its title trusted.

The cache also survived forgetting a host. Nothing expired an entry, and
the module-global memory map meant a later save from any surviving host
serialized the forgotten host's rows straight back to disk. Both cleanup
paths now evict by host, dropping the in-memory rows and rewriting storage,
with a pending debounced write cancelled so it cannot restore them.

Also: the storage key digests the workspace id, which ended in a filesystem
path, and cached rows carry the same de-emphasis as the disabled tab-bar
buttons beside them, so an inert row does not pass for a live one.

* fix(mobile): make a forgotten host's cached tab strip actually leave disk

Review finding on this PR, fixed here so it rides along with the rest.

writeFile swallowed its own rejection, so deleteCachedSessionTabStripForHost
resolved successfully while the unpaired host's plaintext tab titles stayed on
disk, and removeHostAndCloseClient discarded the promise with void so nothing
could have observed the failure anyway.

The write now throws. The debounced save keeps a best-effort catch, since a
dropped cache refresh costs one repaint and the next save rewrites the whole
map, so only the deletion path needs the failure. Host removal awaits the
deletion and logs a failure but never rethrows: the metadata removal has
committed and the client is closed by that point, so reporting a finished
removal as failed would be wrong. The unpaired-host credential sweep already
awaited the deletion and now sees the rejection, consistent with its sibling
credential deletions.

Two ways the rows could come back are closed as well. The cache refuses saves
for a host it has been told to forget, so a snapshot racing the deletion cannot
re-insert it, and the deletion awaits any debounced write already on the wire,
since that write built its blob from the map as it was and would otherwise race
the purge for the last word on disk. The refusal lasts for the process, so
re-pairing the same host caches again from the next app launch, which is the
cheap direction for a deletion the user asked for.

* fix(mobile): order the tab-strip cache writes so a purge is the last word

Two debounced writes could sit on the AsyncStorage bridge at once, and the
second replaced the in-flight handle. A host purge then awaited only the newer
write, so the older blob -- snapshotted while the forgotten host was still in
the map -- could commit after it and restore the host's titles to disk. Writes
now queue behind one chain and the purge queues last.

The unpaired-credential sweep also aborted on a cache-purge failure, stranding
the write revision and onDeleted after every credential was already deleted. It
now warns and finishes, as removeHostAndCloseClient already did.
2026-09-07 13:40:35 -04:00
Jinwoo Hong 6729f3a0b0 tools: add a phone-vantage relay connect benchmark (#19251)
* tools: add a phone-vantage relay connect benchmark

Connect-speed work on the phone had no way to attribute latency to a hop.
Timing the mobile app end to end only says "connect is slow", and a synthetic
WebSocket probe does not exercise the credential check, the E2EE handshake, or
the RPCs the phone blocks on before it publishes connected.

This replays the shipped mobile wire sequence from Node against a real desktop
over the production relay, so each phase gets its own number. The handshake is a
plain-JS port of the mobile client session, which is only trustworthy if it stays
byte-identical to what ships; a parity test runs it against the real desktop
responder in the normal unit suite so drift in the transcript encoding, key
schedule, or frame layout fails there rather than producing a bench that measures
a handshake nobody uses.

Adds a foreground mode for the resume-after-background question the phone lanes
need: connect, go silent past the relay's client silence watchdog, then report
whether the retained socket still answers and what the fallback redial costs.

The bench writes a resume-credential bundle at runtime. That file carries a live
device token for a real paired desktop, so the directory ignores it outright.

* tools: make the relay bench name its target and opt in to dialing

The supporting scripts carried production defaults: the director origin was
hardcoded in both, and the hop-latency probe defaulted to a named production
cell. Running either with no arguments sent live traffic at production, and the
region probe did it on import, before any argument was read. A default like that
is the wrong shape for a bench, because the operator never states what they are
measuring against and a stray invocation is indistinguishable from an intended
one.

Every script now refuses to open a socket unless ORCA_RELAY_BENCH_LIVE=1 is set,
and the director comes from --director or ORCA_RELAY_BENCH_DIRECTOR with no
fallback. The cell origin is a required argument. Refusals print one line of
usage and exit 2, so an accidental run is inert rather than live.

The remaining host-id default is an id no desktop owns, which is the point of
that probe: it measures the cell hop without reaching a desktop at all.

* tools(relay-bench): type refuse() as never so origins are strings

* tools(relay-bench): fail closed on hostile input and bounded arguments

Review found the harness trusted whatever it was handed: the DevTools port
and the director-supplied probe origins went straight into a URL, http
origins were accepted, repeat counts came from a bare Number() cast, and the
state file kept its existing mode.

- Validate the DevTools port as a 1-65535 integer, so '80@attacker.example'
  cannot move the fetch off loopback via URL userinfo.
- Require https for every origin, and refuse loopback, link-local, private,
  and multicast destinations. Region probe origins and the cell URL the
  director returns go through the same check, so a compromised director
  cannot aim the harness at the operator's own network.
- Bound --runs, --rounds, runs, --gap, and --hold as whole numbers, so
  'Infinity' exits 2 instead of looping forever against the relay.
- Report a region as UNREACHABLE when every probe fails, rather than letting
  Math.min([]) spread into NaN and read as ok.
- Bound the director /v1/resolve and /v1/regions fetches and report timeouts.
- Return null openMs when the socket never opened, and clear dial, cell, and
  RPC timers on the first terminal event so Node exits promptly.
- Default handle.rpc() to RPC_TIMEOUT_MS, not DIAL_TIMEOUT_MS.
- Write the state file through a helper that creates the parent directory,
  refuses a symlink, and forces 0600 on an existing file; refuse to read one
  that is readable beyond the operator.
- Read the pairing link from stdin or a 0600 file, never argv.
- Reject missing and invalid positionals with usage and exit 2.

Adds unit tests for the pure guards: argument parsing, bounded integers,
port and origin classification, DNS vetting, state-file modes and symlinks,
region verdicts, and pairing-link decoding. None opens a socket, and every
network path stays gated on ORCA_RELAY_BENCH_LIVE=1.

* tools(relay-bench): settle in-flight rpcs and guard an empty region catalog

Follow-up to the review fixes. Clearing a pending rpc timer without a
resolution swapped a 15 s timeout for an await that never returns, so the
teardown paths now settle each waiter with a closed result. A director that
answers /v1/regions with no regions now reports that and exits 1 instead of
printing an empty round.

* tools(relay-bench): attach the origin-vetting doc to the function it describes

* fix(tools): resolve a director-named cell through DNS and fail cdp-eval clearly
2026-09-07 13:28:47 -04:00
Jinwoo Hong e60d9aaac9 fix(relay): attach a phone whose accept straddles a control rebind (desktop side) (#19238)
* fix(relay): attach a phone whose accept straddles a control rebind (desktop side)

The cell announces a connection with a single conn-open. When the desktop's
control socket dies mid-accept the phone waited out the 10s attach deadline and
was closed HOST_OFFLINE, even though the desktop was online. host-hello-ack
already restates those connections in pendingConns; the desktop parsed the field
and threw it away.

Desktop replays pendingConns on activation. It needs kind and relayDeviceId to
dial: they decide the pairing authority a connection carries and the E2EE device
binding, so neither may be guessed. Two sources, in order:

- the ack entry, when the cell states them. This is the case where the desktop
  never received the conn-open at all, i.e. the headline scenario, and it needs
  the cell change in #19266.
- the conn-open this process already saw, when the frame arrived but the data
  socket died with the control. Works against every deployed cell.

An entry described by neither is skipped with a warning rather than dialed.
Entries already spliced or already holding a data socket are skipped, so a
rebind never double-dials.

The desktop advertises x-orca-host-capabilities: pending-conn-details on the
control upgrade so a cell knows the ack entries will be read. The header name
and token are duplicated by hand because the desktop cannot import the relay
contract; both sides assert the literals so drift fails a test rather than
silently disabling the feature.

Also stop dropping a conn-open that lands while the control is draining. A
drain-only cell refuses new phones, so such a frame predates the drain and only
that cell holds the waiting phone.

* test(relay): pin the attach deadline the desktop mirrors by hand

RELAY_HOST_ATTACH_DEADLINE_MS duplicates RELAY_PROTOCOL_LIMITS.hostAttachDeadlineMs,
which the contract suite already pins to 10_000. Now that the cell and desktop
halves land as separate PRs the two can drift independently, and drift would
silently shorten both the observed-open eviction window and the deadline a
replayed dial states, with nothing failing.
2026-09-07 13:28:44 -04:00
Jinwoo Hong c37413271e perf(mobile): open a session with parallel startup RPCs and a pre-warmed terminal engine (#19260)
Startup RPCs now fan out in parallel and the xterm engine pre-warms inside the
real terminal frame while they are in flight, so the first pane inherits a warm
WebView and an already-measured viewport instead of paying a round trip for it.

The pre-warm opens its engine before measuring: web-ready only reports that the
bundle loaded, and the WebView answers a measure with null until a terminal
exists. It also pre-warms at the user's saved text size, because cell size is
what the frame height gets divided by.

Host writes such as worktree.activate wait for an evaluated status.get reply.
Navigation still fails open when a host cannot answer one, but that fallback no
longer reads as a passing compatibility verdict.
2026-09-07 13:16:44 -04:00
Jinwoo Hong e628090ad4 perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (mobile pass) (#19280)
* perf(mobile): cut the relay reconnect critical path and admit dead sockets faster

Phone medians put E2EE authentication at ~424ms but `connected` at ~630ms,
because the session serialized two RPC round trips behind it: the resume
confirm (`pairing.getEndpoints`) and the capability advisory. Both now ride
the authenticated socket concurrently and off the critical path, so the
session publishes `connected` as soon as E2EE authenticates. Peer identity
is already proven by then — the confirm carries credential/lease bookkeeping
and the cell assignment check, and it still fails the session on a bad answer
or a foreign relayHostId, only later. `persistResumeConfirmation` awaits the
new `whenResumeConfirmed()` instead of assuming the answer is present at
`connected`.

Foreground liveness on a retained relay: `notifyForeground('app-resume')`
now probes past the 10s voluntary minimum on urgent bounds (2s, one miss),
so a socket that died while the process was suspended is admitted in ~2s
instead of ~8s. Focus and network nudges keep the old minimum and bounds.
Relay sessions also gain a 25s idle sweep, gated on foreground so a
backgrounded app spends no probes.

Recovery is no longer blocked by the direct return probe. The probe's 12s
dial is a pure observation on its own socket, so it takes the supervisor's
operation mutex only for the cutover; a relay recovery landing during a
foreground return now starts immediately instead of waiting the budget out.
Requests that do land during the cutover are queued in a new
RelayRecoveryIntentQueue and replayed on release — an owning forced
replacement keeps its intent, everything else replays as a plain recovery.

Tests updated deliberately, for the new ordering:
- 'sends no periodic traffic while an authenticated relay is idle' asserted
  the absence of any relay idle probe, which is exactly the gap D3 closes.
  Replaced by a sweep test plus a backgrounded no-probe test.
- 'rate-limits foreground sequences without suppressing a retry' asserted
  that app-resume was suppressed inside the 10s minimum. An app resume is
  now the one nudge that must never be rate-limited.
- the session helpers waited for the confirm answer before `connected`;
  they now authenticate, read both concurrent frames, and settle them.

* fix(mobile): book backoff when a relay resume confirm fails after the cutover

Review round 1 on 352bfd2300.

P1: publishing `connected` at E2EE authentication made `migrateTo` resolve
before the resume confirm answered, so a confirm that failed afterwards —
a `relayHostId` mismatch from a rehomed desktop is the live case — was still
reported as an `established` dial. registerFailure was skipped, no cooldown
was booked, recordMigration()/setActiveSession() ran for a dying session, and
the queued-recovery replay redialled immediately: a tight loop with a
connected→disconnected blip per pass. The establisher now awaits
whenResumeConfirmed() after the cutover and, if the session is no longer
connected, reports a failed dial (or an aborted one when direct won or the
supervisor went inactive) exactly as a rejected migrateTo used to. The UI
still connects early; only the supervisor's bookkeeping waits.

The state check, rather than getFailure(), is the oracle: a live session can
carry a latched failure without having failed yet, and "is this session still
alive once the confirm settled" is precisely the question migrateTo used to
answer.

P2: the resume probe profile goes to two 2s misses instead of one. The first
frame after a resume rides a cold radio and a possibly distant cell, so one
slow answer is not proof of a dead link; the verdict still lands at 4s rather
than the previous 8s.

Nits: the direct probe's two early returns no longer close the candidate the
finally also closes (the second shape pre-existed); RelayRecoveryIntentQueue
is cleared in the supervisor's stop().

Mutex-hold note: persistResumeConfirmation, and now the establisher's own
await, are bounded by the confirm's request timeout. That would have been the
session's 30s default, so the confirm is pinned to RELAY_CONFIRM_TIMEOUT_MS
(12s) — the same bound migrateTo's waitForAuthenticated applied before.

Test: a supervisor-level case where every dial authenticates then fails the
confirm must book 250/500/1000ms backoff with no immediate redial, and must
never record a migration. It fails on the pre-fix establisher.

* fix(mobile): close three relay probe and liveness gaps from review

Review findings on this PR, fixed here so they ride along with the rest.

Direct return probe: schedule() guarded only the pending timer, so a caller
asking for an immediate probe while a dial was in flight started a second one
that overwrote activeProbe. stop() then reached only the newest socket and left
the earlier dial running out its 12s budget. Releasing the operation mutex for
the dial removed the only thing that had been serializing probes, and the
background bounce hits it directly: background() cancels the timer but leaves an
in-flight dial alone, and the matching foreground return asks for a probe at
once. The in-flight probe now owns the next slot and re-arms on the soonest
delay any caller asked for, so an urgent request is deferred rather than dropped
on the 15s floor.

Liveness watchdog: both retry paths in handleProbeTimeout, the tolerated-miss
one and the unfair-window one, retried without rechecking shouldIdleProbe. An
idle-sweep probe that started in the foreground could therefore keep spending
probes after the app backgrounded and terminate a healthy relay on misses that
were really iOS suspending the socket, which is the exact reading the foreground
gate exists to prevent. Probes now carry their origin, and an idle-sweep probe
that times out while backgrounded clears its state and re-arms the sweep with no
misses carried forward. Caller probes still reach a verdict.

Relay RPC session: whenResumeConfirmed() handed a pre-authentication caller an
already-resolved promise, so the documented contract only held after
authentication. No caller can reach that window today, since publishAuthenticated
assigns the promise before publishing 'connected' and both readers run after
migrateTo resolves, but the type comment promised more than the code delivered.
The deferred now exists from construction and settles on the confirm, on fail(),
and on close(), which are the only ways the session can end. Both endings had to
settle it and already shared nearly all of their teardown, so they are unified
behind one terminate().

* fix(mobile): give a resume probe its own miss budget

A resume probe supersedes an ordinary probe already in flight, but startProbe
carried the ordinary profile's missedProbes across the switch. Relay uses 2
misses for both profiles, so one earlier 4s miss plus a single slow 2s answer
terminated the session -- consuming the tolerated cold-radio answer the urgent
profile exists to provide. Switching profile now resets the count.
2026-09-07 13:12:24 -04:00
Jinwoo Hong 33af0af4ea fix(relay): stop rejecting the near region on a cold first probe (#19233)
* fix(relay): stop rejecting the near region on a cold first probe

The region probe counted the process's first /health request, which pays TCP
and TLS setup, as a latency sample. The resulting spread rejected the near
region on essentially every cold run, leaving the far region as the sole
survivor and pinning US desktops to Asia cells for 24 hours.

Discard a warm-up probe per origin, compare regions by minimum latency, and
keep the spread check only for a genuinely flapping path. A region now wins
only against a measured competitor; a rejected or unmeasurable peer sends no
hint, which is remembered for an hour so a reconnect does not re-probe. An
origin that fails its warm-up is dropped before the sampling rounds, so an
unreachable region costs one probe timeout instead of four.

After a control socket registers, probe the cell we landed on once per
process, and delete the cache only when it names a region other than the best
measured one and that cell is more than 3x slower -- a far cell under a
correct cache is the director declining the hint, and re-measuring would
return the same answer.

* test(relay): audit the region probe's global fetch call site
2026-09-07 13:11:04 -04:00
Brennan BensonandMerge Sim a87a19c996 fix(terminal): remount a pane left unbound by a spawn that returned no PTY id (#19223)
* fix(terminal): remount a pane left unbound by a spawn that returned no PTY id

A restored-PTY reattach that resolves without a PTY id leaves the pane
mounted with no transport binding, so registerData never runs. Main keeps
pushing pty:data for the id; the dispatcher finds no handler and parks the
bytes in the pre-handler buffer, which claims no delivery credit and so ACKs
them anyway — main's flow control reads healthy while the pane shows its last
frame forever. The visibility reconciler skips unbound panes, so nothing
rebinds one until the user remounts the tab.

Every startFreshColdRestoreAgentResume call site is floating (no await, no
catch) and startFreshSpawn resolves null rather than rejecting, so no caller
could see the failure. Settle it at the completion hook they all funnel
through, whose guards already mean "no pty, pane alive, still unbound, nobody
else spawning" — it settled the direct-SSH lease there and did nothing for
local panes. Route those to the existing remount seam instead; the SSH retry
ledger keeps ownership so the two never race.

Observed in the field on three concurrent panes, each parked just past the
64KB pre-handler warn threshold.

* test: drop a mock-only assertion that failed typecheck

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 09:41:29 -07:00
Brennan BensonandMerge Sim da4da8e60a fix(agent-status): stop a stale self-authored agent title from faking a pending question (#19237)
* fix(agent-status): stop a stale self-authored agent title from faking a pending question

A workspace card could show the amber "agent is asking you something" icon while
every pane sat idle and its only agent row read `done`.

Orca injects its own `<Agent> - action required` OSC title when a hook reports
blocked/waiting, then classifies that same title back as evidence. Two gaps let
that one-shot string outlive the state it described:

- The pane-id sets that suppress the title heuristic were built only from FRESH
  rows, so once a row aged past AGENT_STATUS_STALE_AFTER_MS the pane stopped
  suppressing its own title and `permission` — which outranks `done` — decided
  the indicator. Pane identity is not a liveness fact, so it is now tracked
  separately and never expires. Stale rows suppress `permission` only; a working
  spinner re-renders, so its stale-row fallback is preserved.

- The hook-driven tab-title write compared the resolved title against the pane's
  layout slot (`titlesByLeafId`, which only a mounted pane updates) while writing
  `tab.title`. Once those slots diverged, `done` resolved to a title equal to the
  pane slot, the no-op guard skipped the write, and the tab kept the stale label.
  The guard now compares against the slot it actually overwrites.

All three status surfaces read the same suppression inputs, so all three showed
it: the workspace card, the terminal tab glyph, and the cmd-J palette dot.

Tests: each fix has a regression test that fails without it (the sidebar, tab-bar
and palette tests all go red from a single ablation of the stale-set lookup).

* fix(agent-status): preserve native permissions and cover palette fallbacks

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 09:40:32 -07:00
Brennan BensonandMerge Sim 0252fe5c36 feat(native-chat): show Codex subagent activity instead of opcode rows (#18773)
* feat(native-chat): show Codex subagent activity instead of opcode rows

Codex spawns subagents and reports their lifecycle, but Orca rendered only
gray `codex · item:subAgentActivity` opcode rows. Build the real display: one
summary row per spawn group with a live working count and token usage.

State is accumulated from `subAgentActivity.kind` alone. A live probe against
app-server 0.152.1 showed `agentsStates` arrives empty even in a real subagent
run, and that every activity item is delivered twice (item/started and
item/completed), so every transition is idempotent and terminal states latch.

Children never receive `thread/started`, so there is no nickname, role, or
depth to read; the row labels from the trailing segment of `agentPath`.

Two sweeps keep a row from claiming work forever: the parent turn's terminal
event settles still-running children, and session start marks a pre-restart
roster unverifiable rather than exited, since Codex resume replays no
non-message items and no event can ever settle them.

The roster rides a new NativeChatBlock variant paired with a plain-text twin.
A journal item kind could not be used: that union is closed, and an unknown
kind parses as malformed, which is the corrupt-journal class that can hide the
chat tab. Block types are explicitly admissible when unknown, so an older
client drops the block and renders the sentence.

MessageRow moves out of NativeChatMessageList to keep both files under the
max-lines budget without a disable.

* feat(native-chat): give the subagent summary row its bot glyph

The row led with a glyph that swapped on state — a check once every child
completed, a group icon otherwise — so a group appeared to change identity
the moment it settled. Per the approved mock, the glyph names the category
and never moves: state is carried by the status dot and the tone of the
words beside it.

Use lucide `bot`, the same glyph the individual `subAgentActivity` rows take
in the eight-category vocabulary, so the summary reads as their parent. Slot
and glyph are the mock's 16px/14px, muted by default, and the svg is
`aria-hidden` — the headline is what a screen reader announces, so the icon
never stands alone.

* fix(native-chat): correct the Codex subagent roster's build, journal write, and failure reporting

* Restore the exhaustive block handling that adding `subagent-group` to
  `NativeChatBlock` broke. `formatWorkerTranscriptMessage` and `boundBlock`
  both fell through to `image-ref` field access, so `tsc -p` failed for the
  CLI and node projects and `build:cli` could not emit. Both now guard on
  `image-ref` explicitly and give the roster block its own branch.

* Stop the roster's publish from evicting its own append. The sink queue
  coalesces by `coalescingKey` alone with no op-kind check, so passing the
  append's key to `tryPublish` spliced the queued append out and the row
  never reached the journal — permanently, since `lastSerialized` was
  already set. `tryPublish()` now takes no argument, matching every other
  call site. The regression test's fake sink honours the key, which the
  previous fake did not.

* Keep `collabAgentToolCall` substantive. Only the MultiAgentV2 path emits
  `subAgentActivity`, so a V1 turn has no roster row; suppressing its collab
  tool calls too would have left a V1 fan-out showing nothing at all.

* Surface a settled failure while siblings still work. The summary now
  reports the worst adverse outcome independently of the group verdict, so
  the row shows `3 working +1 failed` with a failed-coloured dot instead of
  a neutral pulsing dot. The plain-text twin names it too.

* Treat `/morpheus` as a child. Only `/root` is the turn itself; the old
  segment-count test silently dropped a valid single-segment agent.

* Refresh token-usage recency on update so an active thread is not evicted
  as the oldest entry, and scope the `agentsStates` comment to the V2 path.

* fix(native-chat): stop the subagent roster announcing a new duration every second

The roster row is an `aria-live="polite"` region and it contains the elapsed
clock, which reticks once a second for as long as the fan-out runs. A screen
reader therefore reads out a fresh duration every second, burying the state
changes the live region exists to report — the headline, the verdict, and the
`+1 failed` alert.

No other live region in the transcript does this. `NativeChatToolRun`'s live
button holds only the active tool label, and in `NativeChatWorkingStatus` the
variant that shows a duration is precisely the one with no `aria-live`.

Hide the clock from the accessibility tree only while it is moving. Once the
group settles the duration is fixed, so it stays readable and costs no
announcements.

* fix(native-chat): retry a refused roster publish, and stop two wrong readings

Four defects from a third review pass over the Codex subagent roster.

`write()` set `lastSerialized` before the append and rolled it back only when
the APPEND was refused. A refused PUBLISH left it set, so an identical replay
short-circuited and the revision was never published again. The repo's own
pattern is the opposite: `codex-structured-item-streams.ts` advances
`checkpointLengths` only once the append AND the publish are both accepted.
Roll back on either half.

That alone did not cover the sweep, which is the LAST event a group ever gets:
its `changed` guard skips the write on a retry because every child has already
latched, stranding the settled roster's final revision. Write when the previous
attempt was refused part-way, too.

`formatWorkerTranscriptMessage` read `block.agents` as its exhaustive fallback.
The journal schema deliberately admits block types this build does not know and
`client.call` casts the RPC result instead of validating it, so a newer remote
host's block reached that line and threw `agents is not iterable`, taking down
the whole `worker read`. It printed a harmless `[image omitted]` before. Match
`subagent-group` explicitly and degrade the unknown case.

The elapsed clock measured to `now` whenever no child carried a terminal
timestamp. That is exactly the roster restored from the journal after the host
died: the reconciler latches `unverifiable` without a `settledAt`, so a child
that ran four seconds reported the time since the crash as its run length, on a
row that is not even counting. Show no duration when none is known.

Also restores package.json to origin/main: the merge had deleted one of main's
two duplicate `bench:terminal-partial-escape-tail` keys. Behaviour-preserving
(JSON is last-wins and the deleted line was the dead one), but unrelated to this
PR and better left to its own change. No gate rejects duplicate JSON keys.

The new refusal tests also cover the append-side rollback, which had none.

* fix(native-chat): stop the subagent roster vanishing from every settled turn

`NativeChatToolRun` bailed out for a completed turn whose activity disclosure
is collapsed before it reached the branch that draws a roster-only run. That
guard exists to push TOOL activity behind the turn-status disclosure, and it
fires on exactly the shape a spawn group has: a roster message carries no tool
blocks, so `selectActiveToolCall` returns null and `isSettled` is true, while
the list passes `expandOverride={expandedTurnIds.has(turnKey)}` — false until
the reader opens that turn — and `activeTurnIsWorking={false}`.

That is the default state of every finished turn in the transcript, so the one
compact row this feature exists to leave behind ("Ran 3 subagents") disappeared
the moment its turn ended. Worse, `MessageRow` counts a spawn group as
renderable specifically so the row survives, then rendered a wrapper around a
component that returned null — the empty ghost bubble its own guard is written
to prevent.

Order the roster branch before the disclosure guard. A roster has no tool
activity to hide, and the guard's reasoning ("a failed child command looked
like the whole response was still running") does not reach it. Runs that do
carry tool blocks still fall through to the guard unchanged, and in practice a
roster never shares a message with them: it is its own `role: 'system'` journal
row and `isToolOnlyMessage` is false for it, so `foldToolMessages` never merges
tool blocks into it.

Also drop childless groups when building the rows, so `subagentRows.length`
stays an honest test of "something will draw" — the roster-only branch returns
a margin-bearing wrapper on the strength of it, and a group with no children
renders null.

Both tests fail with their fix reverted; the existing NativeChatToolRun suite
still passes, so the completed-turn disclosure behaviour is unchanged.

* test(native-chat): cover the subagent roster at the message-list level

Every defect this feature has shipped so far lived in the assembly between
rows, and the row-level suites kept passing through all of them. Loop 4's
regression — a settled roster swallowed by the completed-turn disclosure —
was found by reading the code, not by a test, and an independent visual-proof
run observed the same symptom in the real UI and routed around it rather than
reporting it. `NativeChatToolRun` rendered alone is handed `expandOverride`
and `activeTurnIsWorking` by the test author, so it agrees with whatever the
caller was assumed to pass.

Drive the real component instead. The roster is its own `role: 'system'`
journal row carrying the producer's two blocks (structured + plain-text twin),
so what reaches the DOM depends on `foldToolMessages`, the turn-key mapping
and the disclosure state `NativeChatMessageList` owns — none of which a row
test exercises.

Three cases, on one assembled transcript that holds tool calls AND a roster:
  - a settled turn with activity collapsed, the resting state of the whole
    transcript, still shows the row (fails with loop 4's reorder reverted);
  - tool activity stays behind that disclosure and appears only on expand,
    and expanding draws no second roster (fails with the guard removed);
  - a working turn reads as a live spawn.

The first also pins that the plain-text twin is dropped rather than printed
beside the row it stands in for.

Timestamps are explicit and ascending: the list re-sorts by (timestamp, id),
so rows sharing a millisecond tie-break alphabetically and the user turn can
sort last, stranding the roster outside its own turn and reconciling live
children to `unverifiable`.

No production code changed.

* fix(native-chat): make "counts as renderable" and "actually draws" agree for a spawn group

`MessageRow` counts any `subagent-group` block as renderable, but
`NativeChatSubagentRun` renders null for a childless roster. A group with
`agents: []` therefore mounted a row that drew nothing — an empty div that still
costs the transcript one `gap-5` slot. The Codex producer never writes one (every
`write()` call site operates on a group that already holds an entry), but the
block schema admits `agents: []` with no `.min(1)`, and the wire is where such a
shape would arrive.

Narrow `subagentGroupBlocks` — whose only production caller IS that renderable
check — to the groups that will draw, behind a named `isRenderableSubagentGroup`
that `NativeChatToolRun` now shares in place of its own copy of the predicate, so
the two guards cannot drift apart again. A childless group carrying its
plain-text twin now prints the twin, which is what the twin is for; a bare one
skips the row entirely.

Also correct four comments that had stopped describing the code:
  - the roster header called `agentsStates` "always empty", contradicting the
    probe note in `codex-subagent-activity.ts` — it is empty on the MultiAgentV2
    path that emits these items, and the V1 path does populate it;
  - `tokensByThread` was documented "retained UNCONDITIONALLY" while
    `handleTokenUsage` LRU-caps it 65 lines below;
  - the sweep is not "the LAST event a group ever gets": neither `settleTurn` nor
    `settleSession` removes the group, so a later `thread/tokenUsage/updated`
    naming a swept child still writes it. The retry condition is right; only its
    stated reason was wrong;
  - the `subAgentActivity` classification is not reached "for every event — and
    every one of them arrives twice". `handleSubagentItem` intercepts those items
    before `items.handle`, so the live path never consults the catalog;
    `restoreThread` replays them straight through, and is the real consumer.

Comment-only apart from the childless-group guard.

* fix(cli): stop `worker read` printing the subagent roster sentence twice

The producer ALWAYS writes a roster block beside a plain-text twin carrying the
same sentence, for clients that cannot draw the block. The renderer honours that
contract from one side — it draws the block and drops the twin. The CLI honoured
neither side: it printed the twin as prose AND rendered the block as
`[subagents] <same sentence>`, so a real roster message read

    [system] Ran 2 subagents (1 failed)
    [subagents] Ran 2 subagents (1 failed)

Take the mirror of the renderer's rule, which is the cleaner half for a text
client: the twin IS the sentence, so print it and drop the block it stands in
for. A block that arrives WITHOUT its twin — a shape the wire admits and no
producer writes — still stands in for itself, because dropping it
unconditionally would lose the roster entirely. Either way the sentence prints
exactly once, off the same `subagentGroupFallbackText` helper both sides use.

Unreachable through `readWorkerTranscript` today, whose provider rollout decoder
never emits a `subagent-group` block — but the formatter is the CLI's contract
for any transcript source, and the shape is already producible.

The test pinned a TWIN-LESS group, a body `codexSubagentGroupBody` never writes:
it asserted the exact double-print this fixes was correct output, and would have
blessed either behaviour. Rebuild the fixture as the producer's real two-block
row, with the sentence taken from the shared helper rather than hardcoded so it
cannot drift, and assert the sentence appears exactly once. The twin-less shape
keeps a test of its own, labelled as the wire-only fallback it is.

Also record why `settleTurn` keys on the RAW `turnId` while `groupFor` remaps
off-primary activity onto the primary's active turn. The asymmetry is
load-bearing, not an oversight: were `settleTurn` to remap, a child thread
ending its own turn would sweep the parent group and settle every still-working
sibling to `unverifiable`. The lookup missing is the intended no-op.

* fix(native-chat): add the subagent roster's localization keys and narrow its twin filters

The roster row called 16 `components.native-chat.subagents.*` keys that were
never added to the catalog, failing the localization gate. Synced en.json; the
English strings are the component's own inline fallbacks, so nothing renders
differently.

Also tightens the twin/block handoff on both readers. The renderer dropped
every text block once a roster was present, which is safe only because Codex
writes a roster as its own message — the block is provider-agnostic, so a lane
folding prose in beside one would have lost it on desktop while mobile kept it.
And both readers decided "the twin is already printing" by recomputing the
sentence and comparing bytes, which a roster from a newer build never matches:
its unknown state normalizes to `unverifiable` here, so the CLI printed the
roster twice with two different verdicts. Both now recognize a twin by shape.

* test(native-chat): pin the roster twin recognizer against prose

Both readers use it to decide the twin is already printing, so a false positive
eats a message's real prose and a false negative prints the roster twice.

* docs(codex): restore the roster's evictionated trigger to its KNOWN LIMITATION

The previous rewrite dropped both triggers the old comment named and kept only
the restart one, but eviction is the reachable half: `groupFor` caps `groups` at
MAX_CODEX_SUBAGENT_GROUPS and drops the oldest-INSERTED entry (it returns an
existing group without re-inserting, so this is not LRU), which can evict a
still-live group in-process. The row identity is keyed on the group id alone, so
the next activity item rebuilds that row from one child — the same N-to-1
rewrite, with no restart, and with the sweep skipped so the children never latch
`unverifiable`. Also softens "every real turn id is freshly minted" to the
provider assumption it is: turn ids are read verbatim off provider frames and
nothing in this repo mints or asserts them.

* docs(codex): justify the subagent wire notes from the live probe alone

The roster and disposition comments explained themselves in terms of a
provider-internal path taxonomy rather than anything this repo can observe.
Restate them from the evidence Orca actually has: the live app-server probe
saw `agentsStates` arrive empty, so nothing reads it; and `collabAgentToolCall`
stays substantive because nothing guarantees a session reports subagent work as
`subAgentActivity` at all — one that only emits the collab tool call gets no
roster row, and suppressing that too would leave its fan-out blank.

Same behaviour, same tests; comments and one test name only.

* fix(native-chat): stop the roster's durable twin from claiming live subagents

The spawn-group row is written once and revised in place, but the row itself
is durable and replayed on every reconnect. Its plain-text twin — the only
thing a client that cannot draw the block ever sees — froze a live count into
that row: `Kicked off 4 subagents — 2 working`. The desktop renderer never
shows it, and reconciles the block's `working` to `unverifiable` outside the
live turn. A text-only reader does neither. When the writing process dies
mid-flight the turn-end sweep never runs, so the sentence keeps asserting two
running children forever, with nothing left that could re-check them. That is
the collapse `docs/reference/ssh-execution-boundary.md` forbids: loss of
contact reported as a live state.

Fix it at the source rather than per client: the durable sentence now states
only what survives its process — that the group was spawned, plus whatever
outcome had latched. `Kicked off` vs `Ran` stays, because it reports whether an
outcome was recorded at write time; saying `Ran` while children were in flight
would assert they exited, the same error inverted. The adverse count stays so a
failing fan-out still reads as failing. Reconciliation stays in the renderer,
where the block still needs it.

The twin recognizer keeps matching the legacy `— N working` shape: journals
already hold those sentences and their rows replay forever, so dropping the
branch would print every one of them twice, once as the block and once as prose
the reader meant to drop.

Also align the two functions that read `agentPath`. The root check compared the
raw string while the label normalized separators, so `/root/` was both the turn
itself and a child of it — a phantom row labelled `root` inflating the group by
one. Compare normalized segments instead, keeping `/morpheus` a child. And a
trailing segment with nothing visible in it survives the empty-segment filter
and would draw a nameless row, so it now reads as no label and falls back to the
placeholder.

* fix(codex): key the subagent label collision ordinal on what the row draws

`codexSubagentLabel` tested the trailing segment trimmed but returned it
untrimmed, and `claimLabel` keys its collision ordinal on that string. Two
children at `/root/read` and `/root/ read ` therefore both drew as `read`
with no ordinal — the one thing the ordinal exists to prevent. Return the
trimmed segment so labels that render identically collide.

Also correct the legacy-clause note on the twin recognizer. It claimed shipped
journals hold the old `— N working` sentence; the feature is unreleased, so the
only journals holding one are dev worktrees of this branch. The branch still
earns its place — those rows replay too, and it adds no false-positive surface
the bare shape does not already carry — but the stated reason was wrong.

* test(native-chat): retire the subagent-visibility guards now the roster renders

Two tests from the sibling item-coverage PR asserted that subagent items stay
on the generic gray row, explicitly gated on "until a real renderer exists".
This branch is that renderer, so both guards fire on merge — the handoff they
were written to mark rather than a regression.

They now pin the other side of it: subAgentActivity is suppressed because the
spawn-group roster renders it, and collabAgentToolCall deliberately stays
visible, since nothing guarantees a session reports subagent work as
subAgentActivity at all.

Git merged both files without conflict; only running the suite surfaced this.

* fix(native-chat): let a subagent swept at turn end still report what it did

The turn-end sweep marks still-running children `unverifiable`, and the
producer latched on any state that was not `working` — so `unverifiable`
latched too. A subagent that outlived its turn then reported `completed`, the
latch refused it, and a child that finished successfully read as one we never
saw finish, permanently.

One predicate was doing two jobs. `isTerminalSubagentState` is right for
counting — `unverifiable` is not working — and wrong for latching, because
`unverifiable` records that we stopped being able to see the child, not what
it did. Split them: a child's own verdict latches, the sweep's guess does not.

The reverse stays refused. Nothing returns to `working` once we have given up
on it, so a straggler progress tick cannot re-light a settled row.

Neither the latch nor the sweep was wrong alone, and both were tested; the
defect lived only in their interaction, and only when a subagent outlives its
turn — which the probe that drove this design never produced, because the
parent it captured waited on its child.

* fix: drop the @pnpm/exe lockfile drift a merge staged

`git add -A` swept up the pnpm-lock.yaml mutation that every pnpm invocation
leaves in this repo. Nineteen lines, thirteen of them @pnpm/exe, and it fails
sixteen unrelated CI checks — native smoke, typecheck, packaging, xterm patch
sync — none of which name the lockfile.

* fix(native-chat): restore the item fall-through an inline dropped

Inlining the subagent routing helper lost its null check: the roster returning
null means it did not claim the item, and the translator must keep looking.
Returning unconditionally once any thread item parsed swallowed every ordinary
item — twelve settlement tests, none of them about subagents.

* fix(orchestration): rebind the subagent block arm to the renamed bound state

Main renamed clipMetadata's second parameter from a warnings set to a
TranscriptBoundState. The subagent-group arm still passed `warnings`, and git
merged both sides without a conflict because the lines never overlapped — the
rename and the new arm are in different hunks. Typecheck was the only thing
that could catch it, and did.

* fix(codex): publish the turn tail for a subagent item the roster claims

Main's #19055 added a `subAgentActivity` arm to the provider activity table,
which is reached only through `publishActivity`. The roster's admission returned
above that call, so every `subAgentActivity` item bypassed it and a fan-out that
reports nothing else left the turn tail stuck on the previous frame's text.

`publishActivity` already no-ops on a refused admission and on a non-primary
thread, so routing the roster's admission through it is safe.

Also corrects a docstring the frames extraction copy-pasted onto
`settleOversizedNotification`.

* fix(native-chat): bound the subagent roster on every boundary that carries it

The spawn-group arm was the one collection in the worker-transcript payload with
no cap, and the one block type mobile's `sanitizeBlock` forwarded verbatim. The
producer's `MAX_CODEX_SUBAGENTS_PER_GROUP` does not reach either boundary: the
journal schema declares no maximum on `agents`, and a remote host may run a build
with a different cap. Both transports now cap the roster and bound `id`, `label`
and the open `state` string; `label` and `id` also take the standard inline bound
on the journal write path, where every other provider string already does.

A token count is now persisted onto its entry at write time. `write` rebuilt
`tokens` from the LRU-capped thread map on every write, so an eviction silently
retracted a count the durable row had already shown.

Adds the first coverage of the three roster caps, including the group eviction
that rewrites a row from N children down to one.

* fix(native-chat): keep the roster drawn beside tool calls and its clock honest

The roster-only escape is keyed on `blocks.length === 0`, so a spawn group
sharing its message with tool-call blocks fell through to the settled-turn guard,
which returned bare null and took the roster with it — the exact regression the
escape above was written to avoid, after the message row had already counted the
group as renderable. Unreachable for Codex today; the block type is deliberately
provider-agnostic, so it is live for the Claude lane.

The elapsed clock also froze at a sibling's timestamp on a partial sweep: in a
group where one child completed and another is unaccounted for, the ended turn
left `working === 0` with the completed child's `settledAt`, and the row showed
that child's duration as the group's run length. No clock is drawn while any
child is `unverifiable` with no terminal timestamp.

* perf(native-chat): bound the roster's provider strings without digesting them

`boundInlineText` computes a sha256 and a Buffer BEFORE it checks the length,
so the roster paid two digests per child on every write even when nothing was
truncated — and `write()` runs on every claimed activity item (each delivered
twice) and again from `handleTokenUsage`, which streams. A same-process A/B over
a 64-child group: 76.5 us/write before, 2.0 us/write after (plain, unbounded row
is 1.2 us).

The cap changes with the mechanism. 16 KB is the tool-output bound; both readers
of this row already clip the same fields to 512, so the producer was admitting
~2 MB per durable roster row for consumers to throw ~97% of away. One
`MAX_SUBAGENT_FIELD_CHARS` now serves the producer and both readers, and the
marker is an ellipsis rather than the tool-output truncation sentence — `id` is
the roster key and the renderer's React key.

Also raises the orchestration arm's per-group bound from 20 to the producer's
64, matching the mobile arm: a 21-64 child group is routinely producible here,
so that arm clipped children and warned while its sibling clipped none. The
slice and warning stay as the transport's own defence against a remote host with
a larger cap.

* fix(orchestration): suppress one roster block per twin, not all of them

`hasTwin` was a single boolean over the whole message, so a message carrying two
`subagent-group` blocks and one plain-text twin printed one sentence and dropped
the second roster with no marker. Count the twins and claim one per group
instead. Not reachable from this branch's producer, which writes one group per
journal item, but the surrounding reasoning is explicitly about wire shapes the
producer never writes and this is the adjacent one it missed.

* fix(native-chat): loop-3 fixes to the Codex subagent worklog

Five defects loop 2's own fixes introduced.

Twin claiming was order-blind: the count-based claim silenced whichever
roster block came first, so a lone twin belonging to a LATER group erased
an earlier group's roster and printed the later sentence twice. Exact-text
claims are now settled for every group before any leftover twin is claimed
by position; the positional fallback stays for a newer build's frozen twin,
which can never equal a recomputed sentence.

`boundSubagentField` sliced UTF-16 units and could leave a lone high
surrogate in a durable row, and the clip removed exactly the tail that told
two children apart — `id` is the renderer's React key and `claimLabel`
writes its repeat ordinal at the end. It now backs off a split pair and
reserves the child index inside the bound, so both readers' re-clip cannot
cut the disambiguator off again.

`MAX_SUBAGENT_FIELD_CHARS`'s doc claimed a `groupId` bound the producer
never applies; the doc now says so and why. The worker-transcript metadata
cap is a separate literal again: it governs message ids, turn ids, tool-call
names and image urls, so a roster-motivated change must not move it.

* fix(native-chat): never infer a lost subagent from a turn boundary

QA drove a real Codex session with three live `spawn_agent` children and sent
a mid-turn correction. The roster row immediately read "Ran 3 subagents /
3 unverifiable" with no clock, while all three were still running — they
reported `completed` 57-87s after that turn ended.

Both sites rested on the same false premise: that a turn ending means no
event will ever settle a child. Children outlive their turn and keep
reporting into the same group.

- Renderer: drop `reconcileSubagentRoster`. Nothing plumbed to the component
  distinguishes a row written by a dead host from a turn that merely ended —
  journal render items carry no epoch, and a new epoch deletes the rows of the
  one it supersedes — so the row now draws the state the journal recorded.
  Under-claiming beats over-claiming.
- Main: stop sweeping on `turn/completed`. That sweep wrote `unverifiable`
  into the DURABLE journal, which mobile reads with no reconciliation.
  `turn/completed` is Codex's only turn-end notification, so an abort cannot
  be told apart from a clean finish; the safe default is not to sweep.

`settleSession` — the provider actually being gone — is unchanged and is now
the only sweep. `unverifiable` stays non-latching so a late verdict still lands.

* test(native-chat): pin the roster at the seam the QA defect came from

The mid-turn correction opens a new turn, so the fan-out's row stops being
the current turn and the list hands the roster `activeTurnIsWorking={false}`.
Asserted through the list, not the component, because that prop is what
carried the wrong claim.

* fix(native-chat): settle a roster the dying host never got to sweep

`settleSession` only fires when the provider goes away while this process is
alive. If the host itself dies, nothing sweeps and nothing reconciles on
restore, so a `subagent-group` row persisted as `working` claimed live children
forever — the mirror of the defect the previous commit fixed, and the same
`ssh-execution-boundary.md` violation in the other direction.

Reconciled host-side, at journal open, not in the renderer: mobile shows only
the durable text twin and reconciles nothing, so a renderer-only fix would
leave it claiming live children indefinitely. Opening the journal is also the
one moment a host can honestly say the previous writer is gone.

- `staleSubagentRosterRevisions` rewrites every child still reading `working`
  to `unverifiable` and regenerates the twin from the same summary, so the
  block and the sentence cannot disagree.
- No terminal timestamp: the child stopped being observable at an unknown
  moment, and stamping the reopen would report the downtime as its run length.
- Revises in place under the parsed identity, so a reopen upserts the row
  rather than appending a duplicate, and a second reopen writes nothing.
- Skipped on a corrupt load: that journal is still owed a rebuild from provider
  history, and content past the repair's free sequence retires the demand.

Reconciles journal ROWS, not roster state — the producer's in-process group map
is untouched, so the roster's known seeding limitation is unchanged, as is
`canReplaceSubagentState`: `unverifiable` still does not latch.

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 09:38:16 -07:00
Brennan BensonandMerge Sim bffdad9f05 fix(native-chat): make structured chat tabs renameable (#19153)
* fix(native-chat): let a structured chat tab be renamed

Renaming a native chat tab accepted the text and silently did nothing:
setTabCustomTitle only scanned terminal tabs and only bridged to unified
tabs whose contentType was 'terminal', so the agent-session tab it was
keyed to never matched. Any label that did land was then re-nulled by the
next host snapshot, which preserved color/createdAt/isPinned but not
customLabel.

Also routes both placeholder sites through one helper so a Claude chat
stops falling back to 'Codex Chat'.

* test(native-chat): cover structured chat tab rename and label fallback

* chore: drop the local @pnpm/exe lockfile artifact

Swept in accidentally; running pnpm here adds @pnpm/exe to the root
lockfile, which fails CI's frozen-lockfile guard.

* fix(native-chat): reach the rename shortcut and tab color too

Review found the first fix covered only the context-menu path. The
tab.rename shortcut gated on activeTabType === 'terminal', so on a
structured chat tab it stayed the silent no-op this branch set out to
fix. setTabColor carried the identical terminal-only lookup one function
below the one that was fixed.

Both lookups now share one resolver instead of two copies.

* fix(native-chat): stop unknown agents reading as Codex, cover the terminal path

Review found the placeholder helper encoded "unknown means Codex": its
signature accepts null/undefined and Tab.agentSessionAgent is the open
AgentType, so the first caller passing a Tab would label gemini or grok
as "Codex Chat". Routed through the shared agent-name table instead.

Also adds the missing regression test that a terminal rename still
resolves through its entityId now that both rename and color share one
resolver, and a guard on a test that passed with the fix reverted.

* fix(native-chat): degrade instead of throwing on a null tab title

A stacked branch can publish title: null when a conversation name is
cleared. The wire type says string, so this consumer trusted it and
threw inside the store patch that applies the snapshot. Fall back to the
placeholder — the producer bug is fixed separately, but a consumer of
wire data should not crash on a contract violation.

* fix(native-chat): rename the focused structured tab, not a background terminal

* fix(native-chat): cycle terminals from the structured tab, not a stale terminal

---------

Co-authored-by: Merge Sim <sim@local>
2026-09-07 09:36:14 -07:00
6ae5418a89 Add localization for activity view and sidebar (#18589)
* i18n: add localization for activity view and sidebar

Wrap activity thread state labels, interrupted status, and sidebar
title in translate() calls. Add localization keys to all five locale
catalogs (en, es, ja, ko, zh) to enable translation support.

* i18n: refactor to static keys for activity and sidebar

Convert dynamic translation key construction to static literal keys, enabling proper i18n catalog registration. This ensures activity state labels and sidebar strings are bundled in the boot catalog with their complete translations.

* i18n: change permission state label to 'Needs attention'

- Rename state label for semantic clarity across all locales
- Remove strings now using static keys (per i18n refactor to static keys)

---------

Co-authored-by: m4air <m4air@m4airs-Air.localdomain>
Co-authored-by: m4air <m4air@Mac.localdomain>
2026-09-07 09:33:23 -07:00
Brennan BensonandMerge Sim bcb703fb4c test(ssh): isolate the MFA fixture from the developer's real ~/.ssh (#19300)
The multi-stage cases pass `resolved: null`, so `resolvePrivateKeys` falls
through to `findDefaultKeyFile`, which reads `~/.ssh/id_*` via `homedir()`.
On a machine with an encrypted default key ssh2 rejects with "Cannot parse
privateKey" before authentication is exercised, so two cases failed locally
while staying green on hosted CI, which has no key. Point home at the existing
fixture directory so default-key discovery stays in the test's control.

Co-authored-by: Merge Sim <sim@local>
2026-09-07 09:32:14 -07:00
a899f92402 feat(windows): enable structured Codex chat on native Windows (#18519)
* feat(native-chat): enable Windows structured sessions

* fix(codex): prove native Windows process identity

* style(codex): format Windows session seam

* fix Windows structured Codex admission

* fix(windows): reprobe missing process identity capability

* fix(windows): decide folder-workspace WSL routing before the click

Review found pathUsesWslUnc exported but unused, and the folder composer
hardcoding worktreeUsesWslPath:false. Together those meant a folder picked
under a \\wsl.localhost\ parent routed to structured chat, then got refused
by the host and fell back AFTER the click -- which defeats the lane's own
design goal that create cannot fail after the click.

The group's parentPath is in scope at submit and the workspace is created
under it, so the parent decides WSL-ness pre-click. Wires pathUsesWslUnc
there and adds tests for the helper, including the unhydrated-store case
that previously threw.

* fix(windows): collapse the gate derivation to one call, restoring max-lines

CI static analysis failed: launch-agent-in-new-tab.ts crossed the 300-line
oxlint ceiling. Adding a max-lines disable is forbidden, so the two gate
derivations collapse into one readWindowsStructuredGateInputs() call --
a store-backed site now adds one line and one import name instead of two.
Better shape anyway: one derivation entry point rather than two reads a
call site must remember to pair.

* fix(windows): engage the legacy fallback when the host THROWS a refusal

Review found a P1 this merge composes: neither parent could reach it. At the
lane head the only structured entry was launch-agent-in-new-tab (full
store-backed WSL check); on main all win32 was refused. The merge enables
win32 in creation flows that pass no projectRuntime, so a WSL folder
workspace, a WSL-configured repo, or a repair-required runtime now routes
structured -- and the host refuses correctly, but by THROWING rather than
returning {ok:false, refusal}.

Callers engage their legacy-terminal fallback on the refusal CLASS, so an
unmapped throw arrives as a generic RPC rejection: no fallback, empty
workspace, error toast, prompt stranded in the launch outbox. Pre-merge the
same action opened a legacy terminal agent.

Map the host's thrown definitive refusals onto the refusal class at the
launch boundary, so every creation flow -- present and future -- degrades to
the legacy terminal instead of stranding. Narrow predicate: unrelated
failures (ECONNRESET, empty message, non-Error) still propagate untouched.

Ablation-proven: removing the mapping reddens the fallback test.

* fix(windows): teach the mobile RPC double the status probe the lane added

CI's first-ever run on this lane caught a pre-existing lane defect. The lane
changed status.get to resolve through
runtime.getStatusAfterWindowsProcessStartTimeProbe(), but never taught the
mobile-surface runtime double about it, so status.get failed for mobile
clients with "not a function". The lane's own test list did not include this
file and the lane had zero CI, so nothing ever ran it.

The real runtime always implements the method; the double omitted it.

* chore: merge current main and regenerate the localization runtime catalog

CI static analysis failed on a stale en-runtime-required.json: main added
onboarding integration-capability keys, and the generated catalog is checked
against the PR MERGE result, not the branch alone -- so it read clean locally
while failing in CI. Merging current main (90780acb85) and regenerating.

Gates after the merge: pnpm tc 0, oxlint 0, changed-code quality 0/56,
7 gate/lane test files 69 tests green.

* fix: route structured launches by execution host platform

* fix: recover paired structured session mirror on host swap

* Revert "fix: recover paired structured session mirror on host swap"

This reverts commit 81bfca0007.

* Revert "fix: route structured launches by execution host platform"

This reverts commit 47abbd354a.

* fix(windows): refuse structured chat in a paired web client

Reverts the two review-loop commits (restoring a tree byte-identical to the
validated head) and closes the hole they were aiming at, without their cost.

A paired web client's `platform` describes the browser's machine, not the host
that will run the agent, so the Windows gate cannot be evaluated there. Before
this, a browser on macOS driving a Windows runtime read "not win32", skipped the
creation-time proof entirely and allowed structured chat — fail-OPEN, the
dangerous direction, bypassing the guarantee this lane is built on.

`isWebClient` is a required input like the other gate fields, so the compiler
enumerated all seven call sites. Refusal is synchronous and fail-closed: no
async round-trip, no null window, no cache to invalidate — unlike keying on an
asynchronously-fetched host platform, which would have made every desktop
launch wait on a round-trip to fix a paired-web-only hole.

Paired web therefore gets the legacy chat until the host publishes eligibility
itself; that is the proper fix and belongs in its own PR.

Ablation-proven: removing the guard reddens both refusal tests; the
desktop-unaffected test is a preservation check and passes either way.
Gates: tc 0, oxlint 0.

Known open: repos-onboarding-folder-startup.test.ts fails on this branch and
passes on plain main — under investigation, NOT caused by this commit.

* test(onboarding): mock the web-client check the store path now reaches

The web-client refusal added `isWebClientLocation()` to the launch-route
inputs, which this suite's store path reaches while adding the FIRST folder.
The suite stubs `window` as `{ api }` with no `location`, so the function
cleared its `typeof window === 'undefined'` guard and then threw on
`window.location.pathname`.

That threw inside addNonGitFolder's own catch, so folder-1 never activated;
folder-2 then returned early (a project already existed) before reaching the
call at all, leaving exactly one activation with no startup seed.

Test artifact, not a product defect: a real renderer always has
`window.location`, so the seeding path is intact for users. Mocking the module
is the convention 7 other suites already use, and keeps product code free of
defensive branches that only exist to satisfy a stub.

Ablation-proven: removing the mock reproduces the original failure exactly.

* fix(renderer): make the web-client check total over a partial window

isWebClientLocation() guarded `typeof window === 'undefined'` and then assumed
`window.location` existed. A window stubbed without a location cleared the
guard and threw on `.pathname`.

That matters because this branch put the call on the launch-routing path,
where the throw is swallowed by the caller's catch and silently becomes a
FAILED LAUNCH rather than a visible error. CI caught it as 9 failures in
launch-work-item-direct.test.ts.

I previously "fixed" this by mocking the module in the one suite I knew about.
That was whack-a-mole against an unbounded set, and it missed this one. The
defect is the partial-window assumption, so fix it there: the mock is removed
from the onboarding suite and both suites now pass on the hardening alone.

Ablation-proven: reverting to the unguarded form reddens 11 tests across the
new unit suite and launch-work-item-direct.

Gates: tc 0, oxlint 0, changed-code quality 0/58.

* Move Codex's Windows structured-chat eligibility onto the host createSupport probe

The renderer no longer decides Codex win32 eligibility: launchStructuredAgentSession
probes agentSession.createSupport for both providers, the host answers via
supportsCodexStructuredLocation (process start-time proof + WSL refusal), and the
create path re-checks live. Deletes the client-side windows gate module and its
routing inputs (windowsProcessStartTime, worktreeUsesWslPath, isWebClient, platform)
from six call sites. Splits killCodexAppServerProcessTree out of
codex-app-server-session to hold the max-lines ceiling without a disable.

* fix(ci): keep pnpm lockfile stable

* test(windows): align foreground snapshot flags

* Restore main's pane-snapshot flag contract

Main asks for CreationTime on both projections; this branch's hot-path
isolation went away with the async probe it served.

---------

Co-authored-by: Orca Worker <orca-worker@localhost>
Co-authored-by: Merge Sim <sim@local>
Co-authored-by: Merge Sim <merge@localhost>
2026-09-07 09:18:38 -07:00
Jinwoo Hong 8cd0abf76a test(relay): prove the capability header reaches acceptControl over a real upgrade (#19274)
The unit tests cover parseRelayHostCapabilities, the sendHelloAck gating, and the
header literal separately, but nothing joined them: a typo in the header name
read off the upgrade request passed the entire suite. This drives a real control
upgrade carrying the header, leaves an invite connection pending, and asserts the
rebound control's ack. Renaming the header the server reads fails it.
2026-09-07 07:39:38 -04:00
Neil 9d29e6878e fix(codex): distinguish personal and enterprise accounts sharing an email (#19279)
* fix(codex): distinguish same-email accounts in the switcher

* fix(codex): scope switcher disambiguation to the visible runtime group

Review follow-ups: wrap labels at word boundaries instead of mid-word,
disambiguate against the accounts a group actually renders, and tolerate a
missing email arriving from persisted settings or a remote summary.
2026-09-07 03:28:33 -07:00
Jinwoo Hong 1bf30670d4 fix(relay-ops): let the rehome trust probe approve the asia-east2 cells (#19275) 2026-09-07 05:48:19 -04:00
Jinwoo Hong 9c8f4c398c fix(relay): bound control RTT samples per ping and per flush window (#19268)
* fix(relay): bound control RTT samples per ping and per flush window

An authenticated host chose how many round-trip samples a cell recorded: every
pong carrying a recent plausible `t` was forwarded to the process-wide window,
which grew unbounded until the 30s flush copied and sorted it for percentiles.

Time a pong only when it echoes the `t` of the ping still outstanding on that
session, so a flood yields at most one sample per ping the cell actually sent.
A pong that lost the race to the next ping is dropped for timing but still
counts as proof of life for the silence watchdog. Bound the process-wide window
with a 1024-sample reservoir (Algorithm R) so the percentiles stay unbiased,
keep `controlRttSamplesDelta` meaning round trips observed, and publish
`controlRttSamplesDroppedDelta` for the ones the reservoir did not keep.

Replace the leak guard's blanket `"credential":` string rewrite with an exact,
path-scoped rename of the two schema keys that spell a policed word, and make
the guard case-insensitive now that nothing legitimate trips it.

Follow-up to #19232.

* test(relay): prove the RTT reservoir samples the whole window
2026-09-07 05:06:42 -04:00
Jinwoo Hong 91d7783f2b fix(relay): state pending-conn details to hosts that advertise the capability (cell side) (#19266)
The cell announces a connection with a single conn-open. When the desktop's
control socket dies mid-accept the phone waited out the 10s attach deadline and
was closed HOST_OFFLINE, even though the desktop was online. host-hello-ack
already restates those connections in pendingConns, but only by connId and
connTicket, which is not enough for the desktop to dial: kind and relayDeviceId
decide the pairing authority a connection carries and the E2EE device binding,
so neither may be guessed.

The cell now states kind and relayDeviceId on each pending entry, but only to a
host that advertised it can read them: a shipped host parses those entries
strictly, so an unannounced key fails the whole ack parse and kills a working
control. The advertisement rides the control upgrade as
x-orca-host-capabilities, not host-hello, because HostHelloSchema is strict on
the cell too and any new hello key is refused by every already-deployed cell.

The capability is keyed by socket, not by session: a rebind can land a successor
whose decoder is older or newer than the one that opened the session, and the
ack must follow the socket that will actually read it.

With no capable host in the fleet the emitted ack is byte-identical to today's.
The desktop half that consumes the new fields is #19238.
2026-09-07 05:06:38 -04:00
Jinwoo Hong db13cff832 relay: give the asia-east2 cells the regional rehome identity (#19239)
`relay_region_rehome_source_cell_ids` listed only the 16 US cells, and that
list is the sole thing that stamps ORCA_RELAY_REHOME_DIRECTOR_SERVICE_ACCOUNT
and ORCA_RELAY_REHOME_AUDIENCE into a cell's startup script. A cell reports
regionalRehomeProtocol 1 only when both are present, so c27-c29 have always
reported 0. That leaves them ineligible as rehome sources and, once the worker
is bidirectional, as targets too, which strands the US desktops homed there.

This is a prerequisite only. Merge and roll it ONLY AFTER the bidirectional
rehome director change is deployed. Two live gates still hard-code the primary
region and would reject an Asia source no matter what the template stamps:
`cloud/apps/relay/src/app.ts` line 610 fails the trust probe with 409 when the
source cell's region is not RELAY_DEFAULT_REGION, and
`cloud/apps/relay/src/assignment-store.ts` line 5476 skips such a cell as
source_ineligible during rehome source selection. The bidirectional lane
removes both.

The topology check asserted every source sits in the primary region. That
mirrored those two gates rather than protecting anything Terraform owns, so it
is now advisory: it requires only a configured, unfenced cell with an explicit
connection limit, and the comment records that region eligibility belongs to
the director's own source and target predicates. Every cell's region is
already constrained by the assert above it.

The same-cap census test cross-checked membership against us-central1. Every
reviewed serving cell now carries the trust, so it asserts protocol 1 for all,
plus one non-source cell to keep the validator's protocol-0 branch covered.

Roll sequencing, because this apply is not self-contained:

- After the apply the Asia templates carry the two rehome lines, and the
  `unexpectedRehome` rule at `cloud/dev/scripts/validate-relay-capacity-plan.mjs`
  lines 243-247 rejects a protocol-0 plan that contains them. So c27-c29 have
  no dispatchable protocol-0 same-cap roll until the director gate is gone or
  this is reverted.
- The same-cap job runs the per-host trust probe after isolate, drain, and the
  targeted apply. A 409 there leaves the cell serving but isolated and
  migration-only, which is what happened to c13 on 2026-09-06.
- The only safe path: deploy the bidirectional rehome director, then dispatch
  `Deploy Relay Production Same-Cap` canary-apply for one Asia cell with
  target-rehome-protocol 1 and rollback-rehome-protocol 0, then batch-apply the
  remaining two. That job runs its own targeted template and MIG apply.
- Never reach these cells with an untargeted root apply. The current plan
  carries 60 changes and 50 destroys of unrelated standing drift.
2026-09-07 05:03:26 -04:00
Jinwoo Hong d74f8cb787 revert(mobile): hold the relay reconnect path and cache-first reconnect for a separate mobile pass (#19265)
* Revert "feat(mobile): draw the last known tab strip while a session reconnects (#19258)"

This reverts commit 0ba7f8dc8d.

* Revert "perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (#19236)"

This reverts commit 23df74d85a.
2026-09-07 04:56:13 -04:00
Jinwoo Hong fede3eb2ff fix(test): give federation tests a real read-after-write sync barrier (#19262)
`syncOrchestrationFederation()` coalesces onto an already-in-flight relay-tick
sync, which may have pulled from the peer before the caller's mutation existed.
Tests used it as a barrier, so `keeps a timed-out remote question resumable`
could reply against a home DB that had never imported the worker's question:
the reply failed with `Message not found`, no `to_worker` relay was enqueued,
and the resume ask surfaced it 5s later as a spurious timeout.

Add `syncFederationBarrier()`, which chains each active dispatch past the
current round via `syncOrchestrationFederatedDispatchAfterCurrent`, and use it
at every barrier-purpose sync site. The two tests whose subject is the sync
machinery itself keep the raw call. Also assert the reply response, so a failed
reply fails at the reply instead of masquerading as a timeout.

Production is unaffected: `syncOrchestrationFederation` has no production
callers, real read-after-write paths already use the after-current sync, and
relay ticks retry every second.
2026-09-07 04:54:28 -04:00
Jinwoo Hong e068947d4c feat(relay): alert on far-cell placement and skewed region hints (#19253)
* feat(relay): alert on far-cell placement and skewed region hints

US desktops were homed on asia-east2 cells for weeks in 2026-08 with every
existing relay alert green. Roughly 226 of 332 hosts on those cells were
non-APAC, and a phone connect took ~10 s there against ~0.6 s in region, but
nothing in Cloud Monitoring could see distance: the connection, queue, heap,
and SQL bars all measure a cell's own health, which was fine.

Three policies close that gap. Two read distance per cell, from the accept
and control-RTT timing added in the parent commit: phone-accept p95 above
2 s, and control ping p50 above 150 ms. The third reads the cause fleet-wide,
as the asia-east2 share of the region hints desktops send the director, so a
mis-picking client probe is visible before it lands anyone on a far cell.

All three are MQL rather than the metric filters the other relay policies
use. Every runtime metric is a DELTA DISTRIBUTION, and a filter condition can
only align one with a percentile; each alert needs the sum of the extracted
values as a volume floor so a sparse window cannot page. None of these
metrics exists in the project yet, so what was checked against production is
the query shape: the same MQL run over existing metrics of the same kind.

The skew denominator needs one log-based metric per hint key, so
`requestedRegionsDelta` now has one per relay region plus the unhinted
bucket. Those ride the existing snapshot metric family, which adds map
entries without touching the live metrics. A ratchet test pins the key list
to relay-contract's RELAY_REGIONS: a region added there without a metric
would shrink the denominator, so the test fails rather than letting the share
quietly inflate.

* fix(relay): compare hinted regions against placed ones, not a fixed share

Review found the skew alert inverted at both ends. A fixed 40% bar on the
asia-east2 share of region hints was silent through the exact broken state it
was written for, and would page forever once the desktop probe is fixed and
the genuine APAC share rises past it. An absolute share cannot separate those
because it has no reference point.

The hint share now has one: the share of assignments the director actually
placed in that region during the same hour. Measured over twelve hours on
2026-09-07, while the probe was still mis-picking, asia-east2 was 33.8% of
33,800 hinted requests and 7.9% of 45,364 assignments. That is a 4.27x
divergence and a 25.9-point gap, so the alert fires above 2x and 15 points,
inside the broken state and outside a healthy one. Both bars must hold: the
ratio alone blows up on tiny placement counts, the gap alone misses a
proportionally large skew at low volume. The reviewer proposed either bar
alone; requiring both keeps each one meaningful and still clears today's
numbers with room.

`unhinted` requests leave the denominator. They were 27% of all requests, so
a client that always sends a hint would move the number from 21.9% to 35.0%
with no behaviour change at all.

The comparison needs per-region placement counters, so `selectedRegionsDelta`
gets log-based metrics alongside the requested ones. Rather than extract four
hyphenated map keys through quoted field paths, which nothing in the project
does and which cannot be checked without applying, the relay now also
publishes flat `requestedRegion<Region>Delta` and `selectedRegion<Region>Delta`
fields next to the untouched maps. They are emitted as zeros in every
interval, so no series can drop out of the alert's inner join in an hour with
no asia placements, which is exactly the hour the skew is worst. Additive
only: metricVersion is unchanged, the maps still carry anything outside the
catalog, and the emitter's leak guard still passes.

Two corrections to what the previous commit claimed. None of these metrics
exist in the project yet, so the code, the doc and this message now say what
was actually checked against production: the query shapes, run over existing
metrics of the same kind. And the control-RTT policy records that EU desktops
on us-central1 sit at 100-130 ms, so a European-heavy cell can approach the
150 ms bar while correctly homed.

The skew alert will stay lit after a client fix until the backlog is rehomed.
Sticky assignment never re-consults the hint, so a desktop already on an asia
cell keeps landing there whatever it now asks for. The policy description and
the doc both say so, so nobody reads a slow clear as a failed fix.

* fix(relay): cross-multiply the skew bars so a zero placement share still fires

`hint_share / placement_share` is undefined in the hour that matters most.
When the director placed nobody in the region, MQL returns no rows for either
0/0 or x/0, so the series disappears before the gap and volume clauses run and
the alert stays silent. That hour is not hypothetical: it is every desktop
asking for a region while the director puts nobody there, which is what a
drained, fenced, or full region looks like, and it is the most extreme skew
the alert can see.

The condition is now cross-multiplied, `hint_share > 2 * placement_share`,
which is well defined at zero. Both forms were run read-only against
production surrogates chosen so the placement denominator is exactly zero:
the ratio form returned no rows, the cross-multiplied form returned the series
with the condition true on every point. A second surrogate pass with a tiny
hint share returned the series with the condition false, so the gap clause
still suppresses the healthy shape rather than the query silently matching
everything.

The flat field names are no longer derived on either side. Terraform title
cased each dash-separated part and the emitter upper cased each part's first
character, so the ratchet had to pin two source expressions by regex, which a
reformat would break and which never compared the actual rendered names. Both
sides now declare a literal map, relay-contract's
RELAY_REGION_METRIC_SEGMENTS and Terraform's relay_region_field_segments, and
the test compares the two declarations against each other and against the
expected names. `satisfies Record<RelayRegion, string>` makes a region added
without a segment a compile error rather than a silent gap in the alert's
denominators.

Both ratchets were checked by mutation: a wrong Terraform segment, a contract
region with no Terraform entry, and a revert to the ratio form each fail the
node test, and the new region fails the contract build.
2026-09-07 04:51:48 -04:00
Jinwoo Hong 0ba7f8dc8d feat(mobile): draw the last known tab strip while a session reconnects (#19258)
* feat(mobile): draw the last known tab strip while a session reconnects

Reopening a workspace the phone has already visited threw away everything
it knew. The route clears its tabs on mount, so until the reconnect lands
and the first snapshot is applied the session screen has an empty header
and a bare spinner, even though the strip it is about to be handed is the
one it drew a minute ago.

Persist the four fields the strip actually draws -- id, type, title, agent
-- per host and workspace, and add a reconnecting-with-cache shape to the
route state so those rows render immediately, disabled, under the ids the
live snapshot will reuse. Live tabs always outrank the cache, so a
mid-session drop keeps its mounted terminals; an exhausted retry loop or a
rejected pairing outranks it the other way, because a strip the user cannot
reach is worse than the existing offline affordance. With nothing cached
the screen behaves exactly as before.

The body stays a placeholder. Replaying stored scrollback into the terminal
WebView would double-render the same rows once the live stream replays them,
so the strip is the cached content and the body waits for the stream.

* fix(mobile): keep shell titles and unpaired hosts out of the cached tab strip

Review of the reconnect strip cache found two ways it leaked.

A terminal's title is whatever the shell last set, which is routinely the
command line: a psql URL with an inline password, a curl with a bearer
token. Both fit well inside the 64-character cap and both were written to
plaintext AsyncStorage verbatim. Browser tabs carried their page title the
same way. Terminals and browsers now collapse to a fixed label, with a
resolved agent naming itself because that lookup is a closed enum. The rule
lives in the storage module rather than its caller, so it holds for entries
an older build already wrote, and a tab type this build cannot draw is
dropped instead of having its title trusted.

The cache also survived forgetting a host. Nothing expired an entry, and
the module-global memory map meant a later save from any surviving host
serialized the forgotten host's rows straight back to disk. Both cleanup
paths now evict by host, dropping the in-memory rows and rewriting storage,
with a pending debounced write cancelled so it cannot restore them.

Also: the storage key digests the workspace id, which ended in a filesystem
path, and cached rows carry the same de-emphasis as the disabled tab-bar
buttons beside them, so an inert row does not pass for a live one.
2026-09-07 04:42:59 -04:00
Jinwoo Hong 23df74d85a perf(mobile): cut the relay reconnect critical path and admit dead sockets faster (#19236)
* perf(mobile): cut the relay reconnect critical path and admit dead sockets faster

Phone medians put E2EE authentication at ~424ms but `connected` at ~630ms,
because the session serialized two RPC round trips behind it: the resume
confirm (`pairing.getEndpoints`) and the capability advisory. Both now ride
the authenticated socket concurrently and off the critical path, so the
session publishes `connected` as soon as E2EE authenticates. Peer identity
is already proven by then — the confirm carries credential/lease bookkeeping
and the cell assignment check, and it still fails the session on a bad answer
or a foreign relayHostId, only later. `persistResumeConfirmation` awaits the
new `whenResumeConfirmed()` instead of assuming the answer is present at
`connected`.

Foreground liveness on a retained relay: `notifyForeground('app-resume')`
now probes past the 10s voluntary minimum on urgent bounds (2s, one miss),
so a socket that died while the process was suspended is admitted in ~2s
instead of ~8s. Focus and network nudges keep the old minimum and bounds.
Relay sessions also gain a 25s idle sweep, gated on foreground so a
backgrounded app spends no probes.

Recovery is no longer blocked by the direct return probe. The probe's 12s
dial is a pure observation on its own socket, so it takes the supervisor's
operation mutex only for the cutover; a relay recovery landing during a
foreground return now starts immediately instead of waiting the budget out.
Requests that do land during the cutover are queued in a new
RelayRecoveryIntentQueue and replayed on release — an owning forced
replacement keeps its intent, everything else replays as a plain recovery.

Tests updated deliberately, for the new ordering:
- 'sends no periodic traffic while an authenticated relay is idle' asserted
  the absence of any relay idle probe, which is exactly the gap D3 closes.
  Replaced by a sweep test plus a backgrounded no-probe test.
- 'rate-limits foreground sequences without suppressing a retry' asserted
  that app-resume was suppressed inside the 10s minimum. An app resume is
  now the one nudge that must never be rate-limited.
- the session helpers waited for the confirm answer before `connected`;
  they now authenticate, read both concurrent frames, and settle them.

* fix(mobile): book backoff when a relay resume confirm fails after the cutover

Review round 1 on 352bfd2300.

P1: publishing `connected` at E2EE authentication made `migrateTo` resolve
before the resume confirm answered, so a confirm that failed afterwards —
a `relayHostId` mismatch from a rehomed desktop is the live case — was still
reported as an `established` dial. registerFailure was skipped, no cooldown
was booked, recordMigration()/setActiveSession() ran for a dying session, and
the queued-recovery replay redialled immediately: a tight loop with a
connected→disconnected blip per pass. The establisher now awaits
whenResumeConfirmed() after the cutover and, if the session is no longer
connected, reports a failed dial (or an aborted one when direct won or the
supervisor went inactive) exactly as a rejected migrateTo used to. The UI
still connects early; only the supervisor's bookkeeping waits.

The state check, rather than getFailure(), is the oracle: a live session can
carry a latched failure without having failed yet, and "is this session still
alive once the confirm settled" is precisely the question migrateTo used to
answer.

P2: the resume probe profile goes to two 2s misses instead of one. The first
frame after a resume rides a cold radio and a possibly distant cell, so one
slow answer is not proof of a dead link; the verdict still lands at 4s rather
than the previous 8s.

Nits: the direct probe's two early returns no longer close the candidate the
finally also closes (the second shape pre-existed); RelayRecoveryIntentQueue
is cleared in the supervisor's stop().

Mutex-hold note: persistResumeConfirmation, and now the establisher's own
await, are bounded by the confirm's request timeout. That would have been the
session's 30s default, so the confirm is pinned to RELAY_CONFIRM_TIMEOUT_MS
(12s) — the same bound migrateTo's waitForAuthenticated applied before.

Test: a supervisor-level case where every dial authenticates then fails the
confirm must book 250/500/1000ms backoff with no immediate redial, and must
never record a migration. It fails on the pre-fix establisher.
2026-09-07 04:40:40 -04:00
Jinwoo Hong f5be177e44 fix(relay): rehome hosts to their preferred region in either direction (#19241)
* fix(relay): rehome hosts to their preferred region in either direction

The regional-rehome worker only moved hosts from a us-central1 cell to an
asia-east2 one, so a host whose desktop later records us-central1 stays where
it was put. Rehoming now compares the fresh preference against the region of
the cell the host is on and moves it to a general cell in the preferred
region either way, through the same drain, migrate, safety, and rate-limit
machinery.

- relay_region_rehome_attempts.preferred_region accepts both regions; existing
  databases are upgraded in place by an idempotent named-constraint swap that
  is safe when several directors start at once.
- A target must carry the drain protocol too: moving a host onto a cell it
  can never be drained off again is the trap this change exists to undo. The
  fleet whose health gates a rehome is now every general drainable cell,
  which is exactly the set of legal sources and targets.
- The trust probe accepts a source cell in any region.

No wire change, and no behaviour change while the durable control is off.

* fix(relay): bound bidirectional rehoming with a per-host cooldown

Moving hosts in both directions removed the property that made the old
one-way worker self-terminating: a desktop whose region probe flips would be
dragged back and forth, one full drain and migrate per flip, because the
preference age never expires while the host keeps reconnecting.

- relay_region_rehome_control gains host_cooldown_ms, an operator input
  plumbed like preference_max_age_ms (workflow, ops script, admin route,
  durable row) and defaulted to seven days. A host with any attempt row
  inside the window, whichever way that move went, is not a candidate; the
  claim re-reads it under lock so an attempt landing between scan and claim
  cannot start a second move. Skips are named host_cooldown, and the lookup
  rides a new index on (user_id, relay_host_id, created_at).
- The candidate scan now also requires the target cell to be enabled, so it
  mirrors the claim-time filter exactly and stops spending batch slots on
  candidates that are certain to be skipped.
- Region CHECK lists are rendered from the shared region list instead of
  being written out four times.
- The operations runbook states that cells without the drain protocol are
  neither sources, targets, nor members of the safety gate.

* fix(relay): keep rehome reads and brakes working across the cooldown rollout

The ops script validated hostCooldownMs on every inspected control, so
against any director image predating the field inspect, pause, disable, and
failed-enable recovery all threw client-side. The workflow always runs from
main while the director image is operator-supplied, so that window opened at
merge and reopened on every rollback: the operator lost read-only visibility
and both emergency brakes while the worker could still be enabled.

The field is now validated only when the director reports it, and every apply
body that echoes an inspected control omits the key when that control lacks
it, so a legacy director never sees an unknown key. The write path stays
fail-closed the other way: enable refuses up front, before any mutation, when
the director does not report a cooldown it could honour.

Also replaces two bare 'us-central1' defaults with RELAY_DEFAULT_REGION.
2026-09-07 04:40:37 -04:00
Jinwoo Hong ecfcc0d833 feat(relay): time successful client accepts and control round trips (#19232)
* feat(relay): time successful client accepts and control round trips

A 6s accept on a cross-region cell was invisible: only the abandoned path
was timed. Record per-stage durations across acceptClient and acceptHostData
(assignment/credential/activity/attach), emit one completed log line per
accept, and aggregate p50/p95/max into the runtime metrics event.

Sample control ping round trips from the pong echo so a host sitting on a
distant cell is visible fleet-wide and per host, rate-limited to one log
line an hour per session.

* fix(relay): review round 1 on accept and control-RTT timing

Omit the accept and RTT percentiles from windows with no samples: accepts
are sparse, so a zero point every 30s would pin the p50 at 0 and collapse
the p95. The *Delta counts still publish, and say when the omission is
expected. Control-renewal output is unchanged.

Add a `basis` stage for the splice lease and connection-basis writes that
run between the host data leg and relay-hello, and start `attach` where the
activity stage ended, so the stages now tile the whole accept and their sum
equals totalMs. Clamp every stage at zero against a backwards clock step.

Carry role/cellId/region on both new log lines, flatten the stage p95 field
names so the log-metric extractors stay top-level, and record that only the
RTT median reads as distance: the desktop echoes the pong on its main
thread, so the p95 and max track desktop stalls.
2026-09-07 04:40:34 -04:00
Jinwoo Hong a3e67365a3 fix(orchestration): recover Codex idle after completion title race (#19243)
* fix(orchestration): recover Codex idle after completion title race

* test(native-chat): enable structured sessions in adoption replay fixture

* test(orchestration): cover deferred pointer recovery after prolonged unknown status

* fix(orchestration): fence completion recovery by process generation
2026-09-07 04:35:56 -04:00
Neil c3a70082c6 Fix MiniMax credential-expiry reporting, region sync, and refresh (#19250)
* Fix MiniMax credential-expiry reporting, region sync, and refresh

Three defects from #14929:

1. The usage endpoint answers an expired cookie or key with HTTP 200 and
   base_resp.status_code 1004, never 401/403 (confirmed against both regional
   hosts). The stale-token branch was therefore unreachable, so expired
   credentials surfaced as 'usage-unavailable' with the raw upstream string,
   and stale policy kept showing old numbers as if the failure were transient.
   Classify 1004 as an expired credential.

2. minimaxEndpoint reached the SettingsUpdate schema and the web store but was
   never projected by RuntimeClientSettingsController.get(), so a paired client
   fell back to 'overseas' regardless of the host's region and rendered the
   wrong console link. Add it to the projection and the store contract.

3. Changing the region persisted without refreshing usage, leaving the previous
   host's snapshot in the status bar until the next poll. Invalidate and refetch
   when the endpoint, group id, or model list changes.

The RPC-level tests mock the controller, so the projection had no real
coverage; the new test fails against the pre-fix projection.

* Localize the MiniMax credential-expiry copy

Classifying 1004 as stale-token made the status bar show the raw English
error verbatim: the new wording matches none of USAGE_AUTH_ERROR_PATTERNS,
whereas the old upstream text ('...log in again') matched and was replaced
with localized copy. That traded a localized-but-misleading message for an
actionable English-only one, which is the wrong trade for the CN users this
work targets.

Tag the error with credentialSource so the renderer can pick the right
localized string per credential kind, and add the three catalog entries.
2026-09-07 01:22:08 -07:00