fix(830): gate onClose at the exemplar — the convention contradicted its own reference
Round 5 found that §3c and the `rule:` field now instruct readers to gate the DISMISS request, while `AddItemsDialog` -- the one site this record names as "the shape fixed here" -- called `onClose()` unguarded, with a comment arguing that was correct. So a reader following the convention wrote the gate and a reader copying the reference implementation did not. The defect is pre-existing; the CONTRADICTION is mine, introduced when round 3 withdrew H1's code but kept the convention it produced. I checked the docs against the withdrawn addTo code and did not re-check them against the exemplar that stayed. Measured at this site: submit, Escape mid-request, reopen the picker to retry, first POST returns 204 -> the stale instance's `onClose()` (`() => setPickerOpen(false)`) closes the dialog the user just reopened, discarding the selection they rebuilt. Identical mechanism to the addTo clobber. Unlike the addTo layer, the one-line gate IS sufficient here, and that difference is the point: `AddItemsDialog`'s parent has no competing closer (`onAdded` is `load`, which never touches `pickerOpen`), whereas `AddToMenu.handleAdded` closes its dialog itself. That is now stated in the record as the concrete reason one half shipped and the other went to #877. - `onAdded()` stays unguarded -- it REPORTS, and the parent's list reload must survive dismissal - `onClose()` is guarded -- it REQUESTS A DISMISSAL, and after dismissal it aims at whatever the user opened next - comment rewritten to say which is which and why, instead of defending both as "belong to the still-mounted PARENT" Pinned, and nothing pinned it before: "a late SUCCESS does not close the dialog the user reopened after dismissing (#830)". It carries an anti-vacuity check that the late response was actually processed -- `onAdded` is `load`, so a second GET of the items endpoint must have happened -- because otherwise "the dialog is still open" holds trivially. Executed: deleting the `if (mountedRef.current)` around `onClose()` reddens it alone. Also rewrapped five record body lines left ragged by earlier splices. 1277 tests green, tsc/eslint/build clean, pytest 1228 passed, validator OK, catalog no drift. refs #830, #877 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XE2tF2aUasK2hWPmBRsrMY
This commit is contained in:
@@ -7,7 +7,7 @@ supersedes: none
|
||||
superseded-by: none
|
||||
rule: 'A component that starts an async WRITE from inside a dismissible surface (`Dialog`, `SlideOver`, `ConfirmDialog`) must report failure through `useDismissSafeError` (`web/src/hooks.ts`), which renders the message INLINE while the surface is mounted and hands it to a caller-supplied `onFailed` once the surface is gone. Guarding the `setError` with an is-mounted check and stopping there is NOT sufficient: it converts a silent data-loss risk into a silent NO-OP the user reads as success. All three primitives dismiss through Escape and a backdrop/scrim click (`useOverlayBehavior`) plus a header close button, and NONE of those consult a busy flag — disabling the footer Cancel button, which every one of these dialogs does, looks like it closes the hole and does not. Report the OUTCOME past dismissal in both directions — a success callback gated on an is-mounted check makes a completed write silent too (measured on `AddToCollectionDialog`, #877) — but gate the DISMISS request (`onClose`) separately, because closing a surface that is no longer yours closes whatever replaced it. The surviving surface belongs to the PARENT, so the mechanism is a PROP CONTRACT rather than a rendering decision; as of 2026-08-29 exactly ONE screen is wired (`CollectionsScreen`, into its screen-level `role="alert"` banner), and the `notice`+`Toast` pair on `MediaBrowseScreen`/`SearchScreen` is a CANDIDATE second surface, not a wired one; there is no global toast host in this SPA and this decision does not add one. The reporting prop is REQUIRED where the host has a surface (`AddItemsDialog.onAddFailed`), so a failure cannot be dropped by forgetting to wire it; it is optional only where some host genuinely has nowhere to report, and there an omitted callback drops the failure exactly as before — a KNOWN remaining gap, not a claim of coverage.'
|
||||
signals: 'failed add silently swallowed · dialog closed mid-request · Escape backdrop close button ignore adding flag · error banner unmounts with the dialog · useDismissSafeError inline vs onFailed · success outlives dismissal but failure does not · onDone has no failure counterpart · paths: `web/src/hooks.ts`, `web/src/screens/CollectionsScreen.tsx`, `web/src/media/addTo/`, `web/src/components/overlay.tsx` · issues: #830, #877, #740, #685'
|
||||
mechanics: 'Pinned three ways. (1) `web/src/hooks.test.tsx` → "useDismissSafeError (#830)" pins both branches directly: mounted reports INLINE and does not call `onFailed`, unmounted calls `onFailed`, and the report goes through the LATEST callback rather than the one captured on first render. (2) `CollectionsScreen.test.tsx` → "reports a failed add on the screen when the dialog was dismissed before the request settled (#830)" drives the whole path — it parks the POST in flight, dismisses via Escape, then settles the request and asserts the message is on the screen and NOT inside a dialog. Executed: deleting `reportRef.current(message)` alone reddens it on `Unable to find an element with the text: Request failed with status 500`. That one clause is shared, so the same mutation reddens THREE tests (this one plus the two divert tests in (1)) — expect three reds, not one, when re-running it. (3) `CollectionsScreen.guards.test.tsx` counts is-mounted reads and moved from 2 to 1 when the catch''s guard migrated into the hook; its `...actual` module mock cannot see the hook''s internal `useIsMountedRef()`, which is why (1) exists. Executed: removing the surviving `finally` guard takes that count to 0 and reddens.'
|
||||
mechanics: 'Pinned four ways. (1) `web/src/hooks.test.tsx` → "useDismissSafeError (#830)" pins both branches directly: mounted reports INLINE and does not call `onFailed`, unmounted calls `onFailed`, and the report goes through the LATEST callback rather than the one captured on first render. (2) `CollectionsScreen.test.tsx` → "reports a failed add on the screen when the dialog was dismissed before the request settled (#830)" drives the whole path — it parks the POST in flight, dismisses via Escape, then settles the request and asserts the message is on the screen and NOT inside a dialog. Executed: deleting `reportRef.current(message)` alone reddens it on `Unable to find an element with the text: Request failed with status 500`. That one clause is shared, so the same mutation reddens THREE tests (this one plus the two divert tests in (1)) — expect three reds, not one, when re-running it. (3) `CollectionsScreen.test.tsx` → "a late SUCCESS does not close the dialog the user reopened after dismissing (#830)" pins the OTHER half of the split: it dismisses mid-request, reopens the picker, then settles the request 204, and asserts the reopened dialog is still there — with an anti-vacuity check that the late response was actually processed (`onAdded` is `load`, so a second GET of the items endpoint must have happened), because otherwise "the dialog is still open" holds trivially. Executed: deleting the `if (mountedRef.current)` around `onClose()` reddens it alone. (4) `CollectionsScreen.guards.test.tsx` counts is-mounted reads and moved from 2 to 1 when the catch''s guard migrated into the hook; its `...actual` module mock cannot see the hook''s internal `useIsMountedRef()`, which is why (1) exists. Executed: removing the surviving `finally` guard takes that count to 0 and reddens.'
|
||||
---
|
||||
|
||||
**This record applies to ONE site, and the reason the rest were dropped is the useful part.**
|
||||
@@ -25,7 +25,8 @@ different things: `onAdded` is "tell the parent what happened", `onClose` is "cl
|
||||
to a surface that no longer exists. Measured against the real `AddToMenu`: a late success from a
|
||||
DISMISSED dialog closed a dialog the user had since reopened. Read, not measured: the success
|
||||
handlers on `SearchScreen` / `MediaBrowseScreen` also call `clearSelection()` unconditionally, so
|
||||
the same late success would wipe a multi-select the user had rebuilt. Un-gating both is wrong, gating both is wrong, and gating only `onClose` still
|
||||
the same late success would wipe a multi-select the user had rebuilt. Un-gating both is wrong,
|
||||
gating both is wrong, and gating only `onClose` still
|
||||
needs the parents to stop nulling the dialog themselves — three coupled edits across five files,
|
||||
plus an unresolved question about whether `clearSelection()` should fire for a write the user walked
|
||||
away from. That is a design decision, not a bug fix, so it goes to #877 with the measurements
|
||||
@@ -34,6 +35,16 @@ attached rather than riding along here.
|
||||
`AddToMenu` also has `onDone` and no failure counterpart at all, which is why a failed "Add to
|
||||
collection" from a media card reports nowhere. Same issue.
|
||||
|
||||
**The outcome and the dismissal are different callbacks, and the exemplar proves it.** Review
|
||||
measured the cost of conflating them twice: gating both makes a completed write silent, un-gating
|
||||
both makes a late success close the dialog the user reopened to retry. `AddItemsDialog` now does
|
||||
each correctly — `onAdded()` unguarded, because it reloads the parent's list and that must survive;
|
||||
`onClose()` guarded, because after dismissal it is `setPickerOpen(false)` aimed at whatever the user
|
||||
opened next. That split is only this simple where the parent has no competing closer: here
|
||||
`onAdded` is `load`, which never touches `pickerOpen`. In the `media/addTo/` layer
|
||||
`AddToMenu.handleAdded` closes the dialog itself, so the same one-line gate is NOT sufficient there
|
||||
— measured — which is the concrete reason that half is #877 and not this record.
|
||||
|
||||
**Why the inline branch is kept rather than always reporting to the parent.** While the dialog is
|
||||
up, inline is the better surface: it keeps the user's selections and the context they are looking
|
||||
at. Diverting to a parent banner in that case would be its own defect — the message would surface
|
||||
@@ -65,18 +76,22 @@ reporting callback.
|
||||
**The hook has exactly one consumer, and that is worth saying.** `useDismissSafeError` is a shared
|
||||
module with a single call site today. It earns the shape three ways: it is unit-tested directly in
|
||||
`hooks.test.tsx`, in a way that would be awkward to keep if the hook were inlined into
|
||||
`CollectionsScreen`; §3c prescribes it for the next site; and #877 is a queued second consumer. The caveat:
|
||||
`CollectionsScreen`; §3c prescribes it for the next site; and #877 is a queued second consumer. The
|
||||
caveat:
|
||||
#877 may conclude that A2's right answer is a shared reporting SURFACE rather than a per-site prop,
|
||||
in which case this hook may never gain that second consumer and stays a one-off with a convention
|
||||
section attached. That is an accepted risk, not an oversight.
|
||||
|
||||
**Scope, stated rather than implied.** A sweep of all 68 `Dialog`/`ConfirmDialog`/`SlideOver` call
|
||||
sites (2026-08-29; 67 caller-owned plus `ConfirmDialog`'s own internal `<Dialog`) found three shapes: (A1) the surface hard-unmounts and takes its own error state
|
||||
with it — the shape fixed here, at `AddItemsDialog` ONLY — the four `web/src/media/addTo/` dialogs are the same shape and are NOT fixed (#877, see above);
|
||||
sites (2026-08-29; 67 caller-owned plus `ConfirmDialog`'s own internal `<Dialog`) found three
|
||||
shapes: (A1) the surface hard-unmounts and takes its own error state
|
||||
with it — the shape fixed here, at `AddItemsDialog` ONLY — the four `web/src/media/addTo/` dialogs
|
||||
are the same shape and are NOT fixed (#877, see above);
|
||||
(A2) the error state lives in a parent that never unmounts, but the JSX rendering it is nested
|
||||
inside the same `open`/`target` condition dismissal just cleared, so it has no DOM node to render
|
||||
into — the majority pattern, mostly delete-confirm flows; (B) a genuinely surviving screen-level
|
||||
banner, which `DecoTemplatesScreen` and `BlocksScreen` already have. Only ONE A1 site is fixed here. A2 is
|
||||
banner, which `DecoTemplatesScreen` and `BlocksScreen` already have. Only ONE A1 site is fixed here.
|
||||
A2 is
|
||||
LEFT OPEN deliberately: it is a larger, mostly-delete-confirm population whose right answer may be
|
||||
a shared reporting surface rather than a per-site prop, and folding it in would have made this PR a
|
||||
rewrite of twenty screens. It is tracked in #877, which carries the sweep's verified-vs-inferred
|
||||
|
||||
@@ -519,6 +519,61 @@ describe('CollectionsScreen', () => {
|
||||
expect(alert.closest('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
|
||||
// #830, the other half of the same mechanism. `onAdded` and `onClose` are not the same kind of
|
||||
// callback: the first REPORTS an outcome and must survive dismissal, the second REQUESTS A
|
||||
// DISMISSAL and must not — after dismissal it closes whatever the user opened next. Un-gating both
|
||||
// was measured wrong in review; this pins the split at the one site that ships it.
|
||||
it('a late SUCCESS does not close the dialog the user reopened after dismissing (#830)', async () => {
|
||||
let succeedAdd: (() => void) | undefined;
|
||||
const addInFlight = new Promise<Response>((resolve) => {
|
||||
succeedAdd = () => resolve(new Response(null, { status: 204 }));
|
||||
});
|
||||
|
||||
const fetchMock = mockAddItemsApi((url, method) =>
|
||||
url === '/api/v1/collections/1/items' && method === 'POST' ? addInFlight : null
|
||||
);
|
||||
|
||||
const dialog = await openAddItemsDialog();
|
||||
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
|
||||
target: { value: 'za' }
|
||||
});
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
|
||||
expect(await within(dialog).findByText('Zathura')).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(dialog).getByText('Zathura'));
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: /Add 1 item/ }));
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
fetchMock.mock.calls.some(
|
||||
([u, init]) => u === '/api/v1/collections/1/items' && (init?.method ?? '').toUpperCase() === 'POST'
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' });
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
|
||||
// The user reopens the picker to retry the add they believe failed.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add items' }));
|
||||
const reopened = await screen.findByRole('dialog');
|
||||
|
||||
// ...and only now does the first request come back, successfully.
|
||||
succeedAdd?.();
|
||||
|
||||
// ANTI-VACUITY: prove the late response was actually processed, so the assertion below is not
|
||||
// just "nothing has happened yet". `onAdded` is `load`, which refetches the collection's items.
|
||||
await waitFor(() => {
|
||||
const itemReads = fetchMock.mock.calls.filter(
|
||||
([u, init]) => /\/api\/v1\/collections\/1\/items/.test(u.toString()) && (init?.method ?? 'GET').toUpperCase() === 'GET'
|
||||
);
|
||||
expect(itemReads.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
// Remove the `if (mountedRef.current)` around `onClose()` and this dialog vanishes under the user.
|
||||
expect(reopened).toBeInTheDocument();
|
||||
expect(screen.queryByRole('dialog')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('selecting a newly-addable kind filter (Song) surfaces it and buckets it correctly on add', async () => {
|
||||
const fetchMock = mockAddItemsApi();
|
||||
|
||||
|
||||
@@ -350,11 +350,21 @@ function AddItemsDialog({
|
||||
|
||||
try {
|
||||
await addItemsToCollection(collection.id, toAddItemsRequest([...selected.values()]));
|
||||
// NOT guarded: both belong to the still-mounted PARENT. `onAdded` reloads the collection's
|
||||
// items, and dropping it because this dialog went away would leave the list stale after a
|
||||
// write that succeeded.
|
||||
// These two are NOT the same kind of callback, and only one of them survives dismissal.
|
||||
//
|
||||
// `onAdded` REPORTS what happened: it reloads the parent's item list, and dropping it because
|
||||
// this dialog went away would leave that list stale after a write that succeeded. Unguarded.
|
||||
//
|
||||
// `onClose` REQUESTS A DISMISSAL, and after dismissal the thing it closes is no longer this
|
||||
// instance -- `onClose` is `() => setPickerOpen(false)` on a parent that has since reopened
|
||||
// the picker. Firing it from a dead instance closes the dialog the user reopened to retry,
|
||||
// discarding the selection they just rebuilt (measured). Guarded. See `spa-conventions.md`
|
||||
// §3c: report the outcome unguarded, gate the dismiss request.
|
||||
onAdded();
|
||||
onClose();
|
||||
|
||||
if (mountedRef.current) {
|
||||
onClose();
|
||||
}
|
||||
} catch (addError) {
|
||||
// The dialog is unmount-reachable while a request is in flight even though the Add button is
|
||||
// disabled — Escape, a backdrop click and the header close button all reach `onClose` without
|
||||
|
||||
Reference in New Issue
Block a user