Skip to content

fix(mobile): keep host edits from being reverted by late relay persistence - #22509

Closed
mmarabel wants to merge 16 commits into
stablyai:mainfrom
mmarabel:mmarabel/fix-mobile-edit-host-20141
Closed

mmarabel wants to merge 16 commits into
stablyai:mainfrom
mmarabel:mmarabel/fix-mobile-edit-host-20141

Conversation

@mmarabel

@mmarabel mmarabel commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When you edit a paired computer's name or address in the mobile app and tap Save, the app could quietly put the old name and address back a moment later — and even when it did not, the phone kept trying to reach the computer at its old address.

Two things caused that. First, the background code that keeps the relay connection alive held its own copy of the host, taken when the connection opened, and saved that whole copy back whenever the relay moved. Anything you had changed in between was overwritten. Second, the address was written down in two places, and editing the host only changed one of them, so the stale copy kept being dialled.

Now the background code saves only the relay details it actually learned, the address is written down in exactly one place, and saving a new address rebuilds the connection against the row you just saved instead of leaving it pointed at the old one.

What Changed

Before: after Edit host → Save, the name and address could snap back to their old values. Even when they did not, the phone kept dialling the old LAN address, and a host that was already on relay stayed on the old address until the app was restarted.

After: the edit sticks, the old address is gone from the dial list, and the connection is rebuilt against the new address straight away.

The mechanism, in four parts:

  1. One owner for the host row. The connection supervisor persisted a relay re-resolution or credential rotation by re-saving its whole in-memory HostProfile, captured when the connection opened. That replaced the stored row wholesale — a classic read-modify-write against a stale base, and frequent, because a failing relay loop re-resolves on every retry. It now calls saveRelayRouting(hostId, relay), which merges only relay routing onto the stored overlay. The same pattern in the direct→relay upgrade is gone too: persistHost takes an explicit policy (create-or-update / relay-upgrade / pairing-recovery) instead of a requireExisting boolean that had grown two unrelated meanings.

  2. One place for the address. The direct address was stored twice — the host row's endpoint and the relay overlay's direct-primary entry — and the edit path only updated the first. Relay routing now carries the relay endpoint alone, and the host catalog derives the direct entry from the stored row on every read. That both removes the duplicate going forward and self-heals overlays written by shipped builds.

  3. Reconnect actually reconnects, against the saved row. forceReconnect deliberately preserves a live Relay session rather than rebuilding the client, and getActivePath() latches on the first adopted session and is never cleared — so a host whose relay is merely retrying (exactly the reporter's state) still reads relay, and the post-save reconnect degenerated to a foreground nudge of a client still bound to the pre-edit endpoint. forceReconnect now takes { savedAddressChanged }, which the edit screen passes only when the address changed. That one flag drives both things the situation needs: the Relay session is rebuilt, and the in-memory profile cache openHostClientEntry reads before loadHosts() is dropped, so the rebuild opens on the row the user just saved even when the edit screen's best-effort re-prime failed. A rename alone still preserves the session and the cache.

  4. The journaled pairing replay can now date its own address. Re-pairing a machine you already have reuses that machine's host id, so a pairing that is interrupted and later replayed from its journal writes onto an existing row. Previously neither the row nor the journal recorded when its address was written, so the replay could only keep the stored address — losing a genuinely re-paired address. The journal now records the row's address as it stood at capture, and the replay applies its own address only while the row still holds that value. An edit made after capture still wins; a journal written by a shipped build carries no captured address and keeps the conservative behaviour.

Housekeeping that fell out of the above: relayWebSocketUrl and withRelayRouting moved out of the zod schema module into mobile-relay-routing.ts and the two hand-rolled copies in the pairing writers were deleted; the dependency named saveRelayEndpoint became saveRelayRouting, which is what it writes, and persistRelayHost's writer parameter became saveRelayUpgrade; persistSupervisedRelay's stopped guard lost a = false default that made it skippable by omission; the serialized host-list mutation queue moved to host-list-mutation-queue.ts; and host-store.ts shed three modules it had accumulated — host-persist-policy.ts, host-device-token-cache.ts and unpaired-host-cleanup-scheduling.ts — so it stays inside its line budget without a lint suppression.

Two writes that the reporter's failing relay loop repeated on every single retry now short-circuit: persistHost hands back the list it read when no row field moved, and saveMobileRelayHostRouting returns the overlay list unchanged when the resolution repeats the routing already stored.

Why

The decisive fact is that StoredHostProfileSchema holds no relay fields at all — the row is only {id, name, endpoint, publicKeyB64, lastConnected}. A relay re-resolution changes none of them. So the old persistRelayHost → saveHost was a write whose only possible effect on the row was to lose data, performed purely to reach the overlay write at the tail of persistHost. "Persist only the fields this operation actually learned, into the store that actually holds them" is therefore not a judgement call; it is the only defensible write.

That also kills a second, worse class of stale write: persistHost ends with commitDeviceToken(stored.id, validated.deviceToken) on every call. On main, each relay re-resolution and each credential rotation rewrote the supervisor's snapshot device token into expo-secure-store and bumped the credential write revision — a keychain write per retry in a failing relay loop, and if the token had been rotated by a re-pair since the connection opened, the stale one won. Removing the full-profile save removes that too.

The obvious alternative — re-read the host, merge, save the whole profile — is strictly worse: it keeps the read-modify-write and only narrows the race window, and it would still rewrite the keychain token.

For the duplicated address, deriving direct-primary on read alone would have been a compromise: it makes the read path responsible for correcting data the write path knowingly persists wrong. So the write side changed as well and the overlay no longer carries direct endpoints at all. This is backward-safe in both directions: MobileRelayHostOverlaySchema only requires endpoints.min(1) with exactly one relay entry, and an older reader still dials the stored address because directEndpointUrls unions host.endpoint.

For the pairing replay, #22790 proposed a written-at stamp on the stored host row plus the journal's capture time. Comparing values rather than clocks turned out to be both smaller and stronger: the journal already has to be written before the pairing proceeds, so recording the row's address there costs nothing, needs no change to the durable host row, and cannot be fooled by a clock. The comparison is exact — the replay applies its address only when the row is provably the one the journal saw. Both old journals and first-time pairings fall through to today's behaviour.

For the reconnect, the alternative is to make the edit screen's re-prime mandatory and fail the save when it fails. That reports a save that did commit as a failure. Dropping the cache instead makes the reopen read the authoritative store, which is correct whether or not the re-prime worked.

No wire or protocol change: this is on-device storage and in-process wiring only.

Linked Issue

Fixes #20141
Fixes #22790

Visual Proof

Both frames are the real EditHostScreen rendered through react-native-web against the real host-store, overlay store and catalog join, with only AsyncStorage/SecureStore swapped for memory. The sequence in each: seed a relay-paired host (Studio iMac @ 192.168.1.10:6768), type a new name and Tailscale address, tap Save, then let the relay resolution that was already in flight land — through whichever entry point that build's supervisor actually calls — and reopen the host.

Before (current main) — the name now survives, because main's mergeHostNameIdentity keeps the name identity from the stored row on every save. The address is not covered by that merge, so it is still silently reverted to the old LAN address, and the screen re-offers it:

before

After (this PR) — both survive the late relay write:

after

The stored row read back at the end of each run: {"name":"Tailnet desk","endpoint":"ws://192.168.1.10:6768"} before, {"name":"Tailnet desk","endpoint":"ws://100.101.102.103:6768"} after.

Testing

  • I manually tested these changes locally — as the capture above, driving the real screen and the real storage layer. Not exercised on a physical Android or iOS device, and not through an app relaunch on a device; that gap is called out below rather than papered over.
  • Automated tests added/updated, or explained why not below

Reproducible steps for a reviewer with a paired host: open Edit host on a host whose relay is retrying, change the name and the address, Save, go back — on main the values revert and the phone keeps probing the old address; on this branch they stick and the client is rebuilt on the new address.

New and changed tests, all of which fail with their production change reverted (verified one at a time by micro-revert):

  • host-store-endpoint.test.ts — an edit survives a relay move, a direct-only relay upgrade, and a journaled pairing replay; a replay whose journal recorded an unchanged row takes the re-paired address, and one with no recorded address keeps the stored one; a relay upgrade leaves every row field untouched but still throws MobileRelayUpgradeHostRemovedError for a removed host; the overlay loses the stale direct URL on the next routing write; a relay-only save writes no host list and a repeated relay resolution writes no overlay.
  • host-store.test.ts — the pairing identity lookup reports the row's address, which is what the journal records.
  • pre-profile-pairing-coordinator.test.ts — the journal records the row's address when one exists and omits it when the desktop has never been paired; the published profile carries relay routing only.
  • mobile-relay-pairing-recovery.test.ts — the replay hands the recorded address to the store, and hands undefined for a journal that predates it.
  • mobile-endpoint-lifecycle-host-edit.test.ts — the real lifecycle wiring against the real host store: an edit made while relay resolution is pending survives it, and a resolution settling after stop writes nothing.
  • mobile-endpoint-supervisor-rotation-stop.test.ts — a rotation finishing after stop writes the rotated bundle but no relay routing.
  • client-context.test.ts — a Relay-active entry is rebuilt when the reconnect reports a changed address and still nudged when it does not, and that rebuild reads the saved row rather than a stale primed profile.

Run locally on macOS, in mobile/, on the current head: pnpm test (882 files, 9554 passed, 6 skipped), pnpm typecheck, pnpm typecheck:tests, pnpm check:tests-typecheck (878 test files in the program, 126 grandfathered, unchanged), pnpm lint (no errors; the two remaining warnings are pre-existing and in unrelated onboarding tests) and pnpm format:check.

Repository CI has run and is green on this branch. This is a fork PR, so all three workflows sat at action_required awaiting approval and nothing had ever verified the branch. They were approved, and PR Checks, Mobile Checks and PR test LoC all pass. The golden-parity job under src/test-support/rpc-recording is inside PR Checks.

The RPC-foundation goldens were re-recorded once, earlier on this branch, per src/test-support/rpc-recording/README.md: baseline repinned to this branch, full --record, then the delta classified. Only baseline (787, the repin), adapterSha256 (10, the pairing family whose adapter module changed) and the four relay.direct-upgrade bodies moved; nothing was added or deleted. The body move is exactly the disclosed change — a relay-paired profile no longer carries a direct-primary endpoint. The commits since then touch none of the corpus-provenance paths, so the pin stays reachable and no further repin is due.

AI Disclosure

Original change written with Claude Opus 5.5 in the pi coding agent, reviewed by the author. Takeover commits written with Claude Opus 5 in Claude Code, reviewed by @nwparker.

Review

  • Cross-platform: mobile app only; iOS and Android share this transport code. The desktop app is untouched.
  • SSH / remote / wire: no RPC params, stream frames or published content change, so a paired host on any version is unaffected. On-device storage stays within the existing schemas.
  • Backwards compatibility: an overlay written by this build is still readable by an older build — the schema only requires one endpoint and exactly one relay entry, and the older reader dials the stored address because mobile-direct-endpoint-probe.ts unions host.endpoint into its candidate list. An overlay written by an older build is repaired on the next read. The pairing journal's new field is optional and device-local; a journal written before it exists replays exactly as it does today. In the downgrade direction the journal's .strict() schema would reject the new key and the old build would discard that journal rather than misread it — the same characteristic the already-optional winner and authorizationMode keys have, and the cost is one unreconciled interrupted pairing, not a corrupt host row.
  • Performance: relay persistence is now a smaller merge write, no longer rewrites the keychain device token on every relay resolution, and a repeated resolution writes nothing at all. The direct entry is derived from data already in memory.
  • UI: no UI code changed beyond one extra argument at the post-save reconnect call site; the visible change is that saved values persist and the reconnect targets the new address.
  • Security: credential bundles are written exactly as before, a removed host is never resurrected by a relay upgrade, and a stopped supervisor writes nothing.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Taken over by @nwparker from @mmarabel, with the author's PR left intact and commits added on top; nothing of the author's was rewritten or force-pushed. main has since been merged in (the branch was conflicting on the re-recorded goldens).

That merge turned up a real convergence worth flagging: main independently landed a host-list-mutation-queue.ts with the same name and concept this branch had extracted, and a shared pairing-relay-host.ts for the pairing writers' relayHost. Both of this branch's near-duplicates were dropped in favour of main's; pairing-relay-host.relayHost now builds its endpoints through withRelayRouting, which lets the pairing-recovery replay share it instead of keeping a third copy.

main also made name derived (personalName ?? lastKnownMachineName ?? "Host N"), and mergeHostNameIdentity keeps that identity from the stored row on every save — which independently fixes the name half of #20141 for a full-profile save. The address is not covered by it, so the row-skip in this PR is what still carries that half. The before/after capture above is taken against current main, so it shows exactly that: the name survives, the address does not.

Two things an earlier revision of this description over-claimed, now corrected above: merging does not by itself remove the whole class of stale-snapshot overwrites (the journaled pairing-recovery replay was the remaining full-snapshot writer, and is fixed here), and the routing save's guard is "never creates an overlay", not "does nothing for a removed host" — an orphan overlay would still be updated, which is harmless because orphans are filtered on load and cleaned.

The previously listed known limitation — a relay-connected host keeps dialling the old address until restart — was DoD item 2 of #20141 and is fixed in this PR rather than deferred. #22790, opened from an earlier revision of this PR to track the pairing-replay asymmetry, is also closed by it.

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/, and repository CI has been approved and is green (see Testing). pnpm build is a desktop target and is untouched by this change; CI covers it.

…tence

Relay re-resolution, credential rotation and the first relay setup now merge only relay routing instead of re-saving a stale host snapshot; a stopped supervisor no longer persists, and the overlay's direct-primary URL follows the stored host address.

Fixes stablyai#20141
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 5c230115-1c80-4a5b-8dc0-72f22945d9e4

📥 Commits

Reviewing files that changed from the base of the PR and between 34509b3 and 3de8042.

📒 Files selected for processing (3)
  • mobile/src/transport/mobile-endpoint-supervisor-rotation-stop.test.ts
  • mobile/src/transport/mobile-endpoint-supervisor.ts
  • mobile/src/transport/mobile-relay-runtime-failover.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The change adds relay-routing helpers and overlay-store persistence for mobile hosts. The endpoint supervisor now saves relay routing by host ID and relay endpoint, rather than saving a full host snapshot. Relay-upgrade saves preserve the stored host row, and catalog construction uses the stored endpoint URL for the direct-primary endpoint. Added tests cover endpoint edits during relay resolution, stopped lifecycles, relay moves, stale snapshots, and removed hosts.

Merge Risk: ⚪ Minimal · up to 3de80

Host edits and relay routing are preserved on the examined paths; no merge-blocking issue remains after normal checks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 14 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR meets the coding requirements in [#20141]. Relay persistence now merges routing into the current stored host, so late relay work does not replace edited name or address values. Catalog loading …
Out of Scope Changes check ✅ Passed The changes remain within [#20141]. They modify mobile host persistence, relay supervision, endpoint loading, and related regression tests. Helper extraction supports the stale-write fix. No unrelated…
Title check ✅ Passed The title clearly and concisely describes the main change: preventing late relay persistence from reverting mobile host edits.
Description check ✅ Passed The description is complete and follows the repository template. It explains the user impact, implementation, rationale, linked issues, visual proof, testing, compatibility considerations, AI disclosu…

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

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3fc41a76-4102-4cf8-a227-eb1af266f922

📥 Commits

Reviewing files that changed from the base of the PR and between dac82f6 and 34509b3.

📒 Files selected for processing (12)
  • mobile/src/transport/host-catalog-credential-join.ts
  • mobile/src/transport/host-store-endpoint.test.ts
  • mobile/src/transport/host-store.ts
  • mobile/src/transport/mobile-endpoint-lifecycle-host-edit.test.ts
  • mobile/src/transport/mobile-endpoint-lifecycle.ts
  • mobile/src/transport/mobile-endpoint-supervisor-contract.ts
  • mobile/src/transport/mobile-endpoint-supervisor-support.ts
  • mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts
  • mobile/src/transport/mobile-endpoint-supervisor.test.ts
  • mobile/src/transport/mobile-endpoint-supervisor.ts
  • mobile/src/transport/mobile-relay-host-overlay-store.ts
  • mobile/src/transport/mobile-relay-host-overlay.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

A supervisor stopped while a credential rotation was in flight still persisted the rotated relay routing, which could overwrite its successor's routing. Pass the stopped flag to persistSupervisedRelay as the resolution path already does; the rotated bundle stays durable.

@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 — one stale dependency key left over from the rename.

Reviewed changes

  • Merge-only relay persistence: relay resolutions persist via new saveMobileRelayHostRouting, which merges only relay routing onto the stored overlay instead of re-writing the whole host profile captured when the connection opened, and no-ops for a removed host.
  • Stopped supervisors stop writing: persistSupervisedRelay takes a stopped flag and returns without writing when the supervisor has been replaced, so a resolution settling after stop() leaves storage alone.
  • Direct-only relay upgrade no longer rewrites the host row: persistHost keeps the stored row when requireExisting is set, so the upgrade's pre-edit snapshot cannot revert a name/endpoint edit; persistRelayHost is retained because it must create the overlay.
  • direct-primary URL derived on read: joinHostCatalogCredentials overrides the overlay's direct-primary URL with the stored endpoint, so an edited address is no longer dialed.
  • Tests: new mobile-endpoint-lifecycle-host-edit.test.ts exercises the real lifecycle wiring against the real store; store-level cases added in host-store-endpoint.test.ts.

I ran the touched and adjacent mobile tests (host-store-endpoint, mobile-endpoint-lifecycle-host-edit, mobile-endpoint-supervisor, host-store, mobile-relay-host-overlay-store, mobile-relay-direct-upgrade, pre-profile-pairing-coordinator, mobile-relay-pairing-recovery, mobile-relay-runtime-failover), pnpm typecheck, and oxlint on the changed files — all pass. The new tests do pin the intended behavior: with the fix reverted the join would expose the old direct URL and the full-snapshot save would revert the edit.

ℹ️ Stale saveHost in the relay-failover test double

The rename of the supervisor dependency from saveHost to saveRelayEndpoint was not carried into mobile-relay-runtime-failover.test.ts, whose dependencies() helper still declares saveHost and never supplies saveRelayEndpoint. The file is grandfathered in mobile/tests-typecheck-baseline.txt, so check:tests-typecheck stays green and the tests pass only because these cases never reach the director-fallback persistence path — but the double no longer matches the real dependency type, and a future case that settles a relay resolution there will throw dependencies.saveRelayEndpoint is not a function.

Technical details
# Stale `saveHost` in `mobile-relay-runtime-failover.test.ts`

## Affected sites
- `mobile/src/transport/mobile-relay-runtime-failover.test.ts:237` — `saveHost: vi.fn(async () => {})` remains in the object returned by `dependencies()`, while `MobileEndpointSupervisorDependencies` (as of this PR) requires `saveRelayEndpoint` (see `mobile/src/transport/mobile-endpoint-supervisor-contract.ts:22`).
- `mobile/tests-typecheck-baseline.txt:116` — the file is grandfathered, so the new TS2353 error does not fail the ratchet.

## Required outcome
- The test double provides `saveRelayEndpoint: vi.fn(async () => {})` (or overrides it where relevant) and drops the `saveHost` key, so it matches `MobileEndpointSupervisorDependencies` and any path through `persistResolvedRelay` cannot call an undefined function.

## Suggested approach
- Rename the `saveHost` entry at line 237 to `saveRelayEndpoint`; no behavior change to the existing cases.

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

@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

  • Stopped rotations no longer persist relay routing: rotateCredentialIfNeeded now passes this.stopped to persistSupervisedRelay, so a credential rotation that settles after stop() still lands the rotated bundle (already durable) but writes no relay routing, leaving routing to the successor supervisor.
  • Call-site simplification: the rotation path destructures { bundle, relay } from rotateMobileRelayCredential instead of threading a result object.
  • Regression test added: mobile-endpoint-supervisor-rotation-stop.test.ts holds the second writeBundle pending, stops the supervisor, then resolves it and asserts saveRelayEndpoint is never called while writeBundle stays at two calls. I confirmed it is genuine coverage — reverting the new this.stopped argument makes it fail (expected "vi.fn()" to not be called at all, but actually been called 1 times), and the touched suites pass (49 tests across the four files).

The rest of the PR (merge-only saveMobileRelayHostRouting, the saveRelayEndpoint rename and wiring, the direct-upgrade row-preservation, and the read-time direct-primary rewrite) was reviewed in the prior run and is unchanged here.

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

@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

  • Renamed the failover test double's stale dependency key: mobile-relay-runtime-failover.test.ts now supplies saveRelayEndpoint instead of saveHost, so the double matches MobileEndpointSupervisorDependencies, resolving the prior review's finding.

The rest of the PR is unchanged since the last review. I verified by reading the diff and surrounding code; this environment is missing expo and the React Native types, so the mobile suite could not be executed here.

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

The direct address was stored twice - the host row's `endpoint` and the relay
overlay's `direct-primary` entry - and editing a host only updated the first,
so the phone kept probing the pre-edit address. Relay routing now carries the
relay endpoint alone (`withRelayRouting`), and the catalog derives the direct
entry from the stored row on every read, which also self-heals overlays written
by shipped builds. Older readers are unaffected: the overlay schema only
requires one endpoint, and the direct probe already unions `host.endpoint`.

`requireExisting` had grown two unrelated policies, so `persistHost` now takes
an explicit mode. `pairing-recovery` is new: the journal replay carried a
pairing-time snapshot and republished it wholesale, which could overwrite a name
or address edited between capture and replay. It now creates the row only when
it is missing and otherwise publishes just the credential and relay routing.

`relayWebSocketUrl` and `withRelayRouting` move out of the zod schema module
into `mobile-relay-routing.ts`, and the two hand-rolled copies in the pairing
writers are deleted. `saveRelayEndpoint` becomes `saveRelayRouting`, which is
what it actually writes. The serialized host-list mutation queue moves to
`host-list-mutation-queue.ts` so `host-store.ts` stays under its line budget.
Saving a new address on a relay-connected host left the phone on the old one
until the app was restarted. `forceReconnect` deliberately preserves a live
Relay session instead of rebuilding the client, and `getActivePath()` latches on
the first adopted session and is never cleared - so a host whose relay is merely
retrying still reads `relay` and the reconnect degenerated to a foreground nudge
of a client still bound to the pre-edit endpoint.

`forceReconnect` now takes `{ bypassRelayPreservation }`, which the edit screen
passes only when the address actually changed. A rename still preserves the
session, because nothing it wrote invalidates the connection.
The pairing-recovery recording adapter supplied `saveHost`; the module now takes
`saveRecoveredPairingHost`. Recovery deferred on the missing dependency, which
is what the relay.pairing-recovery goldens were showing.
Cause: a relay-paired host profile no longer carries a `direct-primary`
endpoint, because the direct address now lives only in the stored host row. The
four `relay.direct-upgrade` goldens move their body for exactly that; the ten
pairing-family goldens move `adapterSha256` for the recovery adapter's renamed
dependency; every golden moves `baseline` for the repin. Nothing else moved, and
no golden was added or deleted.
@nwparker

Copy link
Copy Markdown
Contributor

Heads up @mmarabel — I've taken this one over and pushed four commits on top of yours (nothing of yours was rewritten or force-pushed). Your diagnosis and the shape of the fix were right; I mostly finished the parts that were left open and tightened two structural edges.

What I added:

  1. The known limitation is now fixed. A relay-connected host really did keep dialling the pre-edit address until restart — that was DoD item 2 of [Bug]: Preserve mobile host name and address after Edit host Save #20141, not an acceptable leftover. The cause is that getActivePath() in stable-logical-rpc-client.ts latches on the first adopted session and is never cleared, so shouldPreserveActiveRelay still returns true for a host whose relay is merely retrying, and forceReconnect degenerated to a foreground nudge. forceReconnect now takes { bypassRelayPreservation }, passed from the edit screen only when the address changed.
  2. The overlay no longer stores a direct address at all. Deriving direct-primary from stored.endpoint on read was a good guard rail, but it left the write path knowingly persisting a value the read path has to correct. withRelayRouting now emits the relay endpoint only, so the duplicate representation that caused this bug is gone rather than masked. Backward-safe both ways (schema only requires one endpoint; older readers union host.endpoint in the direct probe).
  3. The journaled pairing-recovery replay was still a full-snapshot writer — saveHost(relayHost(journal, relay)) built from journal.metadata.host would still clobber an edit made between capture and replay. persistHost grew a third mode for it.
  4. Structural nits: requireExisting became an explicit mode (it had grown two unrelated policies), saveRelayEndpoint → saveRelayRouting, and relayWebSocketUrl/withRelayRouting moved into mobile-relay-routing.ts with both hand-rolled copies in the pairing writers deleted — the refactor had half-landed and briefly left three copies instead of two.

Also: one test name asserted a guarantee the code does not give ("does not recreate relay routing for a removed host" only proved "no overlay"), so it's renamed; the RPC-foundation goldens were re-recorded per the README procedure; and I ran the full mobile suite, typecheck, the tests-typecheck ratchet, lint and format locally, since only pullfrog had run here.

The PR body is rewritten, including real before/after visual proof and the two places the old description over-claimed. The strongest argument for your design, which wasn't written down anywhere: StoredHostProfileSchema has no relay fields, so the old save could only ever lose data — and it re-committed the snapshot's device token to the keychain on every relay retry as well. Nice find.

main landed a `host-list-mutation-queue.ts` with the same name and concept as the
one this branch extracted, plus a shared `pairing-relay-host.ts` for the pairing
writers' `relayHost`. Both of this branch's near-duplicates are dropped in favour
of main's: the persist-mode change is reapplied on top of main's `persistHost`,
and `pairing-relay-host.relayHost` now builds its endpoints through
`withRelayRouting`, which lets the pairing-recovery replay share it too.

main also made `name` derived (`personalName ?? lastKnownMachineName ?? "Host N"`)
and gave `updateHostNameAndEndpoint` a `personalName` field, which independently
fixes the name half of stablyai#20141 for a full-profile save. The address half is not
covered by `mergeHostNameIdentity`, so this branch's row-skip still carries it.

Goldens are taken wholesale from main; the repin and refresh follow.
Cause: a relay-paired host profile no longer carries a `direct-primary`
endpoint, because the direct address now lives only in the stored host row. The
four `relay.direct-upgrade` goldens move their body for exactly that; the ten
pairing-family goldens move `adapterSha256` for the recovery adapter's renamed
dependency; every golden moves `baseline` for the repin onto the merge commit,
which is the last commit to touch a fenced path. Nothing else moved, and no
golden was added or deleted.
@nwparker

Copy link
Copy Markdown
Contributor

Follow-up: merged main in (the branch was conflicting on the re-recorded goldens) and re-recorded against the merge commit per the rpc-recording/README.md procedure — delta is again only baseline (787, the repin), adapterSha256 (10, pairing family) and the four relay.direct-upgrade bodies.

Worth knowing for review: main independently landed a host-list-mutation-queue.ts with the same name and concept I'd extracted here, plus a shared pairing-relay-host.ts. I dropped both of my near-duplicates for main's and routed pairing-relay-host.relayHost through withRelayRouting, so the pairing-recovery replay shares it rather than keeping a third copy.

Also: main's new mergeHostNameIdentity already keeps the name across a full-profile save, so half of #20141 is fixed on main today. The address is not covered by it — the visual proof in the body is re-captured against current main and shows exactly that split (name survives, address reverts). The row-skip in this PR is what closes it.

pnpm test in mobile/: 882 files, 9545 passed. Typecheck, tests-typecheck ratchet, oxlint and format all clean.

@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 — one rough edge inline.

Reviewed changes

  • Gave the stored host row sole ownership of the direct address: withRelayRouting now emits the relay endpoint alone, joinHostCatalogCredentials rebuilds direct-primary from stored.endpoint via the new directAccessEndpoints, and overlays written by older builds self-heal on read.
  • Split host persistence into explicit modes: persistHost now takes create-or-update / relay-upgrade / pairing-recovery, and the journaled pairing-recovery replay uses the new saveRecoveredPairingHost, so it no longer overwrites an edited row while a removed host still refuses an upgrade.
  • Made the post-edit reconnect rebuild the client: the edit screen now calls forceReconnect(hostId, { bypassRelayPreservation: true }) only when the address changed, with a new ForceReconnectOptions type; a rename-only save still preserves the session.
  • Renames and extraction: supervisor saveRelayEndpoint → saveRelayRouting; the host-list read-modify-write queue moved to host-list-mutation-queue.ts; the recovery recording adapter's saveHost → saveRecoveredPairingHost.
  • Re-recorded the RPC recording corpus: baseline repins, the pairing family's adapterSha256, and the four relay.direct-upgrade bodies (a relay-paired profile no longer carries direct-primary).

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

Comment thread mobile/src/transport/client-context.tsx Resolved

@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 in the merge delta — the prior inline finding still stands.

Reviewed changes

  • Merged main into the branch: main's independently-landed host-list-mutation-queue.ts, pairing-relay-host.ts, and derived name identity (mergeHostNameIdentity / withPersonalName) were adopted and the branch's near-duplicates dropped. The relay-only routing fix survives — pairing-relay-host.relayHost builds through withRelayRouting, the pairing-recovery replay still calls saveRecoveredPairingHost, joinHostCatalogCredentials still derives direct-primary from the stored row, and the edit screen still passes bypassRelayPreservation (now alongside main's personalName).
  • Re-recorded the RPC goldens: baseline repinned to the merge commit, with the relay-only endpoint change still reflected in the relay.direct-upgrade bodies.

The bypassed-reconnect finding from the previous review is unchanged by this merge: openHostClientEntry still prefers primedHosts, and forceReconnect still does not invalidate that entry.

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

…rite

`persistRelayHost`'s writer parameter was still called `saveHost` even though its
only production caller passes `saveExistingHostRelayUpgrade`, which deliberately
leaves the stored row alone. A future caller reading that name could pass a
full-profile writer and reintroduce the stale-snapshot overwrite this branch fixes.
Renamed it and the direct-upgrade dependency to `saveRelayUpgrade`.

`persistSupervisedRelay`'s `stopped` flag also carried a `= false` default that no
caller used, making the guard skippable by omission; it is now required.

Also documents the `pairing-recovery` persist mode's deliberate asymmetry with the
inline pairing commit - a journaled replay keeps the stored address because it
cannot date its snapshot against the row - and pins it with a test. Ordering the
two properly needs a written-at stamp on both sides, tracked in stablyai#22790.
The direct-upgrade mount adapter names its injected writer `saveRelayUpgrade`, so
`adapterSha256` moves on the four relay scenarios that mount it. No recorded body
changed: the delta is 787 x `baseline` plus 10 x `adapterSha256`, with no golden
added or removed.
@nwparker

Copy link
Copy Markdown
Contributor

Heads up @mmarabel — @nwparker has taken this over and pushed two more commits on top of your branch (nothing rewritten, no force-push). Second round of takeover review; the engineering was already sound, so this is naming and disclosure plus the CI gap.

  • refactor(mobile): name the relay persist dependencies for what they write — persistRelayHost's writer parameter and the direct-upgrade dependency were still called saveHost even though the only production caller passes saveExistingHostRelayUpgrade, which deliberately leaves the stored row alone; a future caller reading that name could pass a full-profile writer and walk straight back into the bug this PR fixes. Renamed both to saveRelayUpgrade. persistSupervisedRelay's stopped flag also had a = false default no caller used, which made the after-stop guard skippable by omission — it is now required.
  • Same commit documents and pins a real asymmetry the new pairing-recovery mode introduced: a journaled pairing replay no longer applies a re-pair's new address to an existing row, while the inline pairing commit still does. That is the right call (neither side records when its address was written, and losing the user's edit is the failure we are fixing), but it was undisclosed. It is now in the HostPersistMode doc comment, in the PR body's Why section, asserted by a new test, and the proper fix — a written-at stamp on both sides — is filed as mobile: a journaled pairing replay cannot tell a re-pair's new address from a user edit #22790.
  • test(mobile): re-record goldens for the renamed relay-upgrade writer — the rename moves adapterSha256 on the four relay scenarios that mount that adapter. Delta is exactly 787 × baseline + 10 × adapterSha256, no golden added, removed or otherwise changed.

Also: repository CI had never run on this PR — all three workflows were parked at action_required waiting on fork approval, so an 800-file diff had no independent verification. Approved them; PR Checks, Mobile Checks and PR test LoC all went green on af7034ea, and they are approved again on the new head.

Verified locally in mobile/: full vitest run (882 files, 9546 passed, 6 skipped), tsc --noEmit, the tests-typecheck ratchet, and oxlint clean. Each new test was confirmed to fail with its production change reverted.

Thanks for the original fix — the root-cause framing in it (the stored row carries no relay fields, so the old save could only lose data) was the right read and is what the whole thing rests on.

forceReconnect's address-edit path closed the live client but left the
primed HostProfile cache untouched, and openHostClientEntry prefers that
cache over loadHosts(). When the edit screen's best-effort re-prime fails
the rebuild dialled the address the user had just replaced.

Drop the cached profile on that path, and rename the option to the intent
it now drives on both counts.
…ed at

The replay kept the stored address unconditionally, so re-pairing a known
host at a new address lost that address whenever the pairing was
interrupted before the row was written. It could not do better: neither
the row nor the journal said when its address was written.

Record the row's address into the journal at capture, and apply the
pairing's address only while the row still holds it. A post-capture edit
still wins, and a journal from a shipped build carries no captured
address, so it keeps today's conservative behaviour.

Two writes that a failing relay loop repeated on every retry now
short-circuit: persistHost hands back the list it read when no row field
moved, and saveMobileRelayHostRouting returns the overlay list unchanged
when the resolution repeats the stored routing.

The persist policy moves to host-persist-policy.ts, and the credential
cleanup scheduling and device-token cache to modules of their own, so
host-store.ts stays under its line budget without a lint suppression.
@nwparker

Copy link
Copy Markdown
Contributor

@mmarabel heads up — @nwparker has taken this over and pushed three commits on top of yours. Nothing of yours was rewritten or force-pushed.

What changed since 1cae2d1b:

  1. forceReconnect now drops the primed host profile too (client-context.tsx). This was a real hole in the reconnect fix and pullfrog caught it: the bypass path closed the live client but left primedHostsRef alone, and openHostClientEntry prefers that cache over loadHosts(). When the edit screen's best-effort re-prime fails, the "bypass" rebuild dialled the address the user had just replaced. The option is renamed savedAddressChanged because it now drives both consequences, and a new client-context.test.ts case asserts the reopen reads the edited row.

  2. The journaled pairing replay can now date its own address (host-persist-policy.ts, mobile-relay-pairing-journal.ts, pre-profile-pairing-coordinator.ts). Rather than leave the re-pair asymmetry as a disclosed limitation, the journal records the stored row's address at capture and the replay applies its own address only while the row still holds it. That closes mobile: a journaled pairing replay cannot tell a re-pair's new address from a user edit #22790 without the stored-row schema change the issue proposed — comparing values beats comparing clocks. Old journals carry no captured address and keep the conservative behaviour.

  3. Two repeated writes short-circuit. persistHost hands back the list it read when no row field moved, and saveMobileRelayHostRouting returns the overlay list unchanged when a relay resolution repeats the stored routing — both of which the reporter's failing relay loop hit on every retry.

host-store.ts crossed its 300-line budget, so instead of a max-lines suppression it shed three modules: host-persist-policy.ts, host-device-token-cache.ts and unpaired-host-cleanup-scheduling.ts.

Verified in mobile/: pnpm test 882 files / 9554 passed, pnpm typecheck, pnpm typecheck:tests, pnpm check:tests-typecheck, oxlint, oxfmt --check. Every new assertion was confirmed to fail with its production change temporarily reverted. The goldens needed no further repin — none of the corpus-provenance paths moved.

Thanks for the original fix — the diagnosis and the shape of it were right, and it is the root fix rather than a patch.

@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

  • Retired the primed-profile staleness on a bypassed reconnect: ForceReconnectOptions.bypassRelayPreservation became savedAddressChanged, and that branch now drops the primed host profile before openEntry, so a rebuild after an address edit falls back to the authoritative loadHosts() even when the edit screen's best-effort re-prime failed. A new client-context.test.ts case pins it.
  • Converged the journaled pairing replay with the inline commit: the journal now records storedEndpointAtCapture, and pairing-recovery applies the re-paired endpoint only while the row still holds that captured value, preserving any post-capture address edit.
  • Stopped rewriting unchanged host data: persistHost returns the read list when nextStoredRow leaves the row unchanged, and saveMobileRelayHostRouting compares serialized schema outputs before writing, so a failing relay loop's repeated resolution no longer rewrites storage.
  • Extracted the relay-persistence helpers (host-persist-policy.ts, host-device-token-cache.ts, unpaired-host-cleanup-scheduling.ts) and added tests for the new replay policy, the capture recording, and the no-op writes.

ℹ️ PR description still describes the pre-b93c00bd replay asymmetry

The body's "One asymmetry, chosen on purpose" section says the journaled replay "does not" take the address the desktop advertised, and that making the two sides agree needs a written-at stamp filed as #22790. b93c00bd now does exactly that: the journal records storedEndpointAtCapture and nextStoredRow applies the paired address when the row is unchanged. A reviewer reading the description would expect the old behavior.

Technical details
# PR description contradicts the new pairing-recovery behavior

## Affected sites
- PR description, "Why" → "One asymmetry, chosen on purpose" — states the replay keeps the stored address and that dating both sides is a separate PR (#22790).
- `mobile/src/transport/host-persist-policy.ts:36-43` — `nextStoredRow` now returns `{ ...current, endpoint: incoming.endpoint }` for `pairing-recovery` when `capturedStoredEndpoint === current.endpoint`.
- `mobile/src/transport/mobile-relay-pairing-journal.ts:46` — `storedEndpointAtCapture` is the new one-sided stamp.

## Required outcome
- The description reflects that a journaled replay now applies the re-paired address when the row has not moved since capture, and that #22790 only covers the remaining full ordering (the inline commit still takes the offer address unconditionally).

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

@nwparker nwparker 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.

Approved to run CI. Taken over and reworked by @nwparker; findings addressed and independently re-verified.

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Thanks @mmarabel! This PR's investigation found all three bugs behind #20141, and its tests shaped the fix. We landed a reworked version in #22956, which credits you as a co-author. It gives each host field a single writer, so relay code can only save relay routing and can no longer write a whole host profile back.

The pairing-journal change for #22790 isn't included. It adds a field to a strict journal schema that older builds would throw away, for a rare case, so we left it to be decided separately. #22790 stays open for that.

Closing in favour of #22956.

@Jinwoo-H Jinwoo-H closed this Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants