feat(viewer): store run slot + useAsyncRun primitives; scan detection on the run slot

Merged
LO
22d ago
+1579-126

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, an AbortError (isAbortError) cancels, and any other throw fails through toError. It never rejects, so a fire-and-forget caller cannot leave a run running or an unhandled rejection behind.
  • begin(owner) is the manual form. It returns Lease {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 defineSliceTeardown arm returning {kind:'idle'}. Teardown arms stay pure patches but now invalidate the run instead of only flipping a flag.
  • cancelled carries a reason: user | superseded | teardown | scope. The scope check runs at succeed and reuses lib/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 user cancel 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: start refuses re-entry synchronously through a ref; restart supersedes the run in flight.
  • Abort: the run aborts on cancel, reset, unmount and key change. An AbortError becomes cancelled.
  • Settle: only the run that still owns the hook writes state.
  • Outcomes: they carry the reason. start after unmount never calls the task and returns cancelled/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 a key change now abort the run;
    • errors land in state and console.warn instead of rejecting;
    • R is 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, scanDetectionError and their five raw actions become one scanDetectionJob: Run<…> record. scanDetectionRun stays as the last good run, kept after a cancel or failure.
  • On slot.run: the pilot runs entirely inside a slot.run task. The module-level generation counter and the hand-written store.subscribe model watch are gone; the teardown arms end the job.

Defects fixed

  1. 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 0 and then after 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.
  2. Setup throws after the run started (raised by the CodeRabbit review of the first revision).
    • Before: a throw from cloudMatrix or deps.detector() after begin left the job running and 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.

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 cancelled on its own ends the run.

Validation

  • New race tests:
    • useAsyncRun.test.tsx: 13
    • run-slot.test.ts: 19
    • run-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 --noEmit for apps/viewer and apps/viewer-embed, including tests: exit 0.
  • Lint and gates: oxlint on the changed files is clean, and check-module-size and check-source-text-assertions pass.
  • Fleet: the earlier fleet run of root pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint at afb6592 exited 0. CI covers the current head.

Mutation table (each guard removed → named test fails; 27/27 killed)

#GuardKilled by
0hook: refuse re-entry reftwo starts in one tick run the task once
1hook: owner check before success writecancel aborts the signal; late settle cannot overwrite
2hook: AbortError → cancelledan AbortError from the task is cancelled, not failed
3hook: abort on abandoncancel aborts the signal
4hook: key change → idlea key change aborts the run in flight…
5hook: stale progress ignoredprogress from an abandoned run is not shown
6hook: owner check in catchan abandoned run that throws leaves the newer run running and busy
7hook: refuse after unmountstart after unmount never calls the task
8hook: outcome reason recordedcancel aborts the signal (cancelled:user)
9hook: superseded reasonrestart supersedes (cancelled:superseded)
10slot: watcher ends lease on record changea newer begin supersedes…
11slot: abort on non-success enda newer begin supersedes…
12slot: scope check at succeeda scope that changed by succeed discards the result
13slot: isCurrent reads the recorda binding that does not notify still cannot let a replaced lease write
14slot: stale progress is a no-opa newer begin supersedes (no writes from a stale lease)
15slot: journal failed outcomea failure records its message
16slot: non-user cancels drop the rowruns the user did not cancel leave no row
17slot: superseded vs teardown reasona lease knows why it ended
18slot.run: AbortError → cancelan AbortError is a user cancel, not a failure
19slot.run: throw → faila throw fails through toError, and run() still resolves
20slot.run: return → succeeda returned value succeeds
21scan: session-reset invalidatesa session reset mid-detection terminates the worker…
22scan: model-removed invalidateswhen the scan is removed mid-detection…
23scan: all-models-cleared invalidateswhen every model is cleared mid-detection…
24scan: abort → detector.cancela session reset mid-detection terminates the worker…
25scan: federation scopea model replaced under the same id mid-run drops the result
26scan: detector cancelled → cancela 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 messageerror handler, so a worker that only raises messageerror would hang until the 10-minute timeout. That is the createWorkerRpc primitive'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 ScanDetectionSection component test.

🤖 Generated with Claude Code