Repository navigation
fix(mobile): give each host field one writer so relay routing can't revert edits - #22956
Conversation
…evert edits Relay learners (director re-resolution, credential rotation, direct-to-relay upgrade) saved the whole HostProfile snapshot their connection opened with, so a late relay write reverted an Edit Host endpoint and rewrote the device token. The relay overlay also stored a copy of the paired address, which the direct probe kept dialling after an edit. Pairing is now the only full-profile writer (savePairedHost, fenced by a census). Learners call setRelayRouting(hostId, relay), which never touches the row or keychain, refuses a removed host, and skips unchanged routing. The overlay is relay-only in memory; one serializer writes the v2 shape older builds parse, without the direct entry. Saving a new endpoint rebuilds even a Relay-active client from the saved row. Co-authored-by: mmarabel <166927047+mmarabel@users.noreply.github.com> Co-authored-by: Neil <neil@stably.ai>
Baseline moves to the product commit. adapterSha256 moves for the pairing and relay-credential adapters, which now read relay.relayHostId and inject saveRelayRouting. Only the four direct-upgrade bodies change: the settled host no longer carries the overlay's endpoints copy (direct-primary, relay-primary) or the duplicate relayHostId; relay and every effect are unchanged. Co-authored-by: mmarabel <166927047+mmarabel@users.noreply.github.com> Co-authored-by: Neil <neil@stably.ai>
There was a problem hiding this comment.
ℹ️ No critical issues. The refactor's core invariant holds — no relay learner can revert an Edit Host. One non-blocking design question on the new writer boundary below.
Reviewed changes
- One whole-host writer.
saveHost/saveExistingHostRelayUpgradeare replaced by pairing-onlysavePairedHost(fenced bypaired-host-writer-census.test.ts) plussetRelayRouting(hostId, relay), which takes no profile and refuses a removed host. - Address stored once.
HostProfiledropsendpoints/relayHostIdand keepsrelay; the overlay keeps a derived relay-only copy only for older builds, and this build's reader/join consume onlyrelay. - Save reconnects.
forceReconnect(hostId, { savedAddressChanged })rebuilds even a relay-active client and drops the primed profile; the edit screen passes the flag only when the address actually changed. - Single direct dial + one connect-URL builder. The multi-candidate direct probe is removed (the old
endpointslist was always[row address, relay]), and five copies of the relay connect-URL builder collapse intomobile-relay-connect-url.ts. - Stopped-supervisor guard.
adoptRelayRoutingreturns the host unchanged when the supervisor has stopped, so a late resolution/rotation writes nothing.
I read the full authored diff. I verified the two highest-risk contracts: no learner path can write endpoint/deviceToken/name from a connection snapshot (so Edit Host cannot be reverted), setRelayRouting vs removeHost is atomic through the single host-list queue with a consistent host-list → overlay lock order, and the on-disk shape remains readable in both directions by the builds this PR replaces.
ℹ️ Routing writes are not uniformly serialized against a concurrent re-pair
setRelayRouting holds the host-list mutation across its overlay write, but savePairedHost performs its overlay write after mutateStoredHosts has released that queue (and after commitDeviceToken). A live learner's routing write can therefore be enqueued after a concurrent re-pair's, leaving the older routing beside the newer credential bundle. This is a narrower, self-healing version of the stale-cell class the PR already acknowledges, and it is strictly better than main, which reverted the whole row — raising it only as an open question about whether the new API boundary should be the thing that closes it.
Technical details
# Routing-writer serialization asymmetry
## Affected sites
- `mobile/src/transport/host-store.ts:158-171` — `setRelayRouting` spans the host-list mutation and the overlay write, but validates only that the host id still exists, not that the relay/credential identity its snapshot came from is still current.
- `mobile/src/transport/host-store.ts:227-245` — `savePairedHost` writes the credential bundle, then the row, then the overlay; the overlay write runs after the host-list queue is released.
## Why the ordering is not guaranteed
Pairing writes the bundle (`pre-profile-pairing-coordinator.ts:249-250`, `mobile-relay-pairing-recovery.ts:265-268`) before `savePairedHost`. A learner's `setRelayRouting` can acquire the freed host-list queue during pairing's keychain/overlay phase and enqueue its overlay write after pairing's, so the final overlay relay can be the learner's older one while the bundle is the newer one. Which write lands last depends on async timing rather than an explicit loser rule.
## Open questions for the human
- Should `setRelayRouting` refuse when the current routing/credential identity differs from the one the learner resolved, or is a later re-resolution the intended repair?
- If this is acceptable, is it worth a line in the PR's "Known low-severity follow-ups" alongside the `assignmentEpoch` note?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Follow-up to the field-ownership split. The supervisor keeps its host
read-only and holds the relay in a small owner that persists moves through
setRelayRouting; the direct upgrade returns { relay, bundle } and the
lifecycle composes the profile once. With one direct endpoint left, the probe
takes a bound openDirect and the lifecycle computes the direct path once.
One name per writer: setRelayRouting and savePairedHost are also the
dependency keys, and the removed-host error is RelayRoutingHostRemovedError.
The census now counts real value imports of savePairedHost, not mentions.
Co-authored-by: mmarabel <166927047+mmarabel@users.noreply.github.com>
Co-authored-by: Neil <neil@stably.ai>
… result
Baseline moves to the refactor commit, and adapterSha256 moves for the
pairing and relay-credential adapters (dependency keys renamed to
savePairedHost and setRelayRouting). Only the four direct-upgrade bodies
change: the settled upgrade result is now { relay, bundle } instead of
{ host, bundle }, with identical relay, bundle, state and effects.
Co-authored-by: mmarabel <166927047+mmarabel@users.noreply.github.com>
Co-authored-by: Neil <neil@stably.ai>
Edit Host now reuses refreshHostClient, which already rebuilds an owned client (relay-active included) from the saved row after re-pairing, instead of a savedAddressChanged flag on forceReconnect. The session establisher, the only relay dialer, holds the relay and adopts learned routing through setRelayRouting; the supervisor takes a host id and a required relay, so the no-relay guards and the synthetic upgraded profile go. enqueueHostListMutation returns its operation's value, and the overlay store names its API after routing. Co-authored-by: mmarabel <166927047+mmarabel@users.noreply.github.com> Co-authored-by: Neil <neil@stably.ai>
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior pullfrog review at 6ba444b, three commits landed that tighten the field-ownership refactor:
- The relay session establisher owns the relay.
MobileRelaySessionEstablishernow holds theMobileRelayEndpointit dials and exposesadoptRelay, which checks the stopped guard, persists viasetRelayRouting, then updates its own copy; the supervisor no longer holds aHostProfile(constructor takeshostId+relay), andadoptRelayRoutingis removed. - The edit screen refreshes through the shared client hook.
forceReconnectdropsForceReconnectOptions/savedAddressChanged, andedit.tsxcalls the existingrefreshHostClient(host.id), which closes even a relay-active client, forgets the primed profile, and reopens from the saved row. - Overlay and queue plumbing simplified.
mutateOverlaysreturns the changed flag by reference equality andsaveMobileRelayHostRoutingpasses it straight through;enqueueHostListMutationis generic sosetRelayRoutingreads the result; the direct-upgrade result is{ relay, bundle }; and the whole-host census now matches only named imports ofsavePairedHostfromhost-store.
I re-read the full authored delta against the prior review. The ownership transfer is covered — the supervisor test asserts openRelay is called with the director-resolved cell and setRelayRouting is called with it, and the new lifecycle test fails if adoptRelay's stopped guard is dropped. The reconnect swap preserves the relay-preserve bypass and the primed-profile drop, and the "no grey flash" claim holds because closeEntry's disconnected and openEntry's connecting notifications are both emitted synchronously. The prior review's routing-writer serialization question is now captured in the PR's "Known low-severity follow-ups".
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
#22956 re-recorded with baseline = its own branch commit c5c1477, which the squash merge left unreachable from main, so the RPC recording pin guard fails on main and every open PR. Repin to main's tip and re-record: only baseline and lockfileSha256 (main's lockfile moved in #22961/#22964) change; every recorded body is identical.

ELI5
The phone keeps a saved "card" for each paired computer. When you edited the computer's address in the mobile app and tapped Save, the address could quietly change back a moment later, and the phone kept trying the old address anyway.
That happened because background relay code kept its own old copy of the whole card and saved that copy back whenever it learned a new relay route. The address was also written in a second place that editing never updated.
Now each piece of the card has exactly one writer. The relay code can only write the relay route, the address lives in one place, and saving a new address reconnects using the new one.
What Changed
Before: after Edit host → change address → Save, the address could revert to the old one. Even when it did not, the phone kept dialling the old address as well. A host connected over relay kept using the old address until the app restarted. (The name half of #20141 is already fixed on
main.)After: the edited address sticks, only that address is dialled, and a host on relay reconnects against it right away.
Mechanism:
savePairedHost). A census test fails if anything else imports it. The three places that only learn relay routing — relay re-resolution, credential rotation, and the direct→relay upgrade — now callsetRelayRouting(hostId, relay). It takes no host copy, so a stale snapshot cannot be written back. It never touches the saved host row or the keychain device token, refuses a host the user removed, and skips the write when routing is unchanged (a failing relay loop re-resolves on every retry).persistRelayHost,saveExistingHostRelayUpgradeand therequireExistingflag are gone.direct-primary) plus a copy ofrelayHostId. The only reader of that list was the dial list, and nothing ever put anything but those copies in it.HostProfilenow carries justrelay;endpointsandrelayHostIdare removed. One serializer still writes the on-disk shape older builds require, and stale copies in existing records are ignored on read and dropped on the next routing write.refreshHostClient(host.id)when the address changed — the same call the pairing screens already use for a stale endpoint. It closes the connection even when it is on relay, forgets the cached profile, and reopens from the row just saved. A rename alone behaves as before.Also: the connection code now holds only what it owns. The supervisor keeps the host id, and the relay session establisher owns the (required) relay route and is the one place that persists it; the direct→relay upgrade returns
{ relay, bundle }rather than a rebuilt profile. The relay connect-URL builder had five copies and now has one (mobile-relay-connect-url.ts).Why
The root problem was that
HostProfileis assembled from three stores (host row, relay record, keychain token), and the same type was also the thingsaveHostwrote. Any code holding an old profile could write every field back.mainalready patched this for the name (mergeHostNameIdentity); the address and token were the next fields to be hit.This builds on #22509, which found and fixed the same bugs. That PR keeps the full-profile save and adds a policy (
create-or-update/relay-upgrade/pairing-recovery) telling it which fields to ignore. This PR removes the ability instead: relay code gets an API that can only write routing, so the whole class of stale-snapshot writes cannot come back through a future caller. It also shrinks production code (about +240/−320) rather than growing it, and needs no split ofhost-store.ts.Deliberately not included: #22509's pairing-journal change (#22790), which records the address at capture so an interrupted re-pairing replay can't overwrite a later edit. That needs an edit during a seconds-long boot replay, and it adds a field to a strict journal schema that older builds would discard. It can be done separately if wanted.
Linked Issue
Fixes #20141
Supersedes #22509
Visual Proof
N/A for new captures on this branch. The user-visible behaviour matches #22509's before/after capture (edited address survives a late relay write). Verified here by tests driving the real host store, overlay store, supervisor lifecycle and edit-save flow; not yet exercised on a physical device.
Testing
New or changed tests (ported and adapted from #22509 where they applied), each confirmed to fail with its production change reverted on its own:
savePairedHost.Run on macOS in
mobile/:pnpm test(884 files, 9559 passed, 6 skipped),pnpm typecheck,pnpm check:tests-typecheck,pnpm lint,oxfmt --check .; repo rootpnpm run check:code-quality:changed.pnpm typecheck:testsreports errors only in the 126 already-grandfathered test files, as onmain.RPC goldens were re-recorded in a separate commit: every file moves
baseline; 20 pairing/relay goldens moveadapterSha256(two recorder adapters changed); four direct-upgrade bodies change only in the settled upgrade result, which is now{ relay, bundle }instead of{ host, bundle }with identical values. Wire frames,relay, outcomes and effects are unchanged.Review
relayHostId, so older builds parse it and dial the saved address. Records written by older builds are read correctly and repaired on the next routing write. The desktop only ever sends one direct address (mobile-relay-pairing-offer.tscarries a singleendpoint), so dropping the endpoint list loses nothing.setRelayRoutingchecks the host and writes inside the host-list mutation queue, so it cannot raceremoveHostinto recreating a host.Agent skill upstream boundary
Notes
Builds on #22509 by @mmarabel and @nwparker; both are credited as co-authors on the commits.
Known low-severity follow-ups from review, none worse than
main:mainthis case recreated the host.setRelayRoutingdoes not compareassignmentEpoch, so a slow learner can write an older cell; the next dial re-resolves. Same onmain.In progress: a run on a physical device.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm testpass locally inmobile/; CI coverspnpm build