fix(viewer): give each collab join its own attempt token
Defect
startCollab (apps/viewer/src/store/slices/collabSlice.ts) awaits about a dozen times between "join" and "session live". It recognised its own continuation by collabRoomId === roomId, which is a room key, not an attempt token. The code admitted it ("cannot tell a rejoin of the SAME room from this join still being live").
A Leave + rejoin of the same room, or a second start of it, sets the same id, so the abandoned first attempt:
- passed every re-check;
- wired its remote-apply / annotation / reconstruct listeners into the ~12 module-level singletons the live join was using (
docApi,placementApi,placementApplied*,geomApiRef,makeBlobStore,cachedBlobStore,annotationDocApi,remoteApplyTeardown,recipientLiveTeardown,annotationInboundTeardown); - committed a second session over the live one.
If the first attempt failed to start instead, its catch cleared the live join's collabRoomId / collabRole / collabSelfToken. On the stale path, the else branch also reset the live join's collabConnecting.
Concrete scenario
- Click Share. The owner join is parked waiting for relay sync.
- Click Leave, then Share again on the same room.
- The first join's sync lands. It passes
collabRoomId === 'room-1'and commits its own session (collabSession.clientId= the first session's), and the rejoin later overwrites it. Two sessions are wired, one of them leaked.
Variant: the first join's createCollabSession rejects after the rejoin started, and the user is silently kicked out of the room they just rejoined (collabRoomId → null).
Fix
- New
apps/viewer/src/lib/collab/session-attempt.ts.beginCollabAttempt(roomId)returns aCollabAttemptthat owns everything one join wires: the doc helpers (built once bycollabAttemptApis), the placement render bookkeeping, the blob-store factory and promise cache, the cleanups and the session.attempt.liveis the only currency check instartCollab.attempt.adopt(session)disposes a session that arrives for a retired attempt.attempt.onRetire(cleanup)runs at once if the attempt has already retired. That replaces the #3016ownLiveTeardownbookkeeping.
stopCollabretires the live attempt. A session committed without an attempt (test seeding) is still disposed.- The mirror actions read the live attempt's helpers instead of module globals.
runOwnerSeedreturnsnullfor an abandoned join that throws, instead of logging and reporting a failure nobody reads. The "abandoned" case is what happens once #9532 makeswhenSyncedreject on dispose.- The recipient reconstruct
catchreturns quietly for a retired attempt. With #9532, a Leave before the room synced makesawait session.whenSyncedreject, and the catch used to log a misleadingmodel reconstruction failed: CollabSessionDisposedError. - The fire-and-forget geometry shares in
mirrorEntityCreateandmirrorEntityGeometrycheckattempt.livein three places: after the blob-store await, after the upload, and at the top of thecatch. A Leave or rejoin during an upload used to surface "could not be shared with the room" for a room the user had left, or in the new join's state. With #9532, the retired session'stransactthrowsCollabSessionDisposedError, and afterretire()the blob store always rejects, so thecatchalways ran. scripts/check-collab-room-model-target.test.mjs: the mutation anchors follow the newmirrorEntityRemoveshape. The RED case still deletes the realroomStoreFor(get(), modelId)call and fails the guard, and the guard itself still finds every required call.collabSlice.tsshrinks 1312 → 1201 lines; the allowlist budget is lowered to match.
Independent of #9532 (collab package lifecycle). With both merged, the stale continuation's await session.whenSynced rejects promptly instead of parking forever.
Tests
collabSlice.same-room-rejoin.test.ts(new), driving the realstartCollabthrough the session-race loader hook:- the stale first join resuming after a same-room rejoin commits nothing, and the rejoin's session goes live;
- the stale first join's failed start leaves the rejoin's room, role, token and connecting flag alone;
- the stale first join whose session arrives after the rejoin disposes it and returns.
- The hook gains
__collabCreateHoldto park or fail a singlecreateCollabSessioncall. owner-seed.test.ts: an abandoned join's throwing seed reportsnulland stamps no interrupted marker.collabSlice.leave-during-upload.test.ts(new) uses the realstartCollab,mirrorEntityGeometry/mirrorEntityCreateandstopCollab. A Leave while the upload is in flight raises nocollabGeometryNotice.- Verified on a local merge of #9532 + #9554: with the
attempt.livegates, 2/2 pass. With the gates removed, 0/2 pass, and the log shows[collab] mirror resize geometry failed: CollabSessionDisposedError … (transact), i.e. exactly the post-Leave toast. - On #9554 alone the test passes either way: without #9532, the retired session still accepts the write, so no error is raised.
- Verified on a local merge of #9532 + #9554: with the
collabSlice.leave-during-join-race.test.tsnow lets the session's own sync land before Leave. Leave now disposes the in-flight session, and before #9532 a provider disposed before its first sync never settleswhenSynced(the very hang that test's message names).
On the original slice, the new tests fail for the stated reasons: actual: 3794919734, expected: null for the committed stale session, and null !== 'room-1' for the stale failure.
Commands
All test commands ran under systemd-run --user --scope -p MemoryMax=8G -p MemorySwapMax=0; tsc used 12G and lint 24G. Results are for head c49c55a9.
- Collab test family (55 files: every
collabSlice.*,lib/collab/*,collab-publish, presence, and every test importing the slice): - Typecheck:
tsc --noEmitpasses for bothapps/viewerandapps/viewer-embed(tests included). node --test scripts/*.test.mjs: 2181 tests, 2176 pass, 2 fail, neither from this change.- All 6
check-collab-room-model-targettests pass, andnode scripts/check-collab-room-model-target.mjsreports OK (10 entity actions self-gated, 15 call sites bound tomodelId). - The 2 failures are local-environment only.
viewer-embed unused-locals baselinefailed because embed didn't compile against my stale local@ifc-lite/collabdist; after rebuilding that dist, embed compiles and measures 182 = baseline. The smlib native-worker "poison deadline" timing test is unrelated.
- All 6
- Lint:
- Every
pnpm lintstep passes: i18n-literals, jsx-a11y, type-scale, andcheck-lint-ran(no errors). - unused-locals:
apps/vieweris within baseline andapps/viewer-embedmeasures 182 = baseline.cache/create/mutationscan't be compiled here after the rebase (stale local dists that need a wasm rebuild), so CI's lint job is the check for those.
- Every
- Module size:
node scripts/check-module-size.mjspasses, with collabSlice lowered 1312 → 1201. - Source-text assertions:
node scripts/check-source-text-assertions.mjspasses. - Revert oracle (local, base origin/main): OBSERVED.
Mutation table
The tests run against each mutant were the rejoin, leave-during-join, leave-after-reconstruct, seed-phase, session-failure and owner-seed tests.
| Guard removed | Result |
|---|---|
if (!attempt.adopt(session)) return | killed (rejoin: session arrives after rejoin) |
adopt disposing for a retired attempt | killed (same test; the leaked session hangs the file) |
catch gated on current() | killed (stale failed start) |
post-seed if (!current()) return | killed (leave-during-join, stale rejoin) |
onRetire immediate run when retired | killed (leave-after-reconstruct ×2) |
stopCollab → attempt.retire() | killed (leave-after-reconstruct) |
retire() disposing the session | killed (three files hang) |
runOwnerSeed abandoned early return | killed (owner-seed) |
| attempt.live gates on the geometry-share paths | killed on the #9532 + #9554 merge (leave-during-upload, both cases). Not observable on #9554 alone; see Tests. |
Two first-draft guards survived: current() checks inside the presence and status listeners. I deleted them. To correct my earlier wording: those listeners are registered right after adopt, before the session is committed, not only by a committed attempt. Deleting the guards is still safe for two reasons:
- Every return after
adopthappens on a retired attempt, whose sessionretire()has already disposed. stopCollabdisposes the session before resettingcollabPeers/collabStatus, so a late emit is overwritten.
Defence in depth once #9532 lands. Two guards are mutation-killed today but become redundant once #9532 merges, because a disposed session's whenSynced then rejects and its writes throw:
- the
if (!attempt.adopt(session)) returnearly return; - the
liveAttempt === thisclear inretire().
I've kept both deliberately, so this PR is correct without #9532 and the stale path stays short-circuited.
Not verified
- No browser run. Covered by the node test harness (real
@ifc-lite/collab, fake-indexeddb) only.
Out of scope, pre-existing
- Existing local annotations are never pushed when sharing. The loop in
startCollab(~941-952) callsmirrorAnnotationUpsertbeforecollabSessionis committed, so every call is a no-op. This change leaves that behaviour as it was.
🤖 Generated with Claude Code
Summary by CodeRabbit
- Bug Fixes
- Leaving or rejoining a collaboration room while a connection is starting no longer lets an earlier attempt overwrite the current room or connection state.
- Inactive connection attempts are cleaned up, and sessions created by them are discarded.
- Uploads and room setup from an inactive attempt no longer affect the active collaboration or mark it as interrupted.