refactor(viewer): subsume useSingleFlight into useAsyncRun
Moves every useSingleFlight user (#9495) onto useAsyncRun (#9542) and deletes useSingleFlight; supersede means delete. This is item 2 of section 2 of the implicit-state-machines plan: the component-local hook subsumes useSingleFlight, ahead of the mass migration.
Migration
The rename is mechanical:
run(task(isCurrent))→start(task({ isCurrent }))release()→reset()outcome.status === 'refused'→outcome.kind === 'refused'SingleFlight['run']→AsyncRun['start'].AsyncRun'sRnow defaults tovoid, matching the hook.
Migrated (all 15 users on origin/main at 94ca2db):
- Top-level components: BCFPanel (capture, create and viewpoint flights), ClashPanel and useManualClashGroups (shared topic flight), ReportDeletionPreview, ReviewDecision, LayerReviewSection.
- Under
bcf/:- BCFDraftsDialog (export flight; its edit lane moved into the new
useDraftEdits, see below), BCFDraftReconcile, BCFOutboxEntry, BCFPublicationPanel; - BCFServerConnectForm, BCFServerDialog;
- useBcfArchiveActions (import and export), useBcfDraftActions.
- BCFDraftsDialog (export flight; its edit lane moved into the new
- Compare:
compare/useBcfFromChange(capture and submit).
Deleted: apps/viewer/src/hooks/useSingleFlight.ts and apps/viewer/src/hooks/useSingleFlight.test.tsx. Its behaviour is covered by useAsyncRun.test.tsx and by the #9495 component tests, which all still pass unchanged. git grep useSingleFlight now finds only the migration note in useAsyncRun's doc comment.
Behaviour changes
These are documented in useAsyncRun's doc comment ("Migrating from useSingleFlight").
reset()(formerlyrelease()), unmount and akeychange now abort the run'sAbortSignal. Before, they only marked the run stale.- User-visible consequence today: none. None of the migrated tasks passes the signal on yet, so the work still runs to completion. Each discard point still drops the late result, as in #9495:
- closing the BCF create form, Cancel on the compare BCF form, any change of the drafts dialog's active batch, any change of the saved BCF server connection, and a newer archive import.
- Effect: a task can now stop its own fetch or worker by passing
signalthrough. That is the hook for the later per-family PRs.
- User-visible consequence today: none. None of the migrated tasks passes the signal on yet, so the work still runs to completion. Each discard point still drops the late result, as in #9495:
- A task that throws no longer rejects.
startresolves{ kind: 'failed', error }, the hook's state becomesfailed, and the error is logged withconsole.warn.- Before: an escaping throw was an unhandled rejection, so the viewer's global "report this error" invitation (
ErrorReportHost) appeared. - Where it matters (corrected after review): my first pass missed four tasks with code outside their own
try. Each now reports its own failure, so the user is told what failed instead of losing the generic invitation:- BCFDraftReconcile: a throw from
applyTopicReconciliation,draftTopicor the parent's save. Shown in place: "The change could not be applied; the batch is unchanged. {message}". The failure belongs to the comparison its action started under, so a later Compare dismisses it, even one pressed while the action was still running. The flight is never reset on Compare, so a running action keeps its lane. - BCFPanel create topic: before
addTopic(viewpoint capture, building the topic) a failure shows the toast "Could not create the topic. {message}". It is gated onisCurrent(), so a form closed meanwhile stays silent, as in #9495, and the form stays open with the user's input. OnceaddTopichas committed the topic, the create is done and the form closes, so a second press cannot create a duplicate. Attaching its viewpoint then reports its own failure ("Could not add the viewpoint to the topic. {message}"), and analytics are best-effort; both live inbcf/created-topic-followups.ts. Covered byBCFPanel.create-failure.test.tsx: a create that throws, and a viewpoint that cannot be attached. The latter leaves exactly one topic, closes the form and shows only the viewpoint toast. - BCFPanel Add viewpoint:
addViewpointsat outside the capture'stry. A failure now shows the toast "Could not add the viewpoint to the topic. {message}". This lane moved intobcf/useTopicViewpointCapture.ts, which keeps BCFPanel under its module-size budget (474 → 453 measured at this head: 456 after the capture-lane move, then 453 once the create follow-ups moved tobcf/created-topic-followups.ts). - ReportDeletionPreview: two spots.
- Before the removal: the re-read of saved Documents and the dependency check (
reportChartDependencies) ran outside anytry. They are now inside one, and a throw there fails the removal throughstorageFailed(), the same path as a storage failure. - After the removal: if a host callback (
storageFailed,onDeleted) throws, the toast follows the outcome. A removed report gets "The report was removed, but this view could not update. Close and reopen it."; a failed removal gets "The report could not be removed. Close and reopen this view, then try again." (new keycomparePanel.saved.dependencies.removeFailed, en/de/fr/it/ru). Covered bycompare/ReportDeletion.failure-message.test.tsx, which stubs thestorageFailedprop to throw.
- Before the removal: the re-read of saved Documents and the dependency check (
- BCFServerConnectForm: URL validation and the popup open ran before its
try. Both are now inside it, so a throw shows in the form's error line like every other sign-in failure.
- BCFDraftReconcile: a throw from
- The new catalogue keys are in en/de/fr/it/ru. Changeset:
@ifc-lite/viewerpatch.
- Before: an escaping throw was an unhandled rejection, so the viewer's global "report this error" invitation (
- The result type
Ris fixed per hook (useAsyncRun<R>()), not per call.- User-visible consequence: none. Every migrated hook's tasks return nothing, so each is
useAsyncRun()withR = void. It is a compile-time constraint for future users.
- User-visible consequence: none. Every migrated hook's tasks return nothing, so each is
Guards rewritten with the migration
These were #9495's untested guards. They now have tests that hold the operation open with a deferred promise.
- Drafts edit lane →
bcf/useDraftEdits.ts. The dialog's async-edit logic moved into a hook that takes the edit as a promise, so a test can hold it open.- The lane is now owned by the batch on screen through
useAsyncRun({ key: batchId }). This replaces the hand-writtenreset()in the batch<select>handler. - Any change of the dialog's
activeIdreleases the lane, not only a pick in the<select>: an archive import (which selects the imported batch), deleting a batch, and another tab changing the active batch all do. The new batch's editor is usable at once, and the switched-away edit still lands in its own batch. - The release is not remembered per batch. Switching A → B → A while A's edit is still computing frees A's editor too, so a second A edit can start before the first lands. The doc comment says so.
- Covered by
useDraftEdits.test.tsx(deferred-held edits) and, at dialog level, byBCFDraftsDialog.batch-switch.test.tsx. That test presses Remove member and switches batch through the<select>inside oneact(), while the edit is still computing. - The refused-edit failure log moved over unchanged.
- The lane is now owned by the batch on screen through
BCFServerDialog:handleDisconnect'sreleasePull()deleted as redundant.clearBcfServerConfig()dispatches the change event in the same tab, so the dialog'ssubscribeBcfServerlistener has already runapplySavedConnection(null), which releases the pull. Disconnect is alsodisabled={busy}, so it never meets a running pull from this button anyway.- The pull-ownership tests call
clearBcfServerConfig()directly, the same local path, and cover both an account switch and a disconnect followed by a new sign-in.
- The pull-ownership tests call
<BCFDraftReconcile key={batch.id}>in the drafts dialog. A batch switch remounts it, so its proposal, its "no clash run" notice and a shown failure never describe another batch. Covered byBCFDraftsDialog.batch-switch.test.tsx.
Follow-ups (not blocking)
- Two open, unqueued Codex-lane PRs add new
useSingleFlightusers. They will need to switch touseAsyncRun(run→start,release→reset) when they rebase onto this: - #9583 needs the same
({ isCurrent })destructuring in BCFServerConnectForm and BCFServerDialog. It lands after this PR. - Queued PRs: none of #9538, #9546, #9550, #9554, #9534, #9537 or #9540 adds a
useSingleFlightuser. #9540 has already merged and is included here.
Validation (exact commands)
Bot threads + perf ratchet round, head 506a5db. Three commits on top of 5ac46d2:
fix(viewer): a created topic stays created; report deletion failures name the outcome. Both new tests failed on5ac46d2for the reasons in the threads (actual "Could not create the topic. …" and "The report was removed, …") and pass now.perf(viewer): load the BCF drafts dialog on demand. Its test isBCFDraftsControl.test.tsx: the dialog is mounted on first open, opens from the header action, closes and reopens.- BCFPanel's module-size budget drops 456 → 453, BCFPanel's measured line count (
wc -l) at this head. - Gate on
506a5db:- BCF + report-deletion +
hooks/bcf+ useAsyncRun families: 52 files, 259/259 pass under the 8G cap. tsc --noEmitviewer and viewer-embed: exit 0.- check-module-size OK.
- check-source-text-assertions OK.
- check-i18n-literals OK.
- oxlint on the changed files: clean.
- BCF + report-deletion +
Bundle (bundle/viewer-eager-js-bytes). Measured with node scripts/perf-ratchet/measure-bundle.mjs --dist <apps/viewer/dist> on local vite builds of the merge base 440bcfee4 and this branch, with identical dependency builds. Absolute values differ from CI's because of the local dependency builds; the delta is what this PR adds.
| build | viewer-eager-js-bytes | Δ vs merge base |
|---|---|---|
merge base 440bcfee4 | 18,053,970 | |
5fa3355 (before the lazy dialog) | 18,056,989 | +3,019 |
| this head (lazy drafts dialog) | 18,015,733 | −38,237 |
Before the lazy dialog, the per-file eager growth was:
| file | Δ |
|---|---|
useAsyncRun (new) | +1,698 |
main (BCFPanel create flow, drafts dialog/reconcile/edit lane, connect form) | +1,401 |
useSingleFlight (deleted) | −583 |
createLucideIcon (eager English catalogue: the 5 new message keys) | +505 |
useBcfDraftActions | −2 |
With the drafts dialog lazy, main shrinks by 32,094 and the dialog's draft and outbox code leaves the eager set. Some shared modules now sit in their own chunks that stay eager, because other boot code imports them (outbox-dispatch +9,379, revision-baseline +2,159, ModelBadge +1,491, …), offset by runner −9,145, bcf-bridge −3,814, draft-create −3,113, useBcfDraftActions −3,168 and others. Net −38,237. No tests/perf-ratchets/*.json was edited.
Review threads round, head 3604b25. Rebased onto main after #9532 and #9577; the only conflict was scripts/module-size-allowlist.txt, resolved by keeping main's rows plus BCFPanel 456. A third commit, fix(viewer): scope reconcile failures to their comparison; guard report deletion prep, holds this round's code changes.
- Families, 88 files (as listed below plus
hooks/useAsyncRun): 461/461 pass under the 8G cap. This includes the new "an apply that fails after a Compare pressed while it ran does not show under the new comparison". - Fleet, clean commit
3604b25(job f555b2aa):pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint && node scripts/check-module-size.mjs && node scripts/check-source-text-assertions.mjs. Exit 0:- typecheck 136/136 (viewer and viewer-embed included);
- lint "13,029 files … no errors";
- check-module-size OK;
- check-source-text-assertions OK.
- Sweep:
git grep -n useSingleFlight apps/viewer/srcfinds prose only. Main after #9532 and #9577 adds no users.
Review round, head 4e99233 (second commit fix(viewer): surface useAsyncRun task failures; key drafts reconcile by batch; the migration commit 8d8dcf7 is unchanged).
- Families: every test file in
components/viewer/{layers,bcf,clash}/,BCF*,Clash*,ReportDeletion*,compare/ReportDeletion*,assistant/ClashClassifyAll,useManualClash*,hooks/bcf/,hooks/useBCF*andhooks/useClash*(87 files):- Command (from
apps/viewer):systemd-run --user --scope -q -p MemoryMax=8G -p MemorySwapMax=0 npx tsx --import ./src/test/vite-module-hooks.mjs --test --test-timeout=120000 --test-concurrency=1 <87 files>. - Result: 447/447 pass. This includes the new
BCFPanel.create-failure.test.tsxandBCFDraftsDialog.batch-switch.test.tsx, and the extendedBCFDraftReconcile.failure.test.tsx.
- Command (from
- Typecheck:
tsc --noEmitforapps/viewerandapps/viewer-embed, including tests: exit 0 for both. - Fleet, clean commit
4e99233(job 2eddbb73):ifc-fleet run -- pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint && node scripts/check-module-size.mjs && node scripts/check-source-text-assertions.mjs. Exit 0:- typecheck 136/136;
- lint "13,021 files … no errors" (unused-locals, i18n literals and jsx-a11y included);
- check-module-size OK (
v1: BCFPanel's budget lowered 474 → 456 at that head; it is 453 now); - check-source-text-assertions OK, 0 new.
Earlier, on 8d8dcf7:
Rebased onto main after #9566 merged (head 8d8dcf7). #9566 rewrote LayerReviewSection and still used useSingleFlight's positional runAction(async (isCurrent) => …) in openReview. The rebase applied with no text conflicts. The only change to this PR's patch is that one line, now async ({ isCurrent }) for useAsyncRun's context. All three #9566 behaviours are kept: the remount key on [candidateId, refName, collabToken], the latest-wins refreshTicket, and the isCurrent() guard on the openReview error toast.
- Layers, BCF and ClashClassifyAll on the rebased head: every test file in
components/viewer/layers/,components/viewer/bcf/,components/viewer/BCF*,assistant/ClashClassifyAll,hooks/bcf/andhooks/useBCF*(47 files). That includes #9566'sLayerReviewSection.single-flight.test.tsxandClashClassifyAll.test.tsx. - Typecheck on the rebased head:
tsc --noEmitforapps/viewerandapps/viewer-embed, including tests: exit 0 for both. - Sweep:
git grep -n useSingleFlight apps/viewer/srcfinds no users, only two prose mentions (useAsyncRun.ts's migration note, a test docblock). Newly merged main (#9537, #9546, #9550, #9551, #9554, #9565, #9566, …) adds no new users.
Earlier runs on cf8104d (before the #9566 rebase):
All from apps/viewer under systemd-run --user --scope -q -p MemoryMax=8G -p MemorySwapMax=0.
- BCF family, final tree: every test file in
components/viewer/bcf/,components/viewer/BCF*,hooks/bcf/andhooks/useBCF*(42 files, includingBCFDraftReconcile.failure.test.tsx,useDraftEdits.test.tsxandBCFServerDialog.pull-ownership.test.tsx).- Command:
npx tsx --import ./src/test/vite-module-hooks.mjs --test --test-timeout=120000 --test-concurrency=1 <42 files>. - Result: 191/191 pass.
- Command:
- All touched families, before the guard tests: every test file in
bcf/, BCF*, Clash*, Compare*,compare/,clash/, ReportDeletion*, LayerReview*,review/, useManualClash* and all ofhooks/(347 files).- Result: 2475 tests, 2467 pass, 0 fail, 8 skipped (fixture-gated).
- The guard round changed only
bcf/files (BCFDraftsDialog,BCFServerDialog, the newuseDraftEdits), and the BCF family run above re-covers them.
- Typecheck:
tsc --noEmitforapps/viewerandapps/viewer-embed, including tests: exit 0 for both. - Static checks:
- oxlint on the changed files: clean.
node scripts/check-module-size.mjs: OK, 0 new over 400.node scripts/check-source-text-assertions.mjs: OK, 0 new.node --test scripts/check-unused-locals-baseline.test.mjs: 1/1 pass.
- Fleet, pushed head
cf8104d:ifc-fleet run --route fleet -- pnpm install --frozen-lockfile && pnpm typecheck && pnpm lint. Typecheck 136/136 turbo tasks; lint: "12,987 files … no errors", with unused-locals, i18n literals and jsx-a11y included. Exit 0 (job 06d1c308). CITypecheckandLinton this head: SUCCESS.
Mutation table: every guard killed
Each guard was removed in turn. The run covered useAsyncRun.test.tsx plus the BCF / clash / compare / layers / review single-flight and BCF test files, including the three new ones.
| # | Guard | Result | Killed by |
|---|---|---|---|
| 0 | useAsyncRun refuses re-entry (every migrated site) | KILLED | C-2 BCF panel: a double-pressed Capture 3D captures and appends one viewpoint; a double-pressed Export writes one archive (+ the other #9495 double-press tests) |
| 1 | BCFPanel: closing the create form resets its capture | KILLED | C-2 a capture from an earlier opening neither lands in nor stops the spinner of the reopened form |
| 2 | BCFPanel: closing the create form resets its create | KILLED | C-2 a create cancelled while its viewpoint is capturing adds no topic and no project |
| 3 | drafts edit lane owned by the batch on screen (key: batchId) | KILLED | switching batch frees the editor held by the previous batch, and both edits land |
| 4 | drafts edit lane: a refused edit's later failure is logged | KILLED | a second edit pressed while one is held is refused; if it then fails, that failure is logged |
| 5 | BCFServerDialog: an account change resets the pull (applySavedConnection) | KILLED | an account switch mid-pull frees Load topics for the new account, and the old pull never lands; a disconnect in another tab mid-pull, then signing in again here, frees Load topics… |
| 6 | BCFServerDialog: handleDisconnect resets the pull | DELETED | dead code: Disconnect is disabled while a pull runs (asserted in the disconnect test), and the other-tab disconnect path is #5 |
| 7 | archive import: a newer import supersedes the older read | KILLED | C-2 BCF panel: the latest imported file wins over an earlier, slower read |
| 8 | compare BCF form: Cancel resets its capture | KILLED | C-2 compare: after Cancel, an earlier capture neither lands in nor stops the spinner of the reopened form |
| 9 | compare BCF form: Cancel resets its submit | KILLED | C-2 compare: a create cancelled while its viewpoint is capturing adds no topic and no project |
| 10 | BCFDraftReconcile: a failed action is shown | KILLED | a throw while applying a reconciliation is shown in the panel, and Apply is usable again |
| 11 | BCFPanel: a create that throws shows a toast (review N1) | KILLED | a create that throws shows an error toast, adds nothing, and leaves the form usable |
| 12 | <BCFDraftReconcile key={batch.id}> (review N2) | KILLED | the previous batch's reconcile notice does not carry over to the new batch |
| 13 | BCFDraftReconcile: a failure shows only for the comparison its action started under (review N2 + CodeRabbit thread) | KILLED | a new Compare clears the last action's failure; an apply that fails after a Compare pressed while it ran does not show under the new comparison |
| 14 | BCFDraftsDialog passes the batch id to useDraftEdits (review M5 / N3) | KILLED | an edit still computing for the previous batch does not hold the new batch's editor |
Result: 14/14 killed (#11–#14 from the review round, run on 4e99233). Of the 11 original rows, #6 can't be killed, because the code it guarded can't run with a pull in flight, so it was deleted rather than tested. Each new test drives its operation through a deferred promise held across the switch, settles it, and asserts plain values: request counts, saved batch ids, warning lines, the store's pulled titles, busy.
Not mutation-tested: four small catches. These are Add viewpoint, ReportDeletionPreview's preparation and host callbacks, and BCFServerConnectForm's pre-sign-in steps. Each guards code (a store write, the Documents re-read plus reportChartDependencies, two parent state setters, URL validation and window.open) that a test cannot make throw without stubbing it. The review asked for a test only on the create-topic path.
The hook-level guards (owner-checked settle, abort on reset/unmount/key, AbortError → cancelled, start-after-unmount refusal) were mutation-checked in #9542: 27/27 killed.
🤖 Generated with Claude Code
Summary by CodeRabbit
- Bug Fixes
- Failed clash reconciliation now shows an error message and confirms that the batch remains unchanged. A new comparison clears earlier failure notices.
- Failures when creating topics, adding viewpoints, or completing report removal now provide clearer feedback.
- Closing forms or switching batches stops outdated actions from affecting the current view. Editors become available for the newly selected batch while earlier edits finish against their original batch.