Skip to content

fix(app): keep a v2 session's snapshot query alive across the routing-status flip on reload - #4797

Merged
yomgui merged 15 commits into
devfrom
e2e/v2-reload-owner-change-race
Sep 11, 2026
Merged

yomgui merged 15 commits into
devfrom
e2e/v2-reload-owner-change-race

Conversation

@yomgui

@yomgui yomgui commented Sep 10, 2026

Copy link
Copy Markdown
Member

Root cause

Out-of-cluster race observed by #4781 (run 1 of workspace-engine-upgrade, 1 in 3): after reload() on a v2 session, SessionSurface mounts under the v1 URL (engineV2ChatRouting starts false in use-workspace-route-state.ts), starts the owned snapshot read, and the chat-routing status then flips opencodeBaseUrl to /opencode2. sessionOwner changes, readOwnedSnapshotTarget throws "Session snapshot owner changed before the local read completed.", and because the snapshot query is keyed only on (workspace, session) with retry: false on the desktop loopback path, nothing ever refetched: the error card stuck over an empty transcript. draftScope flipping when denAuth.verifiedIdentity resolves has the same shape. Triage context: reports/e2e-red-2026-09-09/triage.md Cluster 1 → #4781 "Noticed, not touched".

A second wrinkle found while fixing: a bare invalidateQueries does not help here. TanStack's Query.fetch only honours cancelRefetch when state.data !== undefined; on a first load (exactly the reload case) it joins the doomed in-flight promise instead of cancelling it.

What changed

  • apps/app/src/react-app/domains/session/surface/session-surface.tsx: when sessionOwner changes under an unchanged snapshot query key, cancel the in-flight owned read and invalidate/refetch under the new owner. Key-changing navigations (different workspace/session) are untouched: they already fetch through the new key. No change to readOwnedSnapshotTarget: the owner check still protects against attributing a read to the wrong owner; the surface now reacts to it instead of dying.
  • apps/app/tests/session-snapshot-owner-flip.test.tsx (new): mounts the surface under /opencode in desktop-loopback mode using the real composeNativeSessionSnapshotWithRetry with injected operations (v1 404s, v2 answers) and a parked retry; flips props to /opencode2 while the read is parked; asserts the transcript renders from the v2 read, the query is success, no "owner changed" text, and endpoints read are exactly [/opencode, /opencode2]. Red on the unmodified surface with exactly error: Session snapshot owner changed before the local read completed. and only /opencode read; green with the fix.

This branch is stacked on origin/e2e/new-session-route-after-reload (#4781, which itself carries #4757) via merge commit ef4c88939, because workspace-engine-upgrade only reaches the reload steps once those land. After #4781 merges the diff reduces to the two commits ec1d2d1c4 (test) and 9038068bf (fix).

Proof (Daytona, single spec, OPENWORK_EVAL_REF pinned; each sandbox printed source verified ef4c88939b559342467ca163e87b4d3dc3ab5a98)

The race is intermittent, so the spec was run three times at ef4c88939, sequentially, one spec per run:

run pnpm evals:e2e workspace-engine-upgrade --daytona duration placement line
1 1 passed / 0 failed / 0 skipped 334 s {"command":"evals:e2e","lane":"e2e","daytona":true,"placement":"daytona","engine":"legacy","surface":"legacy",…,"passed":1,"failed":0,"skipped":0,"skips":[],"verdict":"passed"}
2 1 passed / 0 failed / 0 skipped 369 s same shape, "passed":1,"failed":0,"skipped":0,"verdict":"passed"
3 1 passed / 0 failed / 0 skipped 327 s same shape, "passed":1,"failed":0,"skipped":0,"verdict":"passed"

No "owner changed" text appears in any run log. All six Daytona sandboxes created by these runs were deleted by the runner (verified with daytona sandbox list).

Unit: bun test --isolate tests/opencode-session-native.test.ts tests/session-error-resilience.test.tsx tests/session-transition-controller.test.ts tests/session-snapshot-owner-flip.test.tsx → 59 pass / 0 fail. pnpm --filter app typecheck clean (before and after the stack merge).

Noticed, not touched

  • apps/app/tests/composer-editable-on-snapshot-error.test.tsx is already red on clean origin/dev (586c4100f): "Platform context is missing" from useNativeContextMenu → usePlatform when the transcript renders, i.e. SessionSurface grew a PlatformProvider requirement (and WorkspaceRunModeMenu a DesktopConfigProvider one, feat: choose workspace run modes from the composer #4293) without that test being updated. My new test wraps in PlatformProvider and mocks the run-mode menu; the old test needs the same.
  • Bun mock.module gotcha for anyone writing similar tests: mocking an already-imported module rewires its live bindings, so a mock that calls through namespace.fn recurses into itself and hangs act forever; bind the real function to a const before mock.module.
  • fix(app)/test: a New task after an engine upgrade reload lands on a session route #4781's own "Noticed" items (the seed.workspace adoption trap in the workspaceEngineUpgrade world) still stand.

…immediately

A freshly created session had no cached snapshot, so deriveSessionRenderModel
reported "switching" while the first snapshot round trip ran and the composer
disabled Run task. On Daytona that window is ~0.9 s and a click or Enter inside
it was silently dropped with the draft intact. Seed the snapshot cache from the
create response (stale, so the real fetch still runs as a background refresh).
…ad of wedging

A prompt_async answered with 5xx/408 is an uncertain admission (#4635), but
the hold it created could never end: the acceptance check treated absence as
no evidence, Stop refused while the admission was unknown, and the failure body
was dropped, so the person saw a paused composer with no explanation.

- Keep the settled response body on PromptAdmissionUnknownError and show it as
  the session error card right away; the hold still prevents any resend.
- readPromptAdmission: after the exact-message GET misses, list the idle
  conversation; when native lists it without the message the POST is settled
  and did not admit, so the drain receives admission_rejected and halts like
  any definite failure (explicit retry only, never an automatic resend).
- On release the pending row is removed and the submitted composer is kept as
  an unsent message to restore; on confirmed acceptance the stale failure card
  is cleared.
Lexical keeps one empty paragraph in an empty editor, which innerText reports
as "\n". readComposerState now drops that trailing line break so draftText
matches what the person sees; user.see("composer", { text }) already trimmed.
…ssion button

The sidebar button was renamed from "New task" to "New session" in #4491
(Sep 5) and the "new" scenario added in #4631 (Sep 8) still targeted the old
label, so it could never find the button. Same user action, current label.
…ace-engine-upgrade

Since #4577 the sidebar New session controls open the workspace's empty
New task composer at once and the session is created by the first send,
so waiting for a ses_ route on click never resolves. Re-express the three
sidebar steps: the click lands on the empty New task route without a
session surface and a prompt-ready composer; the send must land in a
session no earlier turn used (same claim shape as bench-openwork-app-v1
in #4738). Palette steps still create their session up front.
The empty New task composer creates its session on submit and hands the
prompt over through a scoped auto-send mark. The mark was keyed with the
workspace's default endpoint URL (always /opencode), while the session
surface under OpenCode v2 routing owns the session as /opencode2, so the
lookup missed and the prompt silently vanished: the person landed on an
empty new session. Key the mark with the endpoint that created the
session (createRouteSessionWithEndpoint), which is the URL the surface
will own it under.
The surface mounts under the v1 URL before chat routing resolves; the owned
read 404s, parks for its retry, and the routing flip changes the owner while
it is in flight. The read rejects with 'Session snapshot owner changed' and
the (workspace, session) query never refetches, so the transcript stays empty.
The snapshot query is keyed on (workspace, session) with retry off on the
desktop loopback path. When chat routing resolves to /opencode2 after boot
(or the draft scope resolves once identity verifies) while the owned read is
in flight, the read rejects with 'Session snapshot owner changed' and nothing
refetched, leaving the error card over an empty transcript. Cancel the doomed
read and refetch under the new owner; a bare invalidate would only join the
in-flight promise because the first load has no data yet.
@vercel

vercel Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Deployment Actions Updated
openwork-app Ready Ready Preview Sep 11, 2026 2:45am UTC
openwork-landing Ready Ready Preview, v0 Sep 11, 2026 2:45am UTC
2 Skipped Deployments
Project Deployment Actions Updated
openwork-den Ignored Ignored Preview Sep 11, 2026 2:45am UTC
openwork-diagnostics Ignored Ignored Preview Sep 11, 2026 2:45am UTC

@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Warden review summary — Clear

Native findings: 0. Blocking policy matches before consolidation: 0. Full finding text remains in Warden's native checks and review threads. This comment retains only native IDs, severity, skill attribution, and safe locations. Analysis run

Reported trigger coverage (not proof of complete repository or context coverage): diff-security-review (15744 ms), confidentiality-review (11267 ms), desktop-den-sync-review (21483 ms).

Blockers

  • None.

Advisories

  • None.

Needs recheck

  • None.

Observed review-thread metrics

  • Unique observed run attempts in retained window: 3
  • Distinct heads in retained window: 3
  • Current unresolved Warden threads: 0 of 0 observed
  • Observed resolved/unresolved transitions in retained snapshots: 0 / 0
  • First observed resolved/unresolved (state at first collection, not event time): 0 / 0
  • Precision: unavailable (no adjudications; no TP/FP values are inferred)
  • Observation window: 3/20 run attempts retained; truncated: false
  • Transition snapshot: 0/0 current attributed threads retained (limit 500); truncated: false

Thread states are read-only collection snapshots. These metrics are neither lifetime totals nor exact resolution times, and this summary is not clearance authority.

diff-warden[bot]
diff-warden Bot previously approved these changes Sep 10, 2026

@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 (ef4c88939b559342467ca163e87b4d3dc3ab5a98). Automated clearance satisfies the required-review gate only — a human still reviews and merges. Analysis run

@github-actions

github-actions Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Passed · 12/12 tests · 18/18 assertions · 8 images

Commit 7af859637899d7bb8442e777cbe9d97ae4248836 · selected evidence

Open review report

@yomgui

yomgui commented Sep 10, 2026

Copy link
Copy Markdown
Member Author

Second witness for this fix from the Cluster 10 session (#4811): attachment-upload-loading-state on origin/dev @ 88b1eec4a (nightly 34444536682) fails its "existing chat" test after user.reload() with Session snapshot owner changed before the local read completed. on screen (engine=legacy, so this is the draft-scope/identity flip shape, not v2 routing). With origin/e2e/v2-reload-owner-change-race merged (sha 2d1209665): pnpm evals:e2e attachment-upload-loading-state --daytona → 2 passed / 0 failed / 0 skipped, no owner changed text in the log. Details in #4811.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Deploying openwork with  Cloudflare Pages  Cloudflare Pages

Latest commit: 152974e
Status: ✅  Deploy successful!
Preview URL: https://c2692762.openwork.pages.dev
Branch Preview URL: https://e2e-v2-reload-owner-change-r.openwork.pages.dev

View logs

diff-warden[bot]
diff-warden Bot previously approved these changes Sep 10, 2026

@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 (152974edb9c4be952274f2357a511e6201111a44). Automated clearance satisfies the required-review gate only — a human still reviews and merges. Analysis run

@yomgui

yomgui commented Sep 10, 2026 •

Copy link
Copy Markdown
Member Author

Resync onto dev after the #4757 / #4781 conflict resolution

Unit tests on the merged head — 1 red, semantic conflict with dev's #4838 (needs owner decision)

bun test --isolate tests/session-snapshot-owner-flip.test.tsx tests/opencode-session-native.test.ts tests/session-error-resilience.test.tsx tests/session-transition-controller.test.ts → 75 pass / 1 fail:

tests/session-snapshot-owner-flip.test.tsx:251
expect(readEndpoints).toEqual([v1BaseUrl, v2BaseUrl])
  received ["…/opencode", "…/opencode2", "…/opencode2"]   (one extra /opencode2 read)

Every other assertion in that test still holds (transcript renders from the v2 read, query success, error null, no "owner changed" text). Cause: since #4838 (4462762b4, merged today) SessionSurface opens through useOpeningSessionHistory — a preview read keyed by owner (["react-session-opening", owner]), and the uncapped snapshotKey query is only enabled once that preview settles (backgroundReady). So under /opencode2 there are now legitimately two reads (preview + full). I did not edit the expected list, because the more important consequence is that on the merged tree the test no longer discriminates: with the fix's cancelQueries(...).then(invalidateQueries) effect disabled, the test fails on exactly the same endpoint-list assertion and still passes the "owner changed"/success assertions — the owner-keyed preview absorbs the flip and the full query starts fresh under the new owner (disable→enable refetches a data-less query). The fix itself still typechecks and composes; whether it is still needed for the hasFullSnapshot/draftScope paths, and how to re-arm the test so it proves it (e.g. park the full read rather than the preview), is the author's call. Not a merge artefact: #4797's proven head ef4c88939 predates #4838.

E2E proof at the pushed head — Failed, pre-existing on the #4781 stack, not introduced here

OPENWORK_EVAL_REF=152974edb9c4be952274f2357a511e6201111a44 pnpm evals:e2e workspace-engine-upgrade --daytona (placement: daytona, source verified 152974edb…): 0 passed / 1 failed. Step 1 (palette chat after enabling v2) green; step 2 "a new chat in the selected existing workspace keeps the first message visible" fails at spec line 61 see(reply) after 90 s with a red CancelledError card, hi visible, no reply.

Clean controls (same command, fresh sandboxes each):

Net: this PR restores MERGEABLE and keeps its product fix intact, but its verdict at 152974edb is not Passed — unit test red (semantic, above) and the stacked spec red for an upstream reason. All Daytona sandboxes from the three runs were deleted by the runner (verified via daytona sandbox list).

@yomgui

yomgui commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Status: CONFLICTING again after dev 858414c41 — waiting on the #4781 owner call, not touching the file.

A fresh git merge origin/dev here conflicts only in evals/specs/workspace-engine-upgrade.e2e.test.ts: dev's #4869 (51a769f97) rewrote that spec wholesale, and this branch carries #4781's edits to the old spec body (0ad717693). AI's analysis on #4781 (comment) is that every commit unique to #4781 is superseded on dev (#4777 + #4869), so the honest resolution is to drop #4781's spec edits — but that is #4781's file and its owner's call (close as superseded vs. re-express). Once #4781 is either closed or resynced, this PR only needs git merge origin/dev (taking dev's spec) and a re-run of workspace-engine-upgrade; its own two commits (ec1d2d1c4, 9038068bf) are untouched by the conflict. Merge attempt aborted; worktree remains at 152974edb.

@yomgui

yomgui commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

Resynced with origin/dev — merge commit 7af859637899d7bb8442e777cbe9d97ae4248836 — MERGEABLE

Context: #4757 landed (ae69a0368); #4781 is being closed as superseded (its product fix by #4777, its spec change by #4869, both on dev). git merge origin/dev (at ea1ef4f5c) into this branch; no rebase, no amend, no force-push. Signed (G).

Conflict resolved

After the merge this branch differs from origin/dev only by its own two files: session-surface.tsx (+14) and tests/session-snapshot-owner-flip.test.tsx (+260).

Checks at 7af859637

  • pnpm --filter @openwork/app typecheck → clean.
  • bun test --isolate tests/session-snapshot-owner-flip.test.tsx tests/opencode-session-native.test.ts tests/workspace-routes.test.ts → 66 pass / 1 fail: a session snapshot read that loses its owner mid-flight is re-read under the new owner expects owner reads […/opencode, …/opencode2] and receives an extra …/opencode2 read.
    • Pre-existing on this PR's own head: same failure at 152974edb (this branch's earlier Merge origin/dev); green at ef4c88939 (the PR's original head). So a dev change merged in 152974edb added a second read under the new owner — very likely perf(chat): prioritize visible thread history and preserve scroll #4838's bounded opening-history preview (react-session-opening query) reading alongside the uncapped snapshot query. Owner call: either the assertion should count reads per query, or the re-read should dedupe. Not changed here (no assertion loosened).

@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 (7af859637899d7bb8442e777cbe9d97ae4248836). Automated clearance satisfies the required-review gate only — a human still reviews and merges. Analysis run

This branch was successfully deployed

4 active (2 outdated) deployments
Preview – openwork-landing — 7af85963 Deployed Sep 11, 2026 by vercel[bot]
Preview – openwork-app — 7af85963 Deployed Sep 11, 2026 by vercel[bot]
Preview – openwork-den — 152974ed Deployed Sep 10, 2026 by vercel[bot]
Preview – openwork-diagnostics — 152974ed Deployed Sep 10, 2026 by vercel[bot]
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.

1 participant