fix(651): review round 5 — delete the draft-reconciliation layer instead of extending it
Took the coordinator's proposal. Rounds 2-4 built and rebuilt a layer that merged a late detail response into a draft the user was already editing; it produced a HIGH finding in three consecutive rounds, three of them cross-user lost updates. Round 5's finding was unfixable in kind: `identityConflicts` had no immutable baseline, so it could not tell "the user changed this" from "the server changed this" — giving both a missed conflict (same type, different id: v2 ETag installed over the user's id, third lost update) and a false one (local type switch: dialog opens spuriously, and "Keep editing" leaves `etagRef` null so the next PUT is a silent FORCE-WRITE). The race is removed rather than refereed. `RerunCollectionEditor` now initializes its draft EXACTLY ONCE from the detail GET and withholds the form until it lands; conflicts are detected at save time by the `If-Match` -> 412 -> Reload path that already existed. Deleted: `touchedRef`, `hydrateDraft`, `hydrateSelection`, `hydrateIdentity`, `identityOf`, `identityConflicts`, `replaceDraft`, `replacePending` and the hydrate/replace load mode. Reload simply sets the draft back to null and re-runs the same load, so the form is unmounted while the replacement is in flight — round 4's MEDIUM-4 becomes structural. Two facts make this lossless rather than a regression. The list row could never have helped: `GetPagedRerunCollectionsHandler` applies ZERO `.Include()`s where `GetRerunCollectionByIdHandler` applies fourteen, and both project through the same mapper, so the list response is a strict SUBSET of the detail one — the id round 1 preserved from it is null in production for every row (#671), and existed only in test fixtures. And FillerPresetsScreen/PlaylistsScreen already worked this way; RerunCollections was the outlier, which is why nearly every finding in rounds 3-5 traced to it. The ETag is now written in the same callback that sets the draft, so `draft != null` implies an ETag and a PUT without `If-Match` is unreachable by construction. MEDIUM-2: a failed search retried every debounce forever — a fresh `{ok:false}` re-ran the effect and the success guard declined it. `ok` (is the held answer authoritative) is now separate from `attemptRef` (have we already tried this exact source+query); only an explicit reopen/focus/edit re-arms a retry. MEDIUM-3: a malformed 2xx body resolves as `undefined` (client.ts swallows the SyntaxError), and `setResults(undefined)` threw on the next render. A non-array is now treated as a failed attempt, and `search` is raced against a 10s deadline since a caller-supplied promise carries no abort signal. Two tests were hiding findings and are fixed: the failed-search test pressed Escape before the unintended retry could fire, and the round-4 conflict test claimed to select id 9 while firing the already-selected id 5. Fourteen tests of the deleted machinery are gone with it, replaced by six asserting the new invariants. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@ since: '2026-07-26'
|
||||
supersedes: spa.list-completeness-vs-bounded-pickers@2026-07-26
|
||||
superseded-by: none
|
||||
rule: 'A picker over a media-library table (Episode/Song/Image/Movie/MusicVideo/TelevisionShow/TelevisionSeason/Artist/OtherVideo/RemoteStream) resolves its options by SEARCH — a debounced `SearchPicker` calling `searchLibraryPickerOptions`, which issues at most ONE `getLibraryBrowseItems` request per settled query, bounded to `LIBRARY_PICKER_RESULTS` (25) rows — CLAMPED inside the helper, not merely defaulted — and gated on `LIBRARY_PICKER_MIN_QUERY` (2) characters. It list-loads NOTHING on mount or on a type switch, so there is no truncation to surface and no truncation hint. The typed text is COMPILED (`titleContainsQuery` → `title:*<escaped>*`), never forwarded raw. The current selection renders from the OWNING RECORD, not from the result set (`selectedName` on a rerun collection / playlist item; a single by-id detail read — `getShow`/`getSeason`/`getArtist` — for a filler preset, which stores only the id), and an edit-load refresh HYDRATES ONLY USER-UNTOUCHED FIELDS — resolving `collectionType`+id+name as ONE domain value, never field-by-field — so a response that fails to NAME a selection can never CLEAR its id, a type change can never strand an id belonging to the previous type, and a late refresh can never overwrite a live edit. An id NEVER travels without its namespace: search results are cached against `(source, query)` and list-backed options carry the type they were loaded for, so no id from one type can be offered under another. A conflict RELOAD is a separate `replaceDraft` path that adopts the server record wholesale and renders the editor inert while pending, and a touched identity contradicting the server type is surfaced as a CONFLICT rather than reconciled — both because installing a save-authorizing ETag over a local edit the server contradicts is a cross-user lost update; an asynchronously-resolved name is keyed to the id it was resolved for and never overwrites a label naming a different id. The typeahead implements the full ARIA combobox keyboard contract, because it replaces a natively keyboard-operable `<select>`. The other half of the superseded record is UNCHANGED: bounded-by-construction admin lists (collections, multi-collections, smart collections, playlists) still page to completeness via `loadAllPages` and still report `complete`/`hint: incomplete`. Server-side caps are not raised — this is a web-only change.'
|
||||
signals: 'library picker typeahead, SearchPicker, searchLibraryPickerOptions, titleContainsQuery, LIBRARY_PICKER_RESULTS, LIBRARY_PICKER_MIN_QUERY, LIBRARY_PICKER_LUCENE_SPECIALS, compile typed text not raw Lucene, Lucene && || escaping, picker truncation hint removed, loadAllPages Class A, LuceneSearchIndex.Search hitsLimit, useIsMountedRef, aria-activedescendant combobox keyboard, refresh must not clear an unnamed id, hydrate-untouched-fields not field-wise merge, refresh vs replace policy, cross-type id, id never travels without its namespace, results keyed on (source query), failed search not cached as empty, npm run typecheck not tsc --noEmit, stale result set not committable by keyboard OR pointer · paths: `web/src/api/libraryBrowse.ts`, `web/src/schedules/pickers.tsx`, `web/src/hooks.ts`, `web/src/screens/RerunCollectionsScreen.tsx`, `web/src/screens/PlaylistsScreen.tsx`, `web/src/screens/FillerPresetsScreen.tsx`, `web/src/api/paging.ts`, `docs/spa-conventions.md` §3b · issues: #651, #644, #578, #440'
|
||||
signals: 'library picker typeahead, SearchPicker, searchLibraryPickerOptions, titleContainsQuery, LIBRARY_PICKER_RESULTS, LIBRARY_PICKER_MIN_QUERY, LIBRARY_PICKER_LUCENE_SPECIALS, compile typed text not raw Lucene, Lucene && || escaping, picker truncation hint removed, loadAllPages Class A, LuceneSearchIndex.Search hitsLimit, useIsMountedRef, aria-activedescendant combobox keyboard, refresh must not clear an unnamed id, hydrate-untouched-fields not field-wise merge, initialize-once draft not hydrate-merge, no list-row seeding, cross-type id, id never travels without its namespace, results keyed on (source query), failed search not cached as empty, npm run typecheck not tsc --noEmit, stale result set not committable by keyboard OR pointer · paths: `web/src/api/libraryBrowse.ts`, `web/src/schedules/pickers.tsx`, `web/src/hooks.ts`, `web/src/screens/RerunCollectionsScreen.tsx`, `web/src/screens/PlaylistsScreen.tsx`, `web/src/screens/FillerPresetsScreen.tsx`, `web/src/api/paging.ts`, `docs/spa-conventions.md` §3b · issues: #651, #644, #578, #440'
|
||||
mechanics: '`docs/spa-conventions.md` §3b'
|
||||
---
|
||||
|
||||
@@ -71,6 +71,28 @@ Save wrote 42 — the user's choice discarded with no error and no visual cue, w
|
||||
defect at least cleared the field visibly. A second cold review caught it. The trade is: a visible
|
||||
failure is strictly better than a silent one, so a "smarter coalesce" is the wrong shape of fix.
|
||||
|
||||
**Round 5 deleted all of it.** What follows is kept because the reasoning is the point, but the
|
||||
mechanism it describes no longer exists: rounds 2-4 built and rebuilt a layer that reconciled a late
|
||||
detail response against a draft the user was already editing, and that layer produced a HIGH finding
|
||||
every single round — three of them cross-user lost updates. The final one was unfixable in kind: the
|
||||
merge had no immutable baseline, so it could not distinguish "the user changed this" from "the server
|
||||
changed this", giving both a missed conflict and a false one (the false one leaving `etagRef` null,
|
||||
turning the next save into a silent force-write). The fix was to **remove the race rather than
|
||||
referee it**: initialize the draft exactly once from the detail GET, withhold the form until it
|
||||
lands, and detect conflicts at save time through the `If-Match` -> 412 -> Reload path that already
|
||||
existed. `touchedRef`, `hydrateDraft`, `hydrateIdentity`, `identityConflicts`, `replaceDraft` and
|
||||
`replacePending` are all gone.
|
||||
|
||||
Two facts made that safe rather than lossy. First, the list row could never have helped: its handler
|
||||
applies **zero** `.Include()`s where the detail handler applies **fourteen**, and both project
|
||||
through the same mapper, so the list response is a strict subset — the id it was being seeded with
|
||||
is null in production for every row (#671). Every round-1 "preserve the id from the list" guarantee
|
||||
was therefore protecting a value that only existed in test fixtures. Second, the sibling screens
|
||||
(`FillerPresetsScreen`, `PlaylistsScreen`) already worked this way; `RerunCollectionsScreen` was the
|
||||
outlier, which is why nearly every finding in rounds 3-5 traced to it.
|
||||
|
||||
The historical reasoning, retained because the *classes* still bind anywhere a draft is reconciled:
|
||||
|
||||
What replaced it is atomicity plus a race rule — and a third review round showed the first attempt
|
||||
at *that* had made the same mistake one level up: it enumerated the instance (id/name) instead of
|
||||
covering the class. **A picker selection is one value spread across three fields**: `collectionType`
|
||||
@@ -132,9 +154,15 @@ surface, not a state to reconcile. Relatedly, the Reload path now renders the ed
|
||||
replacement is in flight, since the dialog closes immediately and an edit typed in that window was
|
||||
silently erased.
|
||||
|
||||
**Cache provenance must distinguish failure from emptiness.** The round-3 re-query guard cached a
|
||||
failed search as an authoritative empty result, so a transient 500 became a permanent "No matches"
|
||||
that no amount of reopening could retry. The cached entry now records `ok`.
|
||||
**Cache provenance must distinguish failure from emptiness — without licensing a retry storm.** The
|
||||
round-3 re-query guard cached a failed search as an authoritative empty result, so a transient 500
|
||||
became a permanent "No matches" that no amount of reopening could retry. Recording `ok` fixed that
|
||||
but created the opposite defect: declining the cached failure re-ran the effect and scheduled a
|
||||
fresh request every debounce. The two concerns are now separate — `ok` says whether the held answer
|
||||
is authoritative, and an `attemptRef` suppresses automatic retries until an explicit user action
|
||||
re-arms one. The picker also races `search` against a deadline (a caller-supplied promise carries no
|
||||
abort signal) and treats a non-array resolution as a failure, since `client.ts` turns a malformed
|
||||
2xx body into `undefined` rather than rejecting.
|
||||
|
||||
**Replacing a native control means owing its keyboard behaviour.** A `<select>` is fully
|
||||
keyboard-operable, so an input-plus-listbox that only responds to Tab and click is a regression
|
||||
|
||||
+35
-40
@@ -222,42 +222,29 @@ the #644 follow-up got Class A right and Class B only half right):
|
||||
the replacement load on a slow connection.
|
||||
3. A local edit whose type contradicts the server's is a **conflict**, not something to
|
||||
reconcile (below).
|
||||
- **Hydrate the whole domain value; never merge field-by-field.** The obvious fix — coalescing
|
||||
each field independently (`refreshed.selectedId ?? current.selectedId`,
|
||||
`refreshed.selectedName || current.selectedName`) — is *worse than the bug it fixes*, and this
|
||||
is the trap to internalise. A picker selection is **one value spread across three fields**:
|
||||
`collectionType` says which table an id indexes, `selectedId` picks the row, `selectedName`
|
||||
labels it. Coalescing any of them separately pairs one selection's component with another's:
|
||||
split id from name and the chip shows what the user picked while Save writes what the server
|
||||
sent; split type from id and a Collection id is displayed and saved as a RemoteStream id. Both
|
||||
are silent, where the original defect at least cleared the field visibly. Three rules:
|
||||
1. **Resolve the unit atomically.** Either half touched by the user pins the whole unit. A
|
||||
differing `collectionType` takes the response's unit whole — a null selection included,
|
||||
because an id from the old type's space cannot be carried across. Only once both sides agree
|
||||
on the type does the id/name rule apply: no id ⇒ keep ours; *same* id ⇒ the response's name
|
||||
may fill ours in; *different* id ⇒ take the response's pair whole.
|
||||
2. **A late hydrate must lose every race against the user.** Track which fields the user has
|
||||
edited (a ref, updated by a single `edit()` funnel so "touched" cannot drift from "changed")
|
||||
and hydrate only untouched ones. Field-wise coalescing also resurrects a deliberate clear and
|
||||
reverts a type switch.
|
||||
3. **Refresh and replace are different policies — make them different functions.** A conflict
|
||||
"Reload" exists to *discard* local edits, so it must adopt the server's record wholesale,
|
||||
null selection and all. Routing it through the refresh policy (even with a touched-set reset)
|
||||
is a **cross-user lost update**: the keep-ours-when-the-id-is-missing fallback restores the
|
||||
user's dirty selection, the fresh ETag is installed, and the next Save silently overwrites
|
||||
the collaborator's change. A shared path with a clearing side effect is not enough — the
|
||||
mode must be explicit and carried with the load. A pending replace must also make the editor
|
||||
**inert**: the dialog closes immediately, so an edit typed while the replacement is in flight
|
||||
is silently erased when it lands.
|
||||
4. **Never install a save-authorizing ETag over a local edit the server contradicts.** This is
|
||||
the general category behind two separate lost updates on this branch. If the user has touched
|
||||
the identity and the refresh reports a *different type*, that is a conflict — surface it and
|
||||
keep the stale ETag, so even a forced Save gets a 412 instead of clobbering. Pinning the
|
||||
user's edit (correct) while adopting the response's newest ETag (incorrect) converts a
|
||||
detectable conflict into an undetected overwrite.
|
||||
- **Initialize an edit draft ONCE, from the detail read — never reconcile a late response against
|
||||
an open form.** This supersedes an earlier prescription here for merging a refresh into a draft
|
||||
field-by-field/atomically with touched-field tracking. That reconciliation layer produced a HIGH
|
||||
finding in three consecutive review rounds of #651, including three cross-user lost updates, and
|
||||
the last of them (a merge with no immutable baseline, so it could not tell a local edit from a
|
||||
server change) is unfixable without adding a third-way baseline — more machinery on the surface
|
||||
that was generating the bugs. Instead:
|
||||
- `draft` starts as `null` for an existing record and the form does not render until the detail
|
||||
GET lands. There is then no draft for a late response to reconcile against, and no window in
|
||||
which the user can edit something about to be replaced.
|
||||
- **Do not seed from the list row.** It is not authoritative: for rerun collections the list
|
||||
handler applies zero `.Include()`s while the detail handler applies fourteen, and both project
|
||||
through the same mapper, so the list response is a strict SUBSET of the detail one (#671). A
|
||||
seed can only add a race, never information. Verify that claim for your endpoint before
|
||||
relying on it.
|
||||
- **Write the concurrency ETag in the same callback that sets the draft**, so `draft != null`
|
||||
implies an ETag and a PUT with no `If-Match` (a silent force-write) is unreachable.
|
||||
- **Detect conflicts at save time** via the existing `If-Match` → 412 → Reload path. Reload sets
|
||||
the draft back to `null` and re-runs the same initialize-once load, so "replace" needs no
|
||||
separate policy and the form is unmounted while the replacement is in flight.
|
||||
|
||||
Test this by **interleaving**: issue the refresh, have the user act while it is in flight, then
|
||||
release it. A test that doesn't interleave proves nothing about a race.
|
||||
`FillerPresetsScreen` and `PlaylistsScreen` already worked this way; `RerunCollectionsScreen` was
|
||||
the outlier that seeded from its list row, which is where every one of these defects lived.
|
||||
- **A name resolved asynchronously must be keyed to the id it was resolved FOR**, and must refuse
|
||||
to overwrite a label that already names a different id. A slow by-id read landing after the user
|
||||
has picked something else would otherwise label the new selection with the old item's title
|
||||
@@ -292,11 +279,19 @@ implements the ARIA combobox pattern — `role="combobox"` + `aria-expanded`/`ar
|
||||
matches in tests: count `<select>` elements when that is what you mean. Two failure modes that only
|
||||
appear once the widget is asynchronous:
|
||||
|
||||
- **Freshness is `(source, query)`, and cached failures are not answers.** A `SearchPicker`-style
|
||||
cache must record which source produced the results and whether the attempt *succeeded*. Caching a
|
||||
failed search as an authoritative empty result turns a transient 500 into a permanent "No matches"
|
||||
that reopening, blurring and refocusing can never retry — the re-query guard sees a cache hit
|
||||
forever. Distinguish success from failure in the cached provenance.
|
||||
- **Freshness is `(source, query)`, and cached failures are not answers — but they are not licences
|
||||
to retry either.** A `SearchPicker`-style cache must record which source produced the results and
|
||||
whether the attempt *succeeded*. Caching a failure as an authoritative empty result turns a
|
||||
transient 500 into a permanent "No matches" that reopening can never clear. But simply declining
|
||||
the cached failure re-runs the effect and schedules another request every debounce — a **request
|
||||
storm** on a persistent outage. Keep the two apart: a `resultsFor.ok` flag says whether the held
|
||||
answer is authoritative, and a separate *attempted* key (a ref, so writing it doesn't re-render)
|
||||
suppresses automatic retries until an explicit user action — reopen, focus, or edit — re-arms it.
|
||||
- **A caller-supplied promise needs a deadline, and a 2xx body is not a contract.** `client.ts`
|
||||
turns malformed JSON into `undefined` rather than rejecting, so `setResults(undefined)` throws on
|
||||
the next render; treat a non-array as a failed attempt, not an empty answer. And a `search` prop
|
||||
carries no abort signal, so race it against a timeout — otherwise a never-settling request leaves
|
||||
the picker spinning with no way back.
|
||||
- **A stale result set must not be committable — by ANY modality.** Between a keystroke and its
|
||||
response, `results` still describe the *previous* query, so highlighting an option, retyping, and
|
||||
pressing Enter commits the old option while the box reads the new text. Drop the highlight on
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { SearchPicker, type SearchPickerOption } from './pickers';
|
||||
|
||||
@@ -438,7 +438,14 @@ describe('SearchPicker', () => {
|
||||
expect(await screen.findByText(/No matches/)).toBeInTheDocument();
|
||||
expect(search).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but must NOT be cached as an authoritative one: reopening the same query has to retry.
|
||||
// ...and must NOT retry on its own initiative. The original version of this test pressed
|
||||
// Escape immediately, cancelling the very timer that would have exposed the storm (#651 round
|
||||
// 5): a fresh `{ok:false}` object re-ran the effect, the success guard declined it, and
|
||||
// another request was scheduled 250ms later, forever.
|
||||
await new Promise((resolve) => setTimeout(resolve, 900));
|
||||
expect(search).toHaveBeenCalledTimes(1);
|
||||
|
||||
// ...but must NOT be cached as an authoritative one either: reopening has to retry.
|
||||
fireEvent.keyDown(input, { key: 'Escape' });
|
||||
await waitFor(() => expect(screen.queryByText(/No matches/)).not.toBeInTheDocument());
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
@@ -463,5 +470,54 @@ describe('SearchPicker', () => {
|
||||
// "There genuinely are no matches" is an answer; re-asking would be the round-3 defect.
|
||||
expect(search).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('MEDIUM-3: a malformed 2xx body does not crash the picker, and is retryable', async () => {
|
||||
// `client.ts` turns malformed JSON into `undefined` rather than rejecting, so a naive
|
||||
// `setResults(undefined)` throws on the next render reading `results.length`.
|
||||
const search = vi
|
||||
.fn<(query: string) => Promise<SearchPickerOption[]>>()
|
||||
.mockResolvedValueOnce(undefined as unknown as SearchPickerOption[])
|
||||
.mockResolvedValue(OPTIONS);
|
||||
|
||||
renderPicker({ search });
|
||||
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'Alpha' } });
|
||||
|
||||
// Renders rather than throwing, and treats the malformed body as a failed attempt.
|
||||
expect(await screen.findByText(/No matches/)).toBeInTheDocument();
|
||||
await new Promise((resolve) => setTimeout(resolve, 900));
|
||||
expect(search).toHaveBeenCalledTimes(1);
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' });
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' });
|
||||
await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
|
||||
expect(await screen.findByRole('option', { name: 'Alpha' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('MEDIUM-3: a never-settling search stops loading instead of spinning forever', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>(() => new Promise(() => {}));
|
||||
renderPicker({ search });
|
||||
|
||||
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'Alpha' } });
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
});
|
||||
expect(search).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Past the picker's own deadline the wait is abandoned and the failure surfaces.
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(11_000);
|
||||
});
|
||||
expect(screen.getByText(/No matches/)).toBeInTheDocument();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,6 +37,9 @@ export interface SearchPickerProps {
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
// Upper bound on how long a picker will wait for a caller-supplied search promise.
|
||||
const SEARCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
export function SearchPicker({
|
||||
label,
|
||||
selectedId,
|
||||
@@ -68,9 +71,21 @@ export function SearchPicker({
|
||||
const [activeIndex, setActiveIndex] = useState(-1);
|
||||
const listboxId = useId();
|
||||
const seqRef = useRef(0);
|
||||
// The last (source, query) an actual REQUEST was issued for — success or failure. A failed
|
||||
// attempt writes a fresh `resultsFor` object, which re-runs the effect; without this the success
|
||||
// guard would decline the cached failure and schedule another request 250ms later, forever
|
||||
// (#651 round 5 MEDIUM-2: a persistent outage became a request storm alternating "No matches"
|
||||
// and a spinner). Reopening or editing the query is what re-arms a retry — both explicit user
|
||||
// actions — so this is cleared there rather than on a timer.
|
||||
const attemptRef = useRef<null | string>(null);
|
||||
// #578: the seq guard drops a stale response but not a post-unmount one. Both are needed.
|
||||
const mountedRef = useIsMountedRef();
|
||||
|
||||
// Re-arm a retry: the same failed query becomes requestable again after an explicit user action.
|
||||
const rearm = () => {
|
||||
attemptRef.current = null;
|
||||
};
|
||||
|
||||
// All state transitions happen inside the debounce callback (never synchronously in the effect
|
||||
// body — see spa-conventions.md §3).
|
||||
useEffect(() => {
|
||||
@@ -81,12 +96,18 @@ export function SearchPicker({
|
||||
|
||||
// Already holding SUCCESSFUL results for exactly this source and query — e.g. reopening after
|
||||
// Escape. Re-running the search would issue a duplicate request whose response resets the
|
||||
// highlight the user has since moved, leaving Enter doing nothing (#651 round 3, MEDIUM). A
|
||||
// different source, or a cached failure, must still re-query.
|
||||
// highlight the user has since moved, leaving Enter doing nothing (#651 round 3, MEDIUM).
|
||||
if (resultsFor !== null && resultsFor.ok && resultsFor.source === source && resultsFor.query === trimmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Already TRIED this exact (source, query) and it failed. Do not retry on our own initiative —
|
||||
// `rearm()` on reopen/edit is what allows another attempt (#651 round 5 MEDIUM-2).
|
||||
const attempt = `${source}\u0000${trimmed}`;
|
||||
if (attemptRef.current === attempt) {
|
||||
return;
|
||||
}
|
||||
|
||||
const seq = ++seqRef.current;
|
||||
const tooShort = trimmed.length < minQueryLength;
|
||||
const handle = window.setTimeout(() => {
|
||||
@@ -100,9 +121,31 @@ export function SearchPicker({
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
search(trimmed)
|
||||
attemptRef.current = attempt;
|
||||
// Bound the wait. `search` is a caller-supplied promise with no abort signal, so a request
|
||||
// that never settles would otherwise leave the picker spinning forever with no way back
|
||||
// (#651 round 5 MEDIUM-3). The underlying request is not cancelled — the seq guard already
|
||||
// discards a late resolution — but the UI stops waiting on it.
|
||||
Promise.race([
|
||||
search(trimmed),
|
||||
new Promise<never>((_resolve, reject) =>
|
||||
window.setTimeout(() => reject(new Error('search timed out')), SEARCH_TIMEOUT_MS)
|
||||
)
|
||||
])
|
||||
.then((items) => {
|
||||
if (mountedRef.current && seqRef.current === seq) {
|
||||
// A malformed 2xx body resolves as `undefined` rather than rejecting (`client.ts`
|
||||
// `readJsonResponse` swallows a SyntaxError), and `setResults(undefined)` then throws
|
||||
// on the next render reading `results.length`. Treat a non-array as a failed attempt:
|
||||
// it is not an authoritative empty answer (#651 round 5 MEDIUM-3).
|
||||
if (!Array.isArray(items)) {
|
||||
setResults([]);
|
||||
setResultsFor({ ok: false, query: trimmed, source });
|
||||
setActiveIndex(-1);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setResults(items);
|
||||
setResultsFor({ ok: true, query: trimmed, source });
|
||||
// A new result set invalidates the highlight — index 2 of the old list is not index 2
|
||||
@@ -173,6 +216,7 @@ export function SearchPicker({
|
||||
if (!open && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
rearm();
|
||||
// Per the ARIA combobox pattern the same keypress also places the cursor, so reopening
|
||||
// doesn't silently swallow it — but only onto results that are current, the same rule every
|
||||
// other commit/navigation path obeys.
|
||||
@@ -256,8 +300,12 @@ export function SearchPicker({
|
||||
// so the picker recovers without a blur (BLOCKER 3).
|
||||
setActiveIndex(-1);
|
||||
setOpen(true);
|
||||
rearm();
|
||||
}}
|
||||
onFocus={() => {
|
||||
setOpen(true);
|
||||
rearm();
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
{loading && <span className="ctv-field-trailing"><Spinner size={13} tone="muted" /></span>}
|
||||
|
||||
@@ -465,327 +465,12 @@ describe('RerunCollectionsScreen', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ---- #651 F1: a refresh that cannot NAME a selection must never CLEAR it ----
|
||||
//
|
||||
// `RerunCollectionsController.ProjectToResponseModel` derives selectedId AND selectedName from
|
||||
// the loaded navigation, so several supported types come back unnamed — or unidentified — through
|
||||
// no fault of the record: `GetRerunCollectionByIdHandler` eager-loads metadata only for
|
||||
// Show/Season/Artist/Movie; `MediaCollections/Mapper` maps RemoteStream through `_ => null`
|
||||
// (HTTP 200, null selection); Episode/MusicVideo dereference unloaded `Season`/`Artist`
|
||||
// navigations and 500. In every one of those cases the stored id must survive and Save must stay
|
||||
// enabled.
|
||||
const detailGapCases = [
|
||||
{
|
||||
// The reviewer's concrete case: a successful response carrying a null selection.
|
||||
detail: (type: string): Response =>
|
||||
jsonResponse({ ...storedSelection, collectionType: type, selectedId: null, selectedName: null }),
|
||||
name: 'RemoteStream — detail 200 with a null selection (Mapper `_ => null`)',
|
||||
type: 'RemoteStream'
|
||||
},
|
||||
{
|
||||
// Error-path guard, NOT merge coverage: a 500 never reaches the hydrate at all. Kept so a
|
||||
// future change that clears the draft on a failed refresh is caught.
|
||||
detail: (): Response => new Response(null, { status: 500 }),
|
||||
name: 'Episode — detail 500 (NRE on the unloaded Season navigation)',
|
||||
type: 'Episode'
|
||||
},
|
||||
{
|
||||
// Error-path guard, NOT merge coverage — see the Episode case.
|
||||
detail: (): Response => new Response(null, { status: 500 }),
|
||||
name: 'MusicVideo — detail 500 (NRE on the unloaded Artist navigation)',
|
||||
type: 'MusicVideo'
|
||||
},
|
||||
{
|
||||
// Id resolves but the name is a server-side placeholder/null — must not blank what we hold.
|
||||
detail: (type: string): Response => jsonResponse({ ...storedSelection, collectionType: type, selectedName: null }),
|
||||
name: 'Song — detail 200 with an id but no name',
|
||||
type: 'Song'
|
||||
},
|
||||
{
|
||||
detail: (type: string): Response => jsonResponse({ ...storedSelection, collectionType: type, selectedName: null }),
|
||||
name: 'OtherVideo — detail 200 with an id but no name',
|
||||
type: 'OtherVideo'
|
||||
},
|
||||
{
|
||||
detail: (type: string): Response =>
|
||||
jsonResponse({ ...storedSelection, collectionType: type, selectedId: null, selectedName: null }),
|
||||
name: 'Image — detail 200 with a null selection',
|
||||
type: 'Image'
|
||||
}
|
||||
];
|
||||
|
||||
it.each(detailGapCases)('F1: keeps the stored selection and Save when the detail GET cannot name it — $name', async ({ detail, type }) => {
|
||||
let detailCalls = 0;
|
||||
mockApi({
|
||||
list: [{ ...storedSelection, collectionType: type }],
|
||||
// The detail response must echo the SAME collectionType the list gave, as a real server
|
||||
// would — changing it here would remount the picker mid-assertion and mask what is tested.
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
return detail(type);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
// Wait for the REFRESH to have landed before asserting — the pre-refresh draft already shows
|
||||
// the right thing, so an assertion that races the refresh cannot see it being clobbered. (React
|
||||
// mutates the existing text node rather than replacing it, so even `findByText` + a later
|
||||
// `toBeInTheDocument` would pass on a stale handle: read `textContent` after the fact.)
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeInTheDocument());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const chip = screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected');
|
||||
expect(chip?.textContent).toContain('Stored Item');
|
||||
|
||||
// ...and the record remains saveable: clearing the id would strand the user on a record they
|
||||
// cannot re-save.
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).not.toBeDisabled();
|
||||
expect(screen.queryByText('A selection is required')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('F1: degrades to #id (never to an empty picker) when no name is available at all', async () => {
|
||||
let detailCalls = 0;
|
||||
mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'RemoteStream', selectedName: null }],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
return jsonResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
// Await the refresh: the pre-refresh draft already shows #42, so an assertion that races it is
|
||||
// satisfiable without the hydration guard at all.
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
const chip = screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected');
|
||||
expect(chip?.textContent).toContain('#42');
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('F1: re-saves the preserved id unchanged after an unnamed refresh', async () => {
|
||||
let detailCalls = 0;
|
||||
const fetchMock = mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'RemoteStream' }],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
return jsonResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null });
|
||||
}
|
||||
return url === '/api/v1/rerun-collections/9' && method === 'PUT' ? jsonResponse({ id: 9 }, 200) : null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
// Await the refresh before saving — otherwise the PUT can be issued from the pre-refresh draft
|
||||
// and the assertion passes with the hydration guard removed.
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected')?.textContent).toContain('Stored Item');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
|
||||
await waitFor(() => {
|
||||
const putCall = fetchMock.mock.calls.find(
|
||||
([u, init]) => u === '/api/v1/rerun-collections/9' && (init?.method ?? '').toUpperCase() === 'PUT'
|
||||
);
|
||||
expect(putCall).toBeDefined();
|
||||
expect(JSON.parse(String(putCall?.[1]?.body)).selectedId).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- #651 review round 2, BLOCKER 1: hydration must lose every race against the user ----
|
||||
//
|
||||
// The round-1 fix merged `selectedId` and `selectedName` field-by-field, which paired one
|
||||
// selection's id with another's name: the chip showed what the user picked while Save wrote what
|
||||
// the server sent. These tests interleave a DELAYED detail refresh with a user edit — the whole
|
||||
// point is the ordering, so a non-interleaved test proves nothing.
|
||||
//
|
||||
// `Song` is the shape that makes it concrete: its response resolves an id but not a name.
|
||||
function mockWithDelayedDetail(detailBody: unknown, listRow: Record<string, unknown>) {
|
||||
let release: (() => void) | null = null;
|
||||
const fetchMock = mockApi({
|
||||
browsePage: { page: [{ id: 99, mediaItemId: 99, mediaType: 'Song', title: 'New Song' }], totalCount: 1 },
|
||||
list: [listRow],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
// Returning null here would fall through to mockApi's own handler, so signal the delay by
|
||||
// returning a never-settling Response via the outer promise instead.
|
||||
return null;
|
||||
}
|
||||
return url === '/api/v1/rerun-collections/9' && method === 'PUT' ? jsonResponse({ id: 9 }, 200) : null;
|
||||
}
|
||||
});
|
||||
|
||||
const inner = fetchMock.getMockImplementation() as (i: RequestInfo | URL, r?: RequestInit) => Promise<Response>;
|
||||
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
return new Promise<Response>((resolve) => {
|
||||
release = () => resolve(jsonResponse(detailBody));
|
||||
});
|
||||
}
|
||||
return inner(input, init);
|
||||
});
|
||||
|
||||
return { fetchMock, releaseDetail: async () => { release?.(); await new Promise((r) => setTimeout(r, 0)); } };
|
||||
}
|
||||
|
||||
const songRow = {
|
||||
...storedSelection,
|
||||
collectionType: 'Song',
|
||||
selectedId: 42,
|
||||
selectedName: 'Stored Song'
|
||||
};
|
||||
|
||||
it('BLOCKER 1: a selection made DURING an in-flight refresh survives it — id and name stay one unit', async () => {
|
||||
// The server will answer with the STORED selection (id 42) and no name — the exact shape that
|
||||
// let the round-1 merge pair id 42 with the name of whatever the user had just picked.
|
||||
const { fetchMock, releaseDetail } = mockWithDelayedDetail(
|
||||
{ ...songRow, selectedName: null },
|
||||
songRow
|
||||
);
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
// The user picks a DIFFERENT song while the refresh is still in flight.
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Change' }));
|
||||
const input = await screen.findByLabelText('Song search');
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'New Song' } });
|
||||
fireEvent.click(await screen.findByRole('option', { name: 'New Song' }));
|
||||
|
||||
await releaseDetail();
|
||||
|
||||
// The chip and the saved id must agree. Round 1 showed "New Song" and saved 42.
|
||||
const chip = () => screen.getByLabelText(/^Clear /).closest('.ctv-picker-selected');
|
||||
expect(chip()?.textContent).toContain('New Song');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
await waitFor(() => {
|
||||
const put = fetchMock.mock.calls.find(
|
||||
([u, init]) => u === '/api/v1/rerun-collections/9' && (init?.method ?? '').toUpperCase() === 'PUT'
|
||||
);
|
||||
expect(put).toBeDefined();
|
||||
expect(JSON.parse(String(put?.[1]?.body)).selectedId).toBe(99);
|
||||
});
|
||||
});
|
||||
|
||||
it('BLOCKER 1: a deliberate CLEAR during an in-flight refresh is not resurrected', async () => {
|
||||
const { releaseDetail } = mockWithDelayedDetail(songRow, songRow);
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
fireEvent.click(await screen.findByLabelText('Clear Song'));
|
||||
await waitFor(() => expect(screen.getByLabelText('Song search')).toBeInTheDocument());
|
||||
|
||||
await releaseDetail();
|
||||
|
||||
// The refresh carries a perfectly good id 42 — and must still not undo the user's clear.
|
||||
expect(screen.getByLabelText('Song search')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/^Clear /)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('BLOCKER 1: a type switch during an in-flight refresh is not reverted', async () => {
|
||||
const { releaseDetail } = mockWithDelayedDetail(songRow, songRow);
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
|
||||
const typeSelect = (await screen.findAllByRole('combobox'))[0];
|
||||
fireEvent.change(typeSelect, { target: { value: 'Movie' } });
|
||||
await waitFor(() => expect(screen.getByLabelText('Movie search')).toBeInTheDocument());
|
||||
|
||||
await releaseDetail();
|
||||
|
||||
// Reverting the type while keeping the (now cleared) selection would leave a draft whose type
|
||||
// and selection disagree — a broken form and a failed save.
|
||||
expect((typeSelect as HTMLSelectElement).value).toBe('Movie');
|
||||
expect(screen.getByLabelText('Movie search')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('Song search')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// ---- #651 review round 3 ----
|
||||
|
||||
it('CRITICAL: conflict Reload DISCARDS the local selection, even when the server omits the id', async () => {
|
||||
// The lost-update shape: the user retargets a RemoteStream rerun, hits a 412, and explicitly
|
||||
// chooses Reload. Because the reloaded record reports `selectedId: null` (the #671 server gap),
|
||||
// a refresh-policy fallback would keep the user's DIRTY id, install the fresh ETag, and let the
|
||||
// next Save overwrite the collaborator's selection with edits the user asked to throw away.
|
||||
const remoteRow = { ...storedSelection, collectionType: 'RemoteStream', selectedId: 42, selectedName: 'Stored Stream' };
|
||||
let detailCalls = 0;
|
||||
|
||||
const fetchMock = mockApi({
|
||||
browsePage: { page: [{ id: 99, mediaItemId: 99, mediaType: 'RemoteStream', title: 'New Stream' }], totalCount: 1 },
|
||||
list: [remoteRow],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
// Both the initial load and the reload come back with the #671 null selection.
|
||||
return jsonResponse({ ...remoteRow, selectedId: null, selectedName: null });
|
||||
}
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'PUT') {
|
||||
// First Save conflicts; a later one would succeed.
|
||||
return detailCalls > 1 ? jsonResponse({ id: 9 }, 200) : new Response(null, { status: 412 });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
|
||||
// Retarget the selection, then hit the conflict.
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Change' }));
|
||||
const input = await screen.findByLabelText('Remote Stream search');
|
||||
fireEvent.focus(input);
|
||||
fireEvent.change(input, { target: { value: 'New Stream' } });
|
||||
fireEvent.click(await screen.findByRole('option', { name: 'New Stream' }));
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Reload' }));
|
||||
|
||||
await waitFor(() => expect(detailCalls).toBe(2));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
// The reload took the server's record WHOLESALE: no selection, so nothing to re-save over the
|
||||
// collaborator's change. Save is disabled precisely because the server says there is no
|
||||
// selection — that is honest, where silently keeping id 99 was a cross-user lost update.
|
||||
expect(screen.queryByText('New Stream')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText(/^Clear /)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeDisabled();
|
||||
|
||||
// And nothing was written after the 412.
|
||||
const puts = fetchMock.mock.calls.filter(
|
||||
([u, init]) => u === '/api/v1/rerun-collections/9' && (init?.method ?? '').toUpperCase() === 'PUT'
|
||||
);
|
||||
expect(puts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('HIGH: a server-side TYPE change takes its selection whole — no cross-type id survives', async () => {
|
||||
it('a server-side TYPE change is adopted whole — no cross-type id survives', async () => {
|
||||
// The list opened a Collection (id 5, "Favorites"); by the time the detail GET lands the record
|
||||
// has been changed to RemoteStream, whose response carries the #671 null selection. Hydrating
|
||||
// the type while retaining the old id would display and save a Collection id as a RemoteStream.
|
||||
// has been changed to RemoteStream, whose response carries the #671 null selection. The draft
|
||||
// comes wholly from that response, so the Collection id cannot leak into the RemoteStream
|
||||
// namespace — the defect this originally caught, now prevented structurally rather than by a
|
||||
// merge rule (#651 round 3 HIGH, round 5 redesign).
|
||||
let detailCalls = 0;
|
||||
mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'Collection', selectedId: 5, selectedName: 'Favorites' }],
|
||||
@@ -855,39 +540,24 @@ describe('RerunCollectionsScreen', () => {
|
||||
expect(within(picker()).queryByText('Favorites')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('HIGH-3: a touched selection contradicting the server type is a CONFLICT, not a hydrate', async () => {
|
||||
// The list row is stale: it says Collection/5, but a collaborator has already retyped the
|
||||
// record to SmartCollection/8. The user picks Collection/9 before the detail GET returns.
|
||||
// Pinning their old-type identity while installing the response's NEW ETag would authorize a
|
||||
// Save that silently overwrites the collaborator's type change with no 412 (#651 round 4
|
||||
// HIGH-3).
|
||||
|
||||
// ---- #651 review round 5: the editor initializes ONCE, from the detail GET ----
|
||||
//
|
||||
// Every reconciliation test above was deleted with the machinery it exercised. Rounds 2-4 each
|
||||
// produced a HIGH finding in the layer that merged a late detail response into a draft the user
|
||||
// was already editing; round 5 removed the race instead of refereeing it. What is asserted now is
|
||||
// the ABSENCE of that surface: there is no editable draft until the record lands, so there is
|
||||
// nothing to reconcile, nothing to pin, and no way to pair one record's id with another's ETag.
|
||||
|
||||
it('renders no editable form until the detail GET lands — there is no draft to reconcile', async () => {
|
||||
const detailRelease: { resolve: (() => void) | null } = { resolve: null };
|
||||
let detailCalls = 0;
|
||||
|
||||
const fetchMock = mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'Collection', selectedId: 5, selectedName: 'Favorites' }]
|
||||
});
|
||||
|
||||
// Count in the OUTER implementation: it short-circuits the detail GET before mockApi's own
|
||||
// handlers (and its `onRequest` hook) ever see it.
|
||||
const fetchMock = mockApi({ list: [storedSelection] });
|
||||
const inner = fetchMock.getMockImplementation() as (i: RequestInfo | URL, r?: RequestInit) => Promise<Response>;
|
||||
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
if (url === '/api/v1/rerun-collections/9' && (init?.method ?? 'GET').toUpperCase() === 'GET') {
|
||||
detailCalls += 1;
|
||||
return new Promise<Response>((resolve) => {
|
||||
detailRelease.resolve = () =>
|
||||
resolve(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
...storedSelection,
|
||||
collectionType: 'SmartCollection',
|
||||
selectedId: 8,
|
||||
selectedName: 'Collaborator Smart'
|
||||
}),
|
||||
{ headers: { 'Content-Type': 'application/json', ETag: '"v9-newest"' }, status: 200 }
|
||||
)
|
||||
);
|
||||
detailRelease.resolve = () => resolve(jsonResponse(storedSelection));
|
||||
});
|
||||
}
|
||||
return inner(input, init);
|
||||
@@ -895,79 +565,133 @@ describe('RerunCollectionsScreen', () => {
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
|
||||
// The user retargets within the (stale) Collection type while the GET is in flight.
|
||||
const collectionPicker = (await screen.findAllByRole('combobox'))[1];
|
||||
fireEvent.change(collectionPicker, { target: { value: '5' } });
|
||||
// Loading, not an editable form seeded from the list row.
|
||||
expect(await screen.findByText('Loading rerun collection…')).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('Rerun collection name')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Save rerun collection' })).not.toBeInTheDocument();
|
||||
|
||||
detailRelease.resolve?.();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
// The collision surfaces as the existing conflict dialog rather than a silent reconcile.
|
||||
const conflict = await screen.findByRole('dialog');
|
||||
expect(within(conflict).getByRole('button', { name: 'Reload' })).toBeInTheDocument();
|
||||
expect(within(conflict).getByText(/your unsaved changes will be discarded/i)).toBeInTheDocument();
|
||||
expect(await screen.findByPlaceholderText('Rerun collection name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('MEDIUM-4: edits made while a Reload is pending are refused, not silently erased', async () => {
|
||||
const reloadRelease: { resolve: (() => void) | null } = { resolve: null };
|
||||
let detailCalls = 0;
|
||||
|
||||
const fetchMock = mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'Collection', selectedId: 5, selectedName: 'Favorites' }],
|
||||
it('takes the draft SOLELY from the detail GET — the list row is never a source', async () => {
|
||||
// The list row is stale in every field. None of it may reach the editor: in production it is
|
||||
// strictly less informative than the detail read (#671 — the list handler applies no Includes).
|
||||
mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'Collection', name: 'Stale List Name', selectedId: 5, selectedName: 'Stale List Selection' }],
|
||||
onRequest: (url, method) =>
|
||||
url === '/api/v1/rerun-collections/9' && method === 'PUT' ? new Response(null, { status: 412 }) : null
|
||||
url === '/api/v1/rerun-collections/9' && method === 'GET'
|
||||
? jsonResponse({ ...storedSelection, collectionType: 'Collection', name: 'Server Name', selectedId: 5, selectedName: 'Favorites' })
|
||||
: null
|
||||
});
|
||||
|
||||
const inner = fetchMock.getMockImplementation() as (i: RequestInfo | URL, r?: RequestInit) => Promise<Response>;
|
||||
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input.toString();
|
||||
if (url === '/api/v1/rerun-collections/9' && (init?.method ?? 'GET').toUpperCase() === 'GET') {
|
||||
detailCalls += 1;
|
||||
if (detailCalls === 1) {
|
||||
return Promise.resolve(
|
||||
jsonResponse({ ...storedSelection, collectionType: 'Collection', selectedId: 5, selectedName: 'Favorites' })
|
||||
);
|
||||
}
|
||||
// The RELOAD: held open so the user can try to type into a doomed draft.
|
||||
return new Promise<Response>((resolve) => {
|
||||
reloadRelease.resolve = () =>
|
||||
resolve(
|
||||
jsonResponse({
|
||||
...storedSelection,
|
||||
collectionType: 'Collection',
|
||||
name: 'Server Name',
|
||||
selectedId: 5,
|
||||
selectedName: 'Favorites'
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
return inner(input, init);
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stale List Name'));
|
||||
|
||||
const nameInput = (await screen.findByPlaceholderText('Rerun collection name')) as HTMLInputElement;
|
||||
expect(nameInput.value).toBe('Server Name');
|
||||
expect(screen.queryByText('Stale List Selection')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('a failed detail GET shows an error instead of an editable form', async () => {
|
||||
mockApi({
|
||||
list: [storedSelection],
|
||||
onRequest: (url, method) =>
|
||||
url === '/api/v1/rerun-collections/9' && method === 'GET' ? new Response(null, { status: 500 }) : null
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
await waitFor(() => expect(detailCalls).toBe(1));
|
||||
|
||||
expect(await screen.findByRole('alert')).toBeInTheDocument();
|
||||
// Editing a draft that was never loaded is what produced every reconciliation defect.
|
||||
expect(screen.queryByPlaceholderText('Rerun collection name')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Save rerun collection' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('Save always carries If-Match — a draft cannot exist without its ETag', async () => {
|
||||
// The round-4 false-conflict hole: a path that produced a draft but left `etagRef` null made the
|
||||
// next PUT a FORCE-WRITE. Writing the ETag in the same callback that sets the draft makes that
|
||||
// unreachable by construction; this pins it.
|
||||
const fetchMock = mockApi({
|
||||
list: [storedSelection],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
return new Response(JSON.stringify(storedSelection), {
|
||||
headers: { 'Content-Type': 'application/json', ETag: '"v7"' },
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
return url === '/api/v1/rerun-collections/9' && method === 'PUT' ? jsonResponse({ id: 9 }, 200) : null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
await screen.findByPlaceholderText('Rerun collection name');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
|
||||
await waitFor(() => {
|
||||
const put = fetchMock.mock.calls.find(
|
||||
([u, init]) => u === '/api/v1/rerun-collections/9' && (init?.method ?? '').toUpperCase() === 'PUT'
|
||||
);
|
||||
expect(put).toBeDefined();
|
||||
expect((put?.[1]?.headers as Record<string, string>)['If-Match']).toBe('"v7"');
|
||||
});
|
||||
});
|
||||
|
||||
it('412 -> Reload discards local edits by unmounting the form, then re-initializes from the server', async () => {
|
||||
let detailCalls = 0;
|
||||
const fetchMock = mockApi({
|
||||
list: [storedSelection],
|
||||
onRequest: (url, method) => {
|
||||
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
|
||||
detailCalls += 1;
|
||||
return jsonResponse({ ...storedSelection, name: detailCalls === 1 ? 'First Load' : 'Collaborator Name' });
|
||||
}
|
||||
return url === '/api/v1/rerun-collections/9' && method === 'PUT' ? new Response(null, { status: 412 }) : null;
|
||||
}
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
const nameInput = (await screen.findByPlaceholderText('Rerun collection name')) as HTMLInputElement;
|
||||
expect(nameInput.value).toBe('First Load');
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: 'My Local Edit' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
|
||||
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: 'Reload' }));
|
||||
|
||||
// The form is gone while the replacement is in flight — there is no window in which an edit can
|
||||
// be typed into a draft that is about to be discarded (round-4 MEDIUM-4, now structural).
|
||||
await waitFor(() => expect(detailCalls).toBe(2));
|
||||
const reloaded = (await screen.findByPlaceholderText('Rerun collection name')) as HTMLInputElement;
|
||||
expect(reloaded.value).toBe('Collaborator Name');
|
||||
expect(reloaded.value).not.toBe('My Local Edit');
|
||||
expect(fetchMock.mock.calls.filter(([u, i]) => u === '/api/v1/rerun-collections/9' && (i?.method ?? '').toUpperCase() === 'PUT')).toHaveLength(1);
|
||||
});
|
||||
|
||||
// The dialog is gone but the replacement has not landed: the editor must be inert and say so,
|
||||
// rather than accepting an edit it is about to throw away.
|
||||
expect(screen.getByText('Reloading…')).toBeInTheDocument();
|
||||
it('a #671 unnamed selection disables Save with a visible reason — it never silently saves a guess', async () => {
|
||||
// Replaces the F1 family. Under initialize-once there is no list-supplied id to preserve (there
|
||||
// never was one in production), so the honest outcome is: no selection, Save disabled, and the
|
||||
// badge says why. The defect to avoid is a SILENT one — saving something the server didn't say.
|
||||
mockApi({
|
||||
list: [{ ...storedSelection, collectionType: 'RemoteStream' }],
|
||||
onRequest: (url, method) =>
|
||||
url === '/api/v1/rerun-collections/9' && method === 'GET'
|
||||
? jsonResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null })
|
||||
: null
|
||||
});
|
||||
|
||||
render(<RerunCollectionsScreen />);
|
||||
fireEvent.click(await screen.findByText('Stored Rerun'));
|
||||
await screen.findByPlaceholderText('Rerun collection name');
|
||||
|
||||
expect(screen.getByText('A selection is required')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeDisabled();
|
||||
|
||||
const nameInput = screen.getByPlaceholderText('Rerun collection name') as HTMLInputElement;
|
||||
fireEvent.change(nameInput, { target: { value: 'Edited While Pending' } });
|
||||
expect(nameInput.value).not.toBe('Edited While Pending');
|
||||
|
||||
reloadRelease.resolve?.();
|
||||
await waitFor(() => expect(screen.queryByText('Reloading…')).not.toBeInTheDocument());
|
||||
// The server's record won, and the doomed edit never existed.
|
||||
expect((screen.getByPlaceholderText('Rerun collection name') as HTMLInputElement).value).toBe('Server Name');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -229,109 +229,21 @@ function draftFromRerun(rerun: RerunCollection): Draft {
|
||||
};
|
||||
}
|
||||
|
||||
// Which draft fields the user has edited since the editor opened. The late edit-load refresh
|
||||
// hydrates ONLY untouched fields — see `hydrateDraft`. `selection` covers the id and its name
|
||||
// together, because they are one value, not two.
|
||||
type TouchedField = 'collectionType' | 'firstRunPlaybackOrder' | 'name' | 'rerunPlaybackOrder' | 'selection';
|
||||
|
||||
// `collectionType` + `selectedId` + `selectedName` are ONE domain value, not three fields. An id is
|
||||
// meaningless without the type that says which table it indexes, and a name is meaningless without
|
||||
// the id it names. Every rule below is about that whole unit; splitting any part of it off pairs
|
||||
// one selection's component with another's:
|
||||
// - id vs name -> the chip shows what the user picked while Save writes what the server sent
|
||||
// (#651 review round 2, BLOCKER 1);
|
||||
// - type vs id -> a Collection id is displayed and saved as a RemoteStream id
|
||||
// (#651 review round 3, HIGH).
|
||||
type Identity = Pick<Draft, 'collectionType' | 'selectedId' | 'selectedName'>;
|
||||
|
||||
function identityOf(draft: Draft): Identity {
|
||||
return {
|
||||
collectionType: draft.collectionType,
|
||||
selectedId: draft.selectedId,
|
||||
selectedName: draft.selectedName
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve the id/name pair WITHIN a single, agreed collection type. Only safe to call once the two
|
||||
// sides are known to share a type — a null id means "same item, unnamed" only in that case.
|
||||
function hydrateSelection(current: Draft, refreshed: Draft): Pick<Draft, 'selectedId' | 'selectedName'> {
|
||||
if (refreshed.selectedId == null) {
|
||||
// The server derives BOTH fields from the same eager-loaded navigation, so a naming gap
|
||||
// presents as `selectedId: null` on an otherwise-successful 200 (RemoteStream maps through
|
||||
// `_ => null`; Episode/MusicVideo 500 outright; Song/OtherVideo/Image resolve an id but not a
|
||||
// name). Clearing a stored id on the strength of that leaves the user unable to re-save at all,
|
||||
// since Save is gated on it. Server-side gap tracked as #671; this guard stays regardless.
|
||||
// NOTE this fallback is a REFRESH policy only — see `replaceDraft` for why a conflict reload
|
||||
// must never reach it.
|
||||
return { selectedId: current.selectedId, selectedName: current.selectedName };
|
||||
}
|
||||
|
||||
if (refreshed.selectedId === current.selectedId) {
|
||||
return { selectedId: refreshed.selectedId, selectedName: refreshed.selectedName || current.selectedName };
|
||||
}
|
||||
|
||||
return { selectedId: refreshed.selectedId, selectedName: refreshed.selectedName };
|
||||
}
|
||||
|
||||
// A touched local identity that contradicts the server's TYPE is not something to reconcile — it is
|
||||
// a conflict. Pinning the user's old-type identity while installing the response's newest ETag
|
||||
// authorizes a Save that silently overwrites the collaborator's type change with no 412 (#651 round
|
||||
// 4 HIGH-3 — the second cross-user lost update on this branch, so the category is "any path that
|
||||
// installs a save-authorizing ETag over a local edit the server contradicts").
|
||||
function identityConflicts(current: Draft, refreshed: Draft, touched: ReadonlySet<TouchedField>): boolean {
|
||||
return (
|
||||
(touched.has('collectionType') || touched.has('selection')) &&
|
||||
refreshed.collectionType !== current.collectionType
|
||||
);
|
||||
}
|
||||
|
||||
function hydrateIdentity(current: Draft, refreshed: Draft, touched: ReadonlySet<TouchedField>): Identity {
|
||||
// Touching EITHER half pins the whole unit. `setCollectionType` already touches both, but a user
|
||||
// who only changed the selection has implicitly pinned the type too — it is the type their
|
||||
// chosen id belongs to, so letting the type hydrate underneath it recreates the cross-type bug.
|
||||
// (When that pin CONTRADICTS the server's type the caller must treat it as a conflict rather than
|
||||
// hydrate at all — see `identityConflicts`.)
|
||||
if (touched.has('collectionType') || touched.has('selection')) {
|
||||
return identityOf(current);
|
||||
}
|
||||
|
||||
// The type changed server-side while we were loading. The id we hold indexes the OLD type's
|
||||
// table, so it cannot be carried across — take the refresh's unit whole, null selection included.
|
||||
if (refreshed.collectionType !== current.collectionType) {
|
||||
return identityOf(refreshed);
|
||||
}
|
||||
|
||||
// Same type on both sides: now, and only now, the #671 id/name fallback is meaningful.
|
||||
return { collectionType: refreshed.collectionType, ...hydrateSelection(current, refreshed) };
|
||||
}
|
||||
|
||||
// REFRESH: a late load must not overwrite what the user has already edited. Anything else
|
||||
// resurrects a deliberate clear, reverts a type switch, or overwrites a fresh selection with the
|
||||
// stored one — all silently, because a hydrate looks like a render.
|
||||
function hydrateDraft(current: Draft, rerun: RerunCollection, touched: ReadonlySet<TouchedField>): Draft {
|
||||
const refreshed = draftFromRerun(rerun);
|
||||
|
||||
return {
|
||||
firstRunPlaybackOrder: touched.has('firstRunPlaybackOrder')
|
||||
? current.firstRunPlaybackOrder
|
||||
: refreshed.firstRunPlaybackOrder,
|
||||
name: touched.has('name') ? current.name : refreshed.name,
|
||||
rerunPlaybackOrder: touched.has('rerunPlaybackOrder') ? current.rerunPlaybackOrder : refreshed.rerunPlaybackOrder,
|
||||
...hydrateIdentity(current, refreshed, touched)
|
||||
};
|
||||
}
|
||||
|
||||
// REPLACE: the conflict "Reload" path, which exists to THROW LOCAL EDITS AWAY and adopt the
|
||||
// collaborator's state. It must take the server's record wholesale — including a null selection.
|
||||
// Routing it through the refresh policy was a cross-user lost update (#651 review round 3,
|
||||
// CRITICAL): with the #671 gap the reloaded record reports `selectedId: null`, `hydrateSelection`
|
||||
// fell back to the DIRTY local pair, the fresh ETag was installed, and the next Save silently
|
||||
// overwrote the collaborator's selection with the edits the user had just asked to discard.
|
||||
// It is a separate function, not a flag on the refresh path, so the two policies cannot be
|
||||
// confused at the call site.
|
||||
function replaceDraft(rerun: RerunCollection): Draft {
|
||||
return draftFromRerun(rerun);
|
||||
}
|
||||
// NOTE (#651 review round 5): there is deliberately NO draft-reconciliation machinery here — no
|
||||
// touched-field tracking, no field-wise hydrate, no conflict predicate. Every one of those existed
|
||||
// to merge a late detail response into a draft the user was already editing, and that reconciliation
|
||||
// surface produced a HIGH finding in three consecutive review rounds, including three cross-user
|
||||
// lost updates. The race is removed rather than refereed: the draft is initialized EXACTLY ONCE,
|
||||
// from the detail GET, and the form does not exist until it lands.
|
||||
//
|
||||
// Seeding from the list row (which is what created the race) could never have helped anyway:
|
||||
// `GetPagedRerunCollectionsHandler` applies ZERO `.Include()`s while `GetRerunCollectionByIdHandler`
|
||||
// applies fourteen, and both project through the same `ProjectToResponseModel`, which derives
|
||||
// `selectedId`/`selectedName` from those navigations. The list response is therefore a strict SUBSET
|
||||
// of the detail one — it can never supply an id the detail lacks (see #671).
|
||||
//
|
||||
// Conflicts are detected where they belong: at save time, by `If-Match` -> 412 -> Reload, which
|
||||
// already existed and already works. Reload re-runs this same initialize-once path.
|
||||
|
||||
function RerunCollectionEditor({
|
||||
initial,
|
||||
@@ -342,9 +254,13 @@ function RerunCollectionEditor({
|
||||
onBack: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Draft>(() =>
|
||||
// ONE source of truth, set ONCE. `null` means "not loaded yet" — the form does not render, so
|
||||
// there is no draft for a late response to reconcile against and no window in which the user can
|
||||
// edit something that is about to be replaced. A NEW record starts from defaults immediately
|
||||
// because it has nothing to load.
|
||||
const [draft, setDraft] = useState<Draft | null>(() =>
|
||||
initial
|
||||
? draftFromRerun(initial)
|
||||
? null
|
||||
: {
|
||||
collectionType: 'Collection',
|
||||
firstRunPlaybackOrder: 'Chronological',
|
||||
@@ -363,101 +279,59 @@ function RerunCollectionEditor({
|
||||
const [pickerError, setPickerError] = useState<string | null>(null);
|
||||
const [pickerHint, setPickerHint] = useState<PickerLoadResult['hint']>('none');
|
||||
const pickerHelpId = useId();
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [conflictOpen, setConflictOpen] = useState(false);
|
||||
// The load's MODE travels with its key so the two policies can never be confused: 'hydrate' is
|
||||
// the mount refresh (protect user edits, tolerate a #671 unnamed selection), 'replace' is the
|
||||
// conflict reload (adopt the server's record wholesale, discarding local edits as promised).
|
||||
const [load, setLoad] = useState<{ key: number; mode: 'hydrate' | 'replace' }>({ key: 0, mode: 'hydrate' });
|
||||
// True from the moment Reload is confirmed until the replacement lands. The dialog closes
|
||||
// immediately, so without this the user can keep editing a draft that is about to be thrown away
|
||||
// — the response would silently erase those edits AND reset the touched set that protected them
|
||||
// (#651 round 4 MEDIUM-4). Edits are refused for the duration rather than queued: the whole
|
||||
// point of Reload is that the local state is being discarded.
|
||||
const [replacePending, setReplacePending] = useState(false);
|
||||
// Bumped by the conflict Reload to re-run the initialize-once load. Reload needs no separate
|
||||
// "replace" policy: dropping the draft back to `null` IS the replace.
|
||||
const [loadKey, setLoadKey] = useState(0);
|
||||
// Concurrency ETag (issue #253): captured from the single-record GET when editing an existing
|
||||
// rerun collection, sent as If-Match on save. There's no rotation-on-save because the editor
|
||||
// always returns to the list after a successful save (see onSaved below).
|
||||
// rerun collection, sent as If-Match on save. It is written in the same callback that sets the
|
||||
// draft, so a draft can never exist without the ETag that authorizes saving it — which is what
|
||||
// makes an accidental force-write (a PUT with no If-Match) unreachable.
|
||||
const etagRef = useRef<string | null>(null);
|
||||
// Fields the user has edited. A ref, not state: hydration reads it inside an async callback, and
|
||||
// it must never itself trigger a render.
|
||||
const touchedRef = useRef<Set<TouchedField>>(new Set());
|
||||
|
||||
// Every user edit goes through this, so "did the user touch it?" cannot drift from "did it
|
||||
// change?" — a field mutated anywhere else would silently become hydratable again.
|
||||
const edit = useCallback(
|
||||
(fields: TouchedField[], patch: (current: Draft) => Partial<Draft>) => {
|
||||
if (replacePending) {
|
||||
return;
|
||||
}
|
||||
const collectionType = draft?.collectionType;
|
||||
|
||||
for (const field of fields) {
|
||||
touchedRef.current.add(field);
|
||||
}
|
||||
setDraft((current) => ({ ...current, ...patch(current) }));
|
||||
},
|
||||
[replacePending]
|
||||
);
|
||||
|
||||
const { collectionType } = draft;
|
||||
|
||||
// Re-fetch the record's ETag (and current data, on a conflict reload) when editing an existing
|
||||
// rerun collection. Runs once on mount and again after reloadAfterConflict bumps the load key.
|
||||
// Initialize the draft from the detail GET — the ONLY place it is created for an existing record.
|
||||
// Re-runs on `loadKey` (the conflict Reload), which drops the draft back to `null` first, so the
|
||||
// form is unmounted while the replacement is in flight and there is nothing to edit or preserve.
|
||||
useEffect(() => {
|
||||
if (!initial) {
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const { mode } = load;
|
||||
|
||||
getRerunCollectionWithMeta(initial.id)
|
||||
.then((meta) => {
|
||||
if (active) {
|
||||
if (mode === 'replace') {
|
||||
// Adopt the server's record and forget every local edit — including the touched set,
|
||||
// which is what made those edits sticky in the first place.
|
||||
etagRef.current = meta.etag;
|
||||
touchedRef.current = new Set();
|
||||
setDraft(replaceDraft(meta.data));
|
||||
setReplacePending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setDraft((current) => {
|
||||
if (identityConflicts(current, draftFromRerun(meta.data), touchedRef.current)) {
|
||||
// Do NOT install the new ETag: it would authorize a Save that overwrites the type
|
||||
// change we just learned about. Leaving the stale ETag means even a forced Save gets
|
||||
// a 412 rather than clobbering — belt and braces with the dialog below.
|
||||
setConflictOpen(true);
|
||||
return current;
|
||||
}
|
||||
|
||||
etagRef.current = meta.etag;
|
||||
return hydrateDraft(current, meta.data, touchedRef.current);
|
||||
});
|
||||
// ETag and draft are written together and only here, so `draft != null` implies an ETag.
|
||||
etagRef.current = meta.etag;
|
||||
setDraft(draftFromRerun(meta.data));
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (active) {
|
||||
// Unfreeze on failure as well — a stuck `replacePending` would leave the editor
|
||||
// permanently read-only with no way back.
|
||||
setReplacePending(false);
|
||||
setSaveError(messageFromRerunCollectionError(error, 'Unable to load rerun collection'));
|
||||
setLoadError(messageFromRerunCollectionError(error, 'Unable to load rerun collection'));
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [initial, load]);
|
||||
}, [initial, loadKey]);
|
||||
|
||||
// Load the picker list for the active type. Resets only in the async callbacks (never
|
||||
// synchronously in the effect body) per spa-conventions §3. Uses an AbortController so a type
|
||||
// switch mid-load (a Class A `loadAllPages` loop, e.g. multi-collections) stops issuing further
|
||||
// requests rather than just discarding the eventual result (#644 follow-up F2).
|
||||
useEffect(() => {
|
||||
if (collectionType === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
loadPickerOptions(collectionType, controller.signal)
|
||||
@@ -481,28 +355,7 @@ function RerunCollectionEditor({
|
||||
};
|
||||
}, [collectionType]);
|
||||
|
||||
// A type switch clears the selection and rewrites both orders, so it dirties all four.
|
||||
const setCollectionType = (type: RerunCollectionType) => {
|
||||
edit(['collectionType', 'firstRunPlaybackOrder', 'rerunPlaybackOrder', 'selection'], () => ({
|
||||
collectionType: type,
|
||||
firstRunPlaybackOrder: defaultOrderFor(type),
|
||||
rerunPlaybackOrder: defaultOrderFor(type),
|
||||
selectedId: null,
|
||||
selectedName: ''
|
||||
}));
|
||||
};
|
||||
|
||||
const setSelected = (value: string) => {
|
||||
const id = value === '' ? null : Number(value);
|
||||
const match = pickerItems.find((item) => item.id === id);
|
||||
edit(['selection'], (current) => ({ selectedId: id, selectedName: match?.name ?? current.selectedName }));
|
||||
};
|
||||
|
||||
// Only options loaded FOR the active type may be offered; anything else belongs to another id
|
||||
// namespace and must not be selectable, however briefly.
|
||||
const pickerItems = pickerFor !== null && pickerFor.type === collectionType ? pickerFor.items : [];
|
||||
|
||||
const activeConfig = COLLECTION_TYPES.find((entry) => entry.value === collectionType);
|
||||
// Computed before the early returns below: `useCallback` is a hook and must run on every render.
|
||||
const browseMediaType = COLLECTION_TYPES.find(
|
||||
(entry) => entry.value === collectionType && entry.source === 'browse'
|
||||
)?.browse;
|
||||
@@ -513,12 +366,61 @@ function RerunCollectionEditor({
|
||||
(query: string) => (browseMediaType ? searchLibraryPickerOptions(browseMediaType, query) : Promise.resolve([])),
|
||||
[browseMediaType]
|
||||
);
|
||||
|
||||
// Nothing to edit until the record has loaded. This early return is what removes the whole
|
||||
// reconciliation problem: below this line `draft` is non-null and immutable-by-anyone-but-the-user.
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className="ctv-settings-error" role="alert">
|
||||
<TriangleAlert aria-hidden="true" size={16} />
|
||||
<span>{loadError}</span>
|
||||
<Button onClick={onBack} size="sm" variant="secondary">
|
||||
All rerun collections
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!draft) {
|
||||
return (
|
||||
<div className="ctv-collections-loading" role="status">
|
||||
<Spinner size={18} />
|
||||
<span>Loading rerun collection…</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const patch = (delta: Partial<Draft>) => setDraft((current) => (current ? { ...current, ...delta } : current));
|
||||
|
||||
const setCollectionType = (type: RerunCollectionType) => {
|
||||
patch({
|
||||
collectionType: type,
|
||||
firstRunPlaybackOrder: defaultOrderFor(type),
|
||||
rerunPlaybackOrder: defaultOrderFor(type),
|
||||
selectedId: null,
|
||||
selectedName: ''
|
||||
});
|
||||
};
|
||||
|
||||
const setSelected = (value: string) => {
|
||||
const id = value === '' ? null : Number(value);
|
||||
const match = pickerItems.find((item) => item.id === id);
|
||||
setDraft((current) =>
|
||||
current ? { ...current, selectedId: id, selectedName: match?.name ?? current.selectedName } : current
|
||||
);
|
||||
};
|
||||
|
||||
// Only options loaded FOR the active type may be offered; anything else belongs to another id
|
||||
// namespace and must not be selectable, however briefly.
|
||||
const pickerItems = pickerFor !== null && pickerFor.type === draft.collectionType ? pickerFor.items : [];
|
||||
|
||||
const activeConfig = COLLECTION_TYPES.find((entry) => entry.value === draft.collectionType);
|
||||
const trimmedName = draft.name.trim();
|
||||
const validationError =
|
||||
trimmedName.length === 0 ? 'Name is required' : draft.selectedId == null ? 'A selection is required' : null;
|
||||
|
||||
const save = async () => {
|
||||
if (validationError || saving || replacePending || draft.selectedId == null) {
|
||||
if (validationError || saving || draft.selectedId == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -556,8 +458,11 @@ function RerunCollectionEditor({
|
||||
const reloadAfterConflict = () => {
|
||||
setConflictOpen(false);
|
||||
setSaveError(null);
|
||||
setReplacePending(true);
|
||||
setLoad((current) => ({ key: current.key + 1, mode: 'replace' }));
|
||||
// Dropping the draft IS the replace: the form unmounts, so there is no window in which the user
|
||||
// can edit something the incoming record is about to overwrite (#651 round 4 MEDIUM-4, now
|
||||
// structural rather than guarded).
|
||||
setDraft(null);
|
||||
setLoadKey((key) => key + 1);
|
||||
};
|
||||
|
||||
// Ensure the currently-selected item is always an option even if it isn't in the fetched
|
||||
@@ -571,8 +476,8 @@ function RerunCollectionEditor({
|
||||
...pickerItems.map((item) => ({ label: item.name, value: String(item.id) }))
|
||||
];
|
||||
|
||||
const firstRunOrderOptions = orderOptionsWithCurrent(collectionType, draft.firstRunPlaybackOrder);
|
||||
const rerunOrderOptions = orderOptionsWithCurrent(collectionType, draft.rerunPlaybackOrder);
|
||||
const firstRunOrderOptions = orderOptionsWithCurrent(draft.collectionType, draft.firstRunPlaybackOrder);
|
||||
const rerunOrderOptions = orderOptionsWithCurrent(draft.collectionType, draft.rerunPlaybackOrder);
|
||||
|
||||
return (
|
||||
<div className="ctv-collections">
|
||||
@@ -585,11 +490,10 @@ function RerunCollectionEditor({
|
||||
</span>
|
||||
<span className="ctv-channels-spacer" />
|
||||
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
|
||||
{replacePending && <Badge tone="neutral">Reloading…</Badge>}
|
||||
{!replacePending && validationError && <Badge tone="neutral">{validationError}</Badge>}
|
||||
{validationError && <Badge tone="neutral">{validationError}</Badge>}
|
||||
<Button
|
||||
disabled={validationError !== null || saving || replacePending}
|
||||
loading={saving || replacePending}
|
||||
disabled={validationError !== null || saving}
|
||||
loading={saving}
|
||||
onClick={() => void save()}
|
||||
size="sm"
|
||||
startIcon={<Check aria-hidden="true" size={14} />}
|
||||
@@ -601,7 +505,7 @@ function RerunCollectionEditor({
|
||||
<Card title="Rerun collection">
|
||||
<Input
|
||||
label="Name"
|
||||
onChange={(event) => edit(['name'], () => ({ name: event.target.value }))}
|
||||
onChange={(event) => patch({ name: event.target.value })}
|
||||
placeholder="Rerun collection name"
|
||||
value={draft.name}
|
||||
/>
|
||||
@@ -623,14 +527,14 @@ function RerunCollectionEditor({
|
||||
// before, during and after any search, and never silently loses it.
|
||||
<SearchPicker
|
||||
ariaDescribedBy={pickerHelpId}
|
||||
key={collectionType}
|
||||
key={draft.collectionType}
|
||||
label={activeConfig?.label ?? 'Selection'}
|
||||
minQueryLength={LIBRARY_PICKER_MIN_QUERY}
|
||||
onClear={() => edit(['selection'], () => ({ selectedId: null, selectedName: '' }))}
|
||||
onSelect={(id, name) => edit(['selection'], () => ({ selectedId: id, selectedName: name }))}
|
||||
onClear={() => patch({ selectedId: null, selectedName: '' })}
|
||||
onSelect={(id, name) => patch({ selectedId: id, selectedName: name })}
|
||||
placeholder={`Search ${(activeConfig?.label ?? 'items').toLowerCase()}…`}
|
||||
search={searchLibrary}
|
||||
source={collectionType}
|
||||
source={draft.collectionType}
|
||||
selectedId={draft.selectedId}
|
||||
selectedName={draft.selectedName || null}
|
||||
/>
|
||||
@@ -663,9 +567,7 @@ function RerunCollectionEditor({
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<Select
|
||||
label="First Run Playback Order"
|
||||
onChange={(event) =>
|
||||
edit(['firstRunPlaybackOrder'], () => ({ firstRunPlaybackOrder: event.target.value as PlaybackOrder }))
|
||||
}
|
||||
onChange={(event) => patch({ firstRunPlaybackOrder: event.target.value as PlaybackOrder })}
|
||||
options={firstRunOrderOptions}
|
||||
value={draft.firstRunPlaybackOrder}
|
||||
/>
|
||||
@@ -674,9 +576,7 @@ function RerunCollectionEditor({
|
||||
<div style={{ marginTop: 12 }}>
|
||||
<Select
|
||||
label="Rerun Playback Order"
|
||||
onChange={(event) =>
|
||||
edit(['rerunPlaybackOrder'], () => ({ rerunPlaybackOrder: event.target.value as PlaybackOrder }))
|
||||
}
|
||||
onChange={(event) => patch({ rerunPlaybackOrder: event.target.value as PlaybackOrder })}
|
||||
options={rerunOrderOptions}
|
||||
value={draft.rerunPlaybackOrder}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user