Skip to content

fix(desktop): commit cross-server handoffs atomically - #4054

Merged
reachjalil merged 2 commits into
devfrom
fix/atomic-control-plane-handoff
Sep 3, 2026
Merged

reachjalil merged 2 commits into
devfrom
fix/atomic-control-plane-handoff

Conversation

@reachjalil

Copy link
Copy Markdown
Member

Problem

A user can accept a Desktop sign-in, organization, install-link, or enterprise handoff for control plane B while control plane A is still active — and end up with a partially switched Desktop state. Concretely:

  • B's bearer token could become the active credential while A's bootstrap origin stayed persisted on disk.
  • An organization selected on A could silently carry into B when B's exchange did not return one.
  • The renderer published sign-in success before B's bootstrap was durably committed, so a bootstrap write failure or an app exit right after "success" left a hybrid enrollment.
  • A late exchange result from an older handoff attempt could overwrite a newer one, and two concurrent attempts could interleave their persistence steps.

Root cause

The handoff sequence updated its pieces independently: exchangeHandoffAndSignIn wrote the token and organization to session storage synchronously, while the bootstrap origin was persisted by a fire-and-forget write (void setDenBootstrapConfig(...).catch(() => undefined)) inside writeDenSettings, and the denSessionUpdated success event fired before either was confirmed. Enterprise activation stamps and consumed-grant cleanup were separate follow-up bootstrap writes after the session had already switched. Nothing versioned attempts, so late or concurrent exchanges raced. The exchange client was supplied redundantly by each caller, so the exchange target and the persisted destination were only coincidentally the same.

Transaction boundary

exchangeHandoffAndSignIn is now a single enrollment transaction with explicit phases:

  1. Preparation — resolve the expected destination once (resolveDenBaseUrlsForDestination, which prefers the API base the destination publishes in its runtime config — the same source the bootstrap commit uses) and number the attempt.
  2. Validation — exchange the grant with a client constructed from that resolved destination, so the grant can only be sent to, and the credential can only come from, the origin this transaction would persist. The caller-supplied client option is removed.
  3. Durable commit — persist the destination bootstrap (folding in requireSignin, enterprise activation stamps, and consumed-grant cleanup that used to be follow-up writes), then re-read and confirm the committed bootstrap is the intended destination. On divergence, restore the previous bootstrap.
  4. Activation — one writeDenSettings call publishes origin, token, and organization together (stamping the issuing origin next to the token via the fix(desktop): keep bootstrap and retained Den sessions origin-coherent #4050 invariant).
  5. Publication — only after the durable commit and activation, broadcast denSessionUpdated: success.

Commits are serialized through a module-level queue, and each attempt carries a generation number checked at the commit boundary.

Invariant

A cross-server handoff's origin, credential, organization, and enrollment generation become active together, or none of them do. The current enrollment remains authoritative until the candidate has been validated against the expected destination, durably persisted, confirmed as the committed bootstrap, promoted to the active session, and only then published as successful.

Solution details

  • Single commit point: the durable bootstrap write happens before any active-session write; the session write is one synchronous batch; success is published last.
  • Rollback: a persistence failure before activation leaves the complete previous enrollment untouched (nothing was written); a read-back mismatch or activation failure restores the previous bootstrap.
  • No cross-origin organization carry-forward: a same-origin handoff with no exchange organization keeps the stored one (unchanged behavior); a cross-origin handoff without a destination organization commits none.
  • Stale-attempt protection: a late result from a superseded attempt returns stale: true, activates nothing, and publishes nothing; concurrent A→B / A→C attempts cannot cross fields — the newest attempt wins whole.
  • Consumed one-time grants: failures after the grant reached the destination return grantConsumed: true; the deep-link and prepared-bootstrap entry points stop retrying spent grants (the prepared-bootstrap path strips the spent grant from disk best-effort) — recovery is a fresh handoff link.
  • Crash windows: the interval between the durable bootstrap commit and the session write is covered by the session-origin coherence gate from fix(desktop): keep bootstrap and retained Den sessions origin-coherent #4050 — an interrupted commit resumes as signed-out-at-the-destination, never as a hybrid.

Preservation

  • Same-origin handoffs (including every eval boot sign-in) work unchanged; the boot sign-in in the new spec is itself a same-origin handoff.
  • One-time grants remain single-use — the spec replays a consumed grant and proves it fails without disturbing the committed enrollment.
  • Hosted, self-hosted, install-link, prepared-bootstrap, and enterprise activation flows all funnel through this one transaction; enterprise activation now commits its stamp atomically with the enrollment instead of after it.
  • Manual control-plane URL changes (saveControlPlaneUrl) keep their existing semantics; the transaction adopts the same persist-then-activate order that path already modeled.
  • Local-only Desktop behavior is unaffected; web (non-desktop) deployments keep their storage-backed base-URL behavior.

Proof

Two deterministic Den identities (two independent local Den servers, orgs "Handoff Atomic A"/"Handoff Atomic B") and an injected bootstrap-persistence failure (the Electron profile root is made read-only so the shell's atomic bootstrap.json write fails).

Command Result
pnpm --filter @openwork/app test (890 tests, incl. 18 handoff transaction tests + the 13 #4050 origin-coherence tests) Passed for all handoff/den suites; 7 unrelated failures pre-exist on base dev in this environment (verified by an A/B run on the clean base: identical set, e.g. missing window.matchMedia)
pnpm --filter @openwork/app typecheck Passed
pnpm --filter @openwork/app build Passed
pnpm evals:e2e cross-server-handoff-atomic-commit --local at the exact head Passed (lane: local; the spec requires local placement because the persistence-failure injection needs local filesystem control, matching first-run-bootstrap-contract's gating)
pnpm --dir evals run lint:layers Passed
pnpm evals:e2e first-run-bootstrap-contract --local Failed identically on the clean base in this environment (timeout waiting for the injected 429 to be observed); A/B verified pre-existing, not introduced by this change

Testkit spec: evals/specs/cross-server-handoff-atomic-commit.e2e.test.ts proves, in one journey against the real app: same-origin enrollment to A → injected bootstrap-persistence failure leaves the complete A enrollment (bootstrap file, token, organization, session origin) active with an error and no success event → a fresh grant commits B's origin, credential, and organization together (file + storage + session-origin all B) → the consumed grant cannot be replayed → a restart restores the complete B enrollment.

Unit/integration (apps/app/tests/den-handoff.test.ts, 18 tests) covers the full matrix: atomic cross-origin commit, no org inheritance, persistence-failure rollback with no success publication and no credential exposure (exchange requests asserted to reach only the destination API host — the negative network half), read-back origin mismatch rejection with durable rollback, stale-attempt rejection, concurrent-attempt isolation, interrupted-commit restart state (never hybrid), committed-commit restart restore, desktop-initiated org deferral, and log capture asserting grants/tokens never appear in diagnostics.

Negative proof

  • With bootstrap persistence failing, the control action returns an error, the bootstrap file on disk still names A, the token/org/session-origin in storage are A's, and the recorded denSessionUpdated stream contains error and no success (e2e + unit).
  • A stale attempt returns stale: true and the persisted state is entirely the newer attempt's — asserted field-by-field (unit).
  • In the failure path, every credential-bearing request went to the destination API host only; nothing was sent to A (unit assertion over the recorded request log), and captured console output contains neither the grant nor either token.

Dependency statement

Independent. The bootstrap/session-origin coherence work landed on dev as #4050 while this change was in flight; this PR is rebased onto it and reuses its sessionOrigin invariant for the crash-window guarantee instead of duplicating a second marker (an earlier draft's separate enrollment marker was removed during reconciliation). No stacked base or special merge order is required.

Risk and rollback

Scope exclusions

This PR does not redesign general Connect policy reconciliation (see #4052), does not change release or deployment behavior, and does not alter Den-side grant issuance.

@vercel

vercel Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
openwork-app Ready Ready Preview Aug 28, 2026 5:02am
openwork-den Ready Ready Preview Aug 28, 2026 5:02am
openwork-den-worker-proxy Ready Ready Preview Aug 28, 2026 5:02am
openwork-diagnostics Ready Ready Preview Aug 28, 2026 5:02am
openwork-landing Ready Ready Preview, v0 Aug 28, 2026 5:02am

@reachjalil

Copy link
Copy Markdown
Member Author

Test evidence — a-cross-server-handoff-commits-origin-credential-and-organization-atomically-or- — 0/0 screenshots passed · 5 assertions

✅ 0/0 screenshots passed · 5 assertions · 5 expectations passed · 0 failed · 0 pending

screenshots not uploaded (no BLOB_READ_WRITE_TOKEN)

ℹ️ ASSERTION — 1. Same-origin handoff enrolled control plane A

The app signed in to Handoff Atomic A with the enrollment origin stamped to A.

  • ✅ PASS Same-origin handoff enrolled control plane A — The app signed in to Handoff Atomic A with the enrollment origin stamped to A.

ℹ️ ASSERTION — 2. Bootstrap persistence failure left the complete A enrollment active

With bootstrap writes failing, the B handoff was rejected: the bootstrap file, token, organization, and enrollment origin all still belong to A, and no success state was published.

  • ✅ PASS Bootstrap persistence failure left the complete A enrollment active — With bootstrap writes failing, the B handoff was rejected: the bootstrap file, token, organization, and enrollment origin all still belong to A, and no success state was published.

ℹ️ ASSERTION — 3. The retried handoff committed B atomically

Origin (bootstrap file), credential, organization (Handoff Atomic B), and enrollment marker switched to B together.

  • ✅ PASS The retried handoff committed B atomically — Origin (bootstrap file), credential, organization (Handoff Atomic B), and enrollment marker switched to B together.

ℹ️ ASSERTION — 4. A consumed one-time grant cannot be replayed

Re-exchanging the spent grant failed and the committed B enrollment was untouched.

  • ✅ PASS A consumed one-time grant cannot be replayed — Re-exchanging the spent grant failed and the committed B enrollment was untouched.

ℹ️ ASSERTION — 5. Restart restored the complete B enrollment

After a relaunch, the app came back signed in to Handoff Atomic B with the B credential and enrollment origin.

  • ✅ PASS Restart restored the complete B enrollment — After a relaunch, the app came back signed in to Handoff Atomic B with the B credential and enrollment origin.

Test run created 2026-08-24T23:50:58.754Z · Source: evals/results/test-runs/2026-08-24T23-50-58-753Z-a-cross-server-handoff-commits-origin-credential-and-organization-atomically-or/test-run.json · Repro: pnpm --dir evals artifacts:publish -- --pr 4054 --test-run 2026-08-24T23-50-58-753Z-a-cross-server-handoff-commits-origin-credential-and-organization-atomically-or

Comment thread apps/app/src/app/lib/den-handoff.ts Resolved
Comment thread apps/app/src/app/lib/den-handoff.ts Resolved
A Desktop handoff for control plane B could partially succeed while control
plane A stayed active: the bearer token, active organization, durable
bootstrap origin, and renderer success state each transitioned independently,
so a bootstrap write failure, app exit, concurrent attempt, or missing
destination organization could leave a hybrid enrollment (B's token active
against A's persisted origin, A's organization leaking into B, or UI success
published before the durable commit).

Make the handoff a single enrollment transaction in exchangeHandoffAndSignIn,
which every entry point (deep link, pasted code, control action, prepared
bootstrap, enterprise activation) already funnels through:

- resolve the destination once (including its published runtime-config API
  base) and construct the exchange client from it, so the grant can only be
  sent to — and the credential can only come from — the origin that will be
  persisted; the redundant caller-supplied client option is removed
- persist the destination bootstrap durably, then confirm the committed
  bootstrap is the intended destination before anything becomes active,
  folding enterprise activation stamps and consumed-grant cleanup into the
  same commit instead of separate follow-up writes
- publish origin, token, and organization in one write; an organization never
  carries into a different origin unless the destination returns one
- roll back to the previous coherent enrollment when persistence, read-back
  confirmation, or activation fails, and report consumed one-time grants as
  non-retriable so entry points stop replaying spent grants
- serialize commits and reject late results from superseded attempts so
  concurrent handoffs cannot interleave or cross their fields

Crash windows between the durable bootstrap commit and the session write are
covered by the session-origin coherence gate introduced in #4050: the
transaction's single activation write stamps the issuing origin, so an
interrupted commit resumes as signed-out-at-the-destination, never as a
hybrid of two control planes.
…off grant

A destination's runtime-published denApiUrl is adopted for the one-time
handoff exchange only when it is same-origin with the destination web
origin or its deterministic hosted API sibling; every other published
value keeps the exchange on the destination's own /api/den proxy.

Cross-origin handoff commits now clear the previous origin's enterprise
activation stamp explicitly, so a new control plane can never inherit an
activation recorded against a different Den base URL.

@diff-warden diff-warden 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.

Warden security clearance: clear. No blocking findings (security or desktop↔den sync) in this diff (69347c0b5552b45250fc87f0ffd9217dfe20a323). Automated clearance satisfies the required-review gate only — a human still reviews and merges. Analysis run

@reachjalil
reachjalil merged commit 3e425fa into dev Sep 3, 2026
18 checks passed
reachjalil pushed a commit that referenced this pull request Sep 3, 2026
…ct snapshot and trusted inventory

#4054 added evals/specs/cross-server-handoff-atomic-commit.e2e.test.ts
without mapping it, so the PR lane on dev fails two governance specs for
every PR:
- spec-impact: "every E2E spec is mapped to an implementation contract or
  explicitly allowlisted"
- spec-quarantine: "the enabled E2E set equals the evidence-backed
  inventory" (38 vs 37)

Map it to desktop.onboarding-cloud-auth (which already owns
den-auth-provider.tsx and forced-signin-page.tsx), add den-handoff.ts to
that contract's implementation, and list the spec in expectedEnabled.
Control: the same two specs fail identically on a clean origin/dev
(3e425fa) checkout.

(cherry picked from commit 1ab90db)
yomgui added a commit that referenced this pull request Sep 3, 2026
…K smoke (#4375)

* test(evals): register the cross-server handoff e2e spec in the contract snapshot and trusted inventory

#4054 added evals/specs/cross-server-handoff-atomic-commit.e2e.test.ts
without mapping it, so the PR lane on dev fails two governance specs for
every PR:
- spec-impact: "every E2E spec is mapped to an implementation contract or
  explicitly allowlisted"
- spec-quarantine: "the enabled E2E set equals the evidence-backed
  inventory" (38 vs 37)

Map it to desktop.onboarding-cloud-auth (which already owns
den-auth-provider.tsx and forced-signin-page.tsx), add den-handoff.ts to
that contract's implementation, and list the spec in expectedEnabled.
Control: the same two specs fail identically on a clean origin/dev
(3e425fa) checkout.

* test(evals): route cross-server handoff helpers through testkit

The same newly added e2e spec also broke the eval-runner layer ratchet by
importing @openwork/behaviors and @openwork/hosts directly. Re-export its
four required runtime helpers from @openwork/testkit and import all eval
primitives and types through that package. This removes the two new
specs-use-testkit-only violations instead of expanding the 206-entry known
violation baseline.

Proof: pnpm test:eval-runner passes 225/225; lint:layers reports zero new
dependency violations.

* test(app): isolate the SDK smoke engine from user and CI runner state

The app SDK smoke inherited the runner's real OpenCode database, plugins,
MCPs, and project config even though it only verifies core SDK calls. On both
CI runners /global/health waited five minutes on unrelated setup, then
path.get hit a vanished process; rerunning reproduced it exactly.

Give this one smoke process a temporary database and minimal config, disable
external setup, and remove the temp directory after close. A PR-lane witness
runs the real script and asserts health, path.get, session operations, and
SSE all complete without an error step. Locally it completes in 4.6 seconds
instead of failing after five minutes.

* test(app): isolate every SDK smoke engine by default

The first isolated script passed in CI, but session-switch then inherited the
runner's real config and failed after the same five-minute wait. Move the
hermetic defaults into spawnOpencodeServe so every core smoke process gets a
temporary database and minimal config. browser-entry opts out of pure config
because it deliberately tests a project command, while retaining the private
database. Cleanup runs even when the child exits early.

The agent-first witness now executes the exact app test:e2e package command:
core SDK calls, session switching, filesystem operations, and browser-entry.

This branch was successfully deployed

5 active (1 outdated) deployments
Preview – openwork-den — 69347c0b Deployed Aug 28, 2026 by vercel[bot]
Preview – openwork-landing — 69347c0b Deployed Aug 28, 2026 by vercel[bot]
Preview – openwork-app — 69347c0b Deployed Aug 28, 2026 by vercel[bot]
Preview – openwork-diagnostics — 69347c0b Deployed Aug 28, 2026 by vercel[bot]
Preview – openwork-den-worker-proxy — e16262e0 Deployed Aug 24, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants