Skip to content

fix(mobile): give each host field one writer so relay routing can't revert edits - #22956

Merged
Jinwoo-H merged 5 commits into
mainfrom
fix/mobile-host-field-ownership
Sep 26, 2026
Merged

Jinwoo-H merged 5 commits into
mainfrom
fix/mobile-host-field-ownership

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​801 $\color{#cf222e}{\Huge{\mathbf{−}}}$​378 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​423
Prod 816 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1163 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1331 $\color{#cf222e}{\Huge{\mathbf{−}}}$​168

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:

  1. One writer per field. Only the pairing flows, which create a host, can save a whole host (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 call setRelayRouting(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, saveExistingHostRelayUpgrade and the requireExisting flag are gone.
  2. The address is stored once. The on-phone relay record used to carry a copy of the direct address (direct-primary) plus a copy of relayHostId. The only reader of that list was the dial list, and nothing ever put anything but those copies in it. HostProfile now carries just relay; endpoints and relayHostId are 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.
  3. Saving a new address reconnects. The edit screen now calls the existing 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 HostProfile is assembled from three stores (host row, relay record, keychain token), and the same type was also the thing saveHost wrote. Any code holding an old profile could write every field back. main already 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 of host-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

  • I manually tested these changes locally — not on a device or simulator yet
  • Automated tests added/updated

New or changed tests (ported and adapted from #22509 where they applied), each confirmed to fail with its production change reverted on its own:

  • An edited address and the keychain token survive a late relay re-resolution, a credential rotation and a direct→relay upgrade.
  • Routing for a removed host throws and never recreates it; a stopped supervisor writes nothing.
  • An old relay record holding the pre-edit address yields only the saved address, and is rewritten relay-only on the next routing write.
  • The new record shape passes a frozen copy of the shipped overlay schema.
  • Repeated identical routing writes nothing; routing writes never touch the keychain.
  • After an address edit, a relay-active host with a live owner is rebuilt from the saved row, with no "disconnected" flash; without the refresh, it keeps the old address.
  • Census: only pairing modules import 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 root pnpm run check:code-quality:changed. pnpm typecheck:tests reports errors only in the 126 already-grandfathered test files, as on main.

RPC goldens were re-recorded in a separate commit: every file moves baseline; 20 pairing/relay goldens move adapterSha256 (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

  • Wire / remote: no RPC, stream or desktop change. On-device storage only.
  • Backwards compatibility: the relay record keeps its v2 shape, with one relay entry and matching 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.ts carries a single endpoint), so dropping the endpoint list loses nothing.
  • Concurrency: setRelayRouting checks the host and writes inside the host-list mutation queue, so it cannot race removeHost into recreating a host.
  • Performance: relay retries no longer write the host list or the keychain, and repeats write nothing.
  • Cross-platform: mobile only; iOS and Android share this code.

Agent skill upstream boundary

  • Not applicable

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:

  • If a host is removed while a credential rotation is in flight, the rotated bundle is left for the pending-cleanup retry rather than deleted immediately (the upgrade path deletes it). On main this case recreated the host.
  • setRelayRouting does not compare assignmentEpoch, so a slow learner can write an older cell; the next dial re-resolves. Same on main.

In progress: a run on a physical device.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test pass locally in mobile/; CI covers pnpm build

Jinwoo-H and others added 2 commits September 25, 2026 18:41
…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>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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 / saveExistingHostRelayUpgrade are replaced by pairing-only savePairedHost (fenced by paired-host-writer-census.test.ts) plus setRelayRouting(hostId, relay), which takes no profile and refuses a removed host.
  • Address stored once. HostProfile drops endpoints/relayHostId and keeps relay; the overlay keeps a derived relay-only copy only for older builds, and this build's reader/join consume only relay.
  • 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 endpoints list was always [row address, relay]), and five copies of the relay connect-URL builder collapse into mobile-relay-connect-url.ts.
  • Stopped-supervisor guard. adoptRelayRouting returns 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?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Jinwoo-H and others added 3 commits September 25, 2026 19:12
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>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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. MobileRelaySessionEstablisher now holds the MobileRelayEndpoint it dials and exposes adoptRelay, which checks the stopped guard, persists via setRelayRouting, then updates its own copy; the supervisor no longer holds a HostProfile (constructor takes hostId + relay), and adoptRelayRouting is removed.
  • The edit screen refreshes through the shared client hook. forceReconnect drops ForceReconnectOptions/savedAddressChanged, and edit.tsx calls the existing refreshHostClient(host.id), which closes even a relay-active client, forgets the primed profile, and reopens from the saved row.
  • Overlay and queue plumbing simplified. mutateOverlays returns the changed flag by reference equality and saveMobileRelayHostRouting passes it straight through; enqueueHostListMutation is generic so setRelayRouting reads the result; the direct-upgrade result is { relay, bundle }; and the whole-host census now matches only named imports of savePairedHost from host-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".

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 02a5594 into main Sep 26, 2026
42 of 44 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 26, 2026
#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Preserve mobile host name and address after Edit host Save

1 participant