feat(viewer): store run slot + useAsyncRun primitives; scan detection on the run slot
Implicit-state-machines plan, section 2 (Phase 0 primitives), items 1, 2, 5 and 6. The pilot migrates scan detection.
What this adds
lib/runs/run-slot.ts: a store-level run slot. The job's record lives in the store, and the record is the ownership. A lease is current while the store holds {kind:'running', runId: <its id>}.
slot.run(owner, async (lease) => R, { toError, scopeIsCurrent? })is the default way to start a run. A return succeeds, anAbortError(isAbortError) cancels, and any other throw fails throughtoError. It never rejects, so a fire-and-forget caller cannot leave a runrunningor an unhandled rejection behind.begin(owner)is the manual form. It returnsLease {runId, signal, isCurrent(), progress(), succeed(), fail(), cancel(), cancelReason()}, and every method is a no-op once the lease is stale.- Anything that writes the record ends the lease and aborts its signal: a newer run (supersede), a cancel, or a
defineSliceTeardownarm returning{kind:'idle'}. Teardown arms stay pure patches but now invalidate the run instead of only flipping a flag. cancelledcarries a reason:user | superseded | teardown | scope. The scope check runs at succeed and reuseslib/federation/federation-identity.ts(#9496).- The activity journal row is derived from the slot, and the tray's Cancel is wired to the lease. Only a
usercancel shows as "cancelled". A superseded, torn-down or scope-dropped run removes its row, so the tray never shows a cancel the user didn't make.
hooks/useAsyncRun.ts: the component-local version. It keeps one union: idle | running{progress?} | succeeded{result} | failed{error} | cancelled{reason:'user'}.
- Re-entry:
startrefuses re-entry synchronously through a ref;restartsupersedes the run in flight. - Abort: the run aborts on
cancel,reset, unmount andkeychange. AnAbortErrorbecomescancelled. - Settle: only the run that still owns the hook writes state.
- Outcomes: they carry the reason.
startafter unmount never calls the task and returnscancelled/teardown. - StrictMode: a test asserts the double-invoked effects leave a run alone.
- Docs: the doc comment has a before/after example and lists the behaviour changes from
useSingleFlight. In short:release, unmount and akeychange now abort the run;- errors land in state and
console.warninstead of rejecting; Ris fixed per hook.
- useSingleFlight is not touched here. It lives in #9495 (queued). The migration that deletes it follows as its own PR after #9495 merges.
Test kit and helpers: test/race.ts (deferred, interleave, abortError, and installFakeWorker, a fake worker that can crash, raise messageerror, or die silently), lib/assert-never.ts, and lib/runs/abort.ts. isAbortError moved out of the activity journal so recordActivity, slot.run and useAsyncRun share one definition.
Pilot: scan detection (run-detection.ts + scanDetectionSlice)
- One record:
scanDetectionStatus,scanDetectionStage,scanDetectionErrorand their five raw actions become onescanDetectionJob: Run<…>record.scanDetectionRunstays as the last good run, kept after a cancel or failure. - On
slot.run: the pilot runs entirely inside aslot.runtask. The module-levelgenerationcounter and the hand-writtenstore.subscribemodel watch are gone; the teardown arms end the job.
Defects fixed
- Session reset mid-detection (verified on unmodified main before the change).
- Scenario: run "Detect elements", then load a new primary model while the worker is still segmenting.
- Before: a scratch test on main printed
after reset: status idle cancels 0and thenafter late answer: status done run published true. The old session's proposals landed in the new one. - After: the worker is terminated, the late answer is refused, and no tray row is left.
- Setup throws after the run started (raised by the CodeRabbit review of the first revision).
- Before: a throw from
cloudMatrixordeps.detector()after begin left the jobrunningand the button disabled, plus an unhandled rejection. - After: the run fails with the message. Both probes fail on the begin-based revision and pass now.
- Before: a throw from
Also new (user-visible)
- Scan detection appears in the activity tray, and the tray's Cancel stops it.
- If a model is replaced under the same id, the result is dropped.
- A detector that reports
cancelledon its own ends the run.
Validation
- New race tests:
useAsyncRun.test.tsx: 13run-slot.test.ts: 19run-detection.run-slot.test.ts: 11
- Touched families: every file of scan-to-bim, the scan-detection components, the teardown suite, activity, and the new files. Run under
systemd-run --user --scope -p MemoryMax=8G -p MemorySwapMax=0 npx tsx --import ./src/test/vite-module-hooks.mjs --test --test-concurrency=1 <47 files>: 319/319 pass. - Typecheck:
tsc --noEmitfor apps/viewer and apps/viewer-embed, including tests: exit 0. - Lint and gates: oxlint on the changed files is clean, and
check-module-sizeandcheck-source-text-assertionspass. - Fleet: the earlier fleet run of root
pnpm install --frozen-lockfile && pnpm typecheck && pnpm lintat afb6592 exited 0. CI covers the current head.
Mutation table (each guard removed → named test fails; 27/27 killed)
| # | Guard | Killed by |
|---|---|---|
| 0 | hook: refuse re-entry ref | two starts in one tick run the task once |
| 1 | hook: owner check before success write | cancel aborts the signal; late settle cannot overwrite |
| 2 | hook: AbortError → cancelled | an AbortError from the task is cancelled, not failed |
| 3 | hook: abort on abandon | cancel aborts the signal |
| 4 | hook: key change → idle | a key change aborts the run in flight… |
| 5 | hook: stale progress ignored | progress from an abandoned run is not shown |
| 6 | hook: owner check in catch | an abandoned run that throws leaves the newer run running and busy |
| 7 | hook: refuse after unmount | start after unmount never calls the task |
| 8 | hook: outcome reason recorded | cancel aborts the signal (cancelled:user) |
| 9 | hook: superseded reason | restart supersedes (cancelled:superseded) |
| 10 | slot: watcher ends lease on record change | a newer begin supersedes… |
| 11 | slot: abort on non-success end | a newer begin supersedes… |
| 12 | slot: scope check at succeed | a scope that changed by succeed discards the result |
| 13 | slot: isCurrent reads the record | a binding that does not notify still cannot let a replaced lease write |
| 14 | slot: stale progress is a no-op | a newer begin supersedes (no writes from a stale lease) |
| 15 | slot: journal failed outcome | a failure records its message |
| 16 | slot: non-user cancels drop the row | runs the user did not cancel leave no row |
| 17 | slot: superseded vs teardown reason | a lease knows why it ended |
| 18 | slot.run: AbortError → cancel | an AbortError is a user cancel, not a failure |
| 19 | slot.run: throw → fail | a throw fails through toError, and run() still resolves |
| 20 | slot.run: return → succeed | a returned value succeeds |
| 21 | scan: session-reset invalidates | a session reset mid-detection terminates the worker… |
| 22 | scan: model-removed invalidates | when the scan is removed mid-detection… |
| 23 | scan: all-models-cleared invalidates | when every model is cleared mid-detection… |
| 24 | scan: abort → detector.cancel | a session reset mid-detection terminates the worker… |
| 25 | scan: federation scope | a model replaced under the same id mid-run drops the result |
| 26 | scan: detector cancelled → cancel | a detector that reports cancelled on its own ends the run |
On the first pass #17 survived: superseded and teardown both drop the tray row, so the reason was unobservable. lease.cancelReason() now exposes it, and a test pins it.
Not verified / follow-ups
- The scan detection worker client has no
messageerrorhandler, so a worker that only raisesmessageerrorwould hang until the 10-minute timeout. That is thecreateWorkerRpcprimitive's job (plan item 3) and is out of scope here. - I did not run the viewer with a real E57 file. The change is covered by the store/detector race tests and the existing
ScanDetectionSectioncomponent test.
🤖 Generated with Claude Code