feat(651): library-browse pickers resolve by search, not a 100-row window #678

Merged
timothy merged 11 commits from feat/651-searchable-pickers into main 2026-07-27 05:47:07 +02:00
27 changed files with 3225 additions and 322 deletions
+1 -1
View File
@@ -164,7 +164,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `spa.deco-templates-table` | The deco-templates editor also renders its day/deco assignment as a table, extending (not replacing) the templates-editor-table convention. | 2026-07-09 | [link](records/spa/deco-templates-table.md) |
| `spa.download-sample-gate` | The SPA disables both Download Media Sample and Download Results while a troubleshooting session is starting/running (Blazor only gated Download Results). | 2026-07-09 | [link](records/spa/download-sample-gate.md) |
| `spa.legacy-redirect-matcher` | `LegacyUiRedirects.TryGetRedirect` is a two-tier matcher — an exact `OrdinalIgnoreCase` `Map` (Tier 1) then an ordered segment-template pattern list (Tier 2, first-match-wins) — collision-free by construction, with a guard invariant that no rule may prefix-match `/api`, `/artwork`, `/docs`, `/openapi`, `/iptv`, `/app`, or `/media/sources`. | 2026-07-11 | [link](records/spa/legacy-redirect-matcher.md) |
| `spa.list-completeness-vs-bounded-pickers` | The shared `loadAllPages` helper (`web/src/api/paging.ts`) pages a `/api/v1` list to completeness against `totalCount` and is used ONLY for lists that are bounded by construction (rerun collections, multi-collections, playlists — admin-created, hundreds of rows at most). A `getLibraryBrowseItems` picker over a media-library table (Episode/Song/Image/Movie/MusicVideo, tens of thousands of rows possible) must NOT page to completeness — it fetches ONE bounded page (the server cap) and surfaces the truncation (a `ctv-field-help` hint wired to the real `totalCount`) instead of silently dropping the rest. | 2026-07-26 | [link](records/spa/list-completeness-vs-bounded-pickers.md) |
| `spa.library-pickers-resolve-by-search` | 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 draft is INITIALIZED ONCE from the detail read — never seeded from the list row, never reconciled against a late response — with the form withheld until it lands, the editor failing CLOSED when the response carries no USABLE concurrency token — absent, empty and whitespace-only ETags are ONE case, normalized in one place, so a PUT without `If-Match` is unreachable, and a deadline plus a route back so a hung request cannot strand it. 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; and every id entering editor state — search result, list-backed option, or a selection restored from a detail read — passes ONE shared `isSelectionId` (int32) predicate at that boundary, an unbindable id being treated as ABSENT rather than coerced. Conflicts are detected at SAVE time via `If-Match` -> 412 -> Reload, and Reload simply drops the draft back to null and re-runs the same initialize-once load, so the form is unmounted while the replacement is in flight; 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. | 2026-07-26 | [link](records/spa/library-pickers-resolve-by-search.md) |
| `spa.logs-page-size-local` | The Logs page rows-per-page preference is stored in `window.localStorage` (`ctv-logs-page-size`), not a server `ConfigElement`. | 2026-07-11 | [link](records/spa/logs-page-size-local.md) |
| `spa.playback-troubleshoot-poll` | The playback-troubleshooting screen reports FFmpeg completion by polling `GET /api/troubleshoot/playback/status` (~2s) rather than a server push channel. | 2026-07-09 | [link](records/spa/playback-troubleshoot-poll.md) |
| `spa.playout-reset-button` | The SPA keeps a single Reset action (server picks the default build mode) and drops Blazor's separate "Schedule reset" button since its capability already exists via the playout's Edit-details flow. | 2026-07-09 | [link](records/spa/playout-reset-button.md) |
@@ -1,13 +1,13 @@
---
key: spa.list-completeness-vs-bounded-pickers
title: '2026-07-26 — `loadAllPages` is for bounded-by-construction lists only; media-library pickers stay bounded and show truncation (#644 follow-up)'
status: active
status: superseded
since: '2026-07-26'
supersedes: none
superseded-by: none
rule: 'The shared `loadAllPages` helper (`web/src/api/paging.ts`) pages a `/api/v1` list to completeness against `totalCount` and is used ONLY for lists that are bounded by construction (rerun collections, multi-collections, playlists — admin-created, hundreds of rows at most). A `getLibraryBrowseItems` picker over a media-library table (Episode/Song/Image/Movie/MusicVideo, tens of thousands of rows possible) must NOT page to completeness — it fetches ONE bounded page (the server cap) and surfaces the truncation (a `ctv-field-help` hint wired to the real `totalCount`) instead of silently dropping the rest.'
superseded-by: spa.library-pickers-resolve-by-search@2026-07-26
rule: '(superseded) The shared `loadAllPages` helper (`web/src/api/paging.ts`) pages a `/api/v1` list to completeness against `totalCount` and is used ONLY for lists that are bounded by construction (rerun collections, multi-collections, playlists — admin-created, hundreds of rows at most). A `getLibraryBrowseItems` picker over a media-library table (Episode/Song/Image/Movie/MusicVideo, tens of thousands of rows possible) must NOT page to completeness — it fetches ONE bounded page (the server cap) and surfaces the truncation (a `ctv-field-help` hint wired to the real `totalCount`) instead of silently dropping the rest.'
signals: '`loadAllPages`, Class A vs Class B picker, LuceneSearchIndex.Search hitsLimit, picker truncation hint, ctv-field-help, PagedResult, `complete` flag · paths: `web/src/api/paging.ts`, `web/src/screens/RerunCollectionsScreen.tsx`, `web/src/screens/PlaylistsScreen.tsx`, `web/src/screens/FillerPresetsScreen.tsx`, `web/src/screens/MultiCollectionsScreen.tsx`, `docs/spa-conventions.md` §3b · issues: #644'
mechanics: '`docs/spa-conventions.md` §3b'
mechanics: 'superseded by `spa.library-pickers-resolve-by-search` (ersatztv#651) — Class A (`loadAllPages` for bounded-by-construction lists) survives there unchanged; only the Class B rule is reversed. See `docs/spa-conventions.md` §3b'
---
`fe342a6a` (#644) extracted the `loadAllPages` client-side paging helper and applied it at every
@@ -0,0 +1,198 @@
---
key: spa.library-pickers-resolve-by-search
title: '2026-07-26 — a media-library picker resolves by SEARCH, never by a window over the type; `loadAllPages` stays for bounded-by-construction lists (#651)'
status: active
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 draft is INITIALIZED ONCE from the detail read — never seeded from the list row, never reconciled against a late response — with the form withheld until it lands, the editor failing CLOSED when the response carries no USABLE concurrency token — absent, empty and whitespace-only ETags are ONE case, normalized in one place, so a PUT without `If-Match` is unreachable, and a deadline plus a route back so a hung request cannot strand it. 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; and every id entering editor state — search result, list-backed option, or a selection restored from a detail read — passes ONE shared `isSelectionId` (int32) predicate at that boundary, an unbindable id being treated as ABSENT rather than coerced. Conflicts are detected at SAVE time via `If-Match` -> 412 -> Reload, and Reload simply drops the draft back to null and re-runs the same initialize-once load, so the form is unmounted while the replacement is in flight; 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, initialize-once draft not hydrate-merge, no list-row seeding, fail closed on a missing or blank ETag, usable concurrency token, cross-type id, id never travels without its namespace, results keyed on (source query), failed search not cached as empty, selection id int32 boundary predicate, isSelectionId, 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'
---
#644 fixed a silent truncation: three `getLibraryBrowseItems` pickers asked for an over-cap
`pageSize` and got the server's `MaxPageSize` back with no indication. Its follow-up review
(`spa.list-completeness-vs-bounded-pickers`) correctly refused to "fix" that by paging to
completeness — ~200 serial requests against a 20,000-row table, each more expensive than the last
(`LuceneSearchIndex.Search` computes `hitsLimit = skip + limit`), ending in a `<select>` with
20,000 `<option>` nodes — and settled on one bounded page plus a visible `Showing the first 100 of
5000 — use search to narrow.` hint. That removed the *silence*. It did not remove the
*unusability*: a 100-row window over Episode or Song is not a picker, it is an arbitrary alphabetical
prefix, and the hint pointed at a search box that did not exist. The record said so itself, deferring
"a full typeahead/search-driven picker over the media library" to a follow-up issue. This is that
issue.
**The fix is to stop windowing and start searching.** `getLibraryBrowseItems` already took a `query`
param (`CollectionsScreen`/`SmartCollectionDialog` were already using it). The three pickers —
`RerunCollectionsScreen`, `PlaylistsScreen`, `FillerPresetsScreen` — now render the existing
`SearchPicker` for their media-library types instead of a `<Select>`, backed by one shared
`searchLibraryPickerOptions(mediaType, text)`. Selecting a media-library type now issues **zero**
requests; a settled query issues **one**, for at most 25 rows. Both bounds are properties of the
helper, not of a caller's discipline, and are pinned by request-count assertions against a
20,000-row fixture rather than by inspection.
**Typed text is compiled, never forwarded.** The rule from #440's Auto-Tune add-source typeahead now
binds here too, and its helper is shared rather than re-implemented: `titleContainsQuery` moved out
of `AutoTuneScreen` into `web/src/api/libraryBrowse.ts`. The search index's default field does not
match bare title words — `Alpha` finds nothing for "Show Alpha" — so forwarding the literal text the
way an explicit query box does would look broken in a *name* picker. Every Lucene special (and
whitespace) is escaped so the boundary stars are the only live wildcards, the same shape
`builder/rules/compile.ts` emits for `contains`.
**The already-selected item is preserved by rendering it from the record, not the result set.** This
is the failure mode that would make a search picker *worse* than the windowed one: a user opening an
existing record must see what it points at, before typing anything and after any search that doesn't
happen to include it. `SearchPicker` already renders `selectedName` independently of `results`, and
rerun collections and playlist items already carry that name on their own DTOs. `FillerPresetFullResponseModel`
does **not** — it stores only the id — so the edit path resolves the name through a single by-id
detail read (`/api/v1/shows|seasons|artists/{id}`), which is *stricter* than the behaviour it
replaces: the old picker could only name a selection that happened to fall inside the first 100
browse rows, and rendered a bare `#9999` otherwise. A failed resolution degrades to `#id`; it never
clears the id.
A cold cross-family review found that "renders from the record" was not by itself enough, because
the *record* can arrive without its selection. `RerunCollectionsController.ProjectToResponseModel`
derives both `selectedId` and `selectedName` from the same eager-loaded navigation, and
`GetRerunCollectionByIdHandler` loads media metadata only for Show/Season/Artist/Movie while
`MediaCollections/Mapper` maps RemoteStream through `_ => null` — so opening a RemoteStream rerun
collection returned HTTP 200 with a null selection and the edit-load refresh *cleared a stored id*,
leaving Save permanently disabled. The rule is therefore stated as a prohibition on the client:
**no code path may clear a stored id it merely failed to name.** Every affected type (RemoteStream,
Episode, MusicVideo, Song, OtherVideo, Image) is covered by its own test. The underlying read-model
gaps are server-side, tracked as **#671**; this branch is web-only and the client guard stays after
that lands.
**The obvious form of that fix is worse than the bug, and this is the part worth remembering.** The
first attempt coalesced the two fields independently — `refreshed.selectedId ?? current.selectedId`
and `refreshed.selectedName || current.selectedName`. But an id and its display name are ONE value:
against a `Song` response (id resolves, name does not), a user selecting a different song while the
refresh was in flight got the *new* name paired with the *stored* id. The chip read "New Song" and
Save wrote 42 — the user's choice discarded with no error and no visual cue, where the original
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`
says which table an id indexes, `selectedId` picks the row, `selectedName` labels it. Splitting type
from id is the identical bug to splitting id from name — the editor displayed and would have saved
a Collection id as a RemoteStream id, when the record's type changed server-side mid-load. So the
whole `{collectionType, selectedId, selectedName}` unit resolves together: either half touched by
the user pins all of it; a differing type takes the response's unit whole (null selection included,
since an id from the old type's space cannot be carried across); and only once both sides agree on
the type does the id/name rule apply.
Hydration also **loses every race against the user**: a `touchedRef` records which fields have been
edited, through a single `edit()` funnel so "touched" cannot drift from "changed".
**Refresh and replace are different policies and must be different functions.** The same review
found a *cross-user lost update*, the worst defect in the series: the conflict "Reload" — which
exists to discard local edits — ran through the refresh path with a touched-set reset. Because the
reloaded record reports `selectedId: null` under the #671 gap, the keep-ours fallback restored the
user's **dirty** selection, the fresh ETag was installed, and the next Save silently overwrote the
collaborator's change with edits the user had explicitly asked to throw away. `replaceDraft` was made a separate function with the mode carried on the load — machinery that
round 5 then deleted outright along with the rest of the reconciliation layer. Every interleaving is tested by holding the detail response open, acting as the user, then
releasing it.
Symmetrically, a name resolved asynchronously is **keyed to the id it was resolved for** and refuses
to overwrite a label that already names a different id — otherwise a slow edit-load read landing
after the user picked something else labels the new selection with the old item's title while the
saved id says otherwise. Keying the render alone stops the mislabelling but still throws away the
newer, correct label, so both halves are needed.
**Scope: Lucene-backed types only.** `GetLibraryBrowseItemsHandler` applies `query` two different
ways — as a Lucene clause for media items, and as a plain SQL `LIKE` on `Name` for the
collection-family types (Collection / SmartCollection / MultiCollection / RerunCollection /
Playlist). A compiled `title:*x*` sent at the latter would be LIKE-matched literally and match
nothing. So `FillerPresetsScreen` marks only its media-item types `searchable`; its
collection-family types keep the bounded single-page load and the truncation hint, and the Class A
`loadAllPages` paths in the other two screens are untouched. The `api.search-allitems-paging`
precedent holds: the client bounds itself, the server cap is not raised.
**The generalisation that took four rounds: an id never travels without its namespace.** Rounds 2
and 3 made *hydration* treat `{collectionType, selectedId, selectedName}` as one value. Round 4 found
the same defect in three more places, because the fix had been applied to the one structure that was
named rather than to every structure that carries an id. A typeahead cached its results against the
query TEXT, so switching the search source with the same text made the re-query guard *suppress* the
new request and leave the previous namespace's hit clickable under the new label. List-backed
`<select>` options were normalised to `{id, name}`, dropping the type, so on a slow connection the
previous type's rows stayed selectable while the replacement loaded — on both screens. The rule that
covers all of them: **every result, option and cached result set carries its source, and identity is
compared as `(type, id)`.** `SearchPicker` now takes a required `source` prop (required, not
defaulted — a default would silently opt every caller out), and `pickerFor` tags list-backed options
with the type that produced them.
**Two cross-user lost updates make a category, not two incidents.** Round 3's was conflict-Reload
running through the refresh policy. Round 4's was subtler: a touched identity pinned against a
server-side type change is *correct*, but adopting the response's newest ETag alongside it authorized
a Save that silently overwrote the collaborator's change with no 412. The category is **never install
a save-authorizing ETag over a local edit the server contradicts** — such a collision is a conflict to
surface, not a state to reconcile. Relatedly, the Reload path now renders the editor inert while the
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 — 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
introduced by this change rather than a pre-existing gap. `SearchPicker` implements the ARIA
combobox pattern: `role="combobox"` with `aria-expanded`/`aria-controls`/`aria-autocomplete`,
Arrow/Home/End moving a virtual cursor exposed through `aria-activedescendant`, Enter committing,
Escape dismissing, and options as non-tab-stops. Two defects specific to an *asynchronous* combobox
also had to be closed: a stale result set was committable (highlight Alpha for "Al", retype "Be",
press Enter before the debounce — Enter selected Alpha), so the highlight now drops on input change
and the guard lives in the single `choose()` sink rather than on each call site (gating Enter while
leaving `onClick` open was the same defect in another modality, found a round later); and Escape
closed the popup while focus stayed in the input, where `onFocus` can never re-arm it, so the picker
was dead until the user blurred and refocused — typing and ArrowDown now both reopen it, without
re-querying results that are already current, since the duplicate response would reset the cursor
and leave Enter doing nothing.
Folded in from #578 (same components): the rule-builder facet typeahead arms on **focus** rather
than on mount, so an N-row rule tree no longer fires N unrequested `search/fields/*/values`
requests; and both it and `SearchPicker` now pair their `seqRef` stale-response guard with a shared
`useIsMountedRef` (`web/src/hooks.ts`) so a fetch resolving after unmount is dropped. Proving that
guard needs two tests, because React 19 no longer warns on a setState-after-unmount and an unmounted
tree renders nothing either way: a unit test of the hook (including a StrictMode double-invoke for
the re-arm) plus an integration test that mocks the hook module and asserts `SearchPicker` actually
read `current` and saw `false`. #578's remaining item — extending the `artist` facet source beyond
entity artists — is a `GetSearchFieldValuesHandler` change, out of scope for a web-only fix, and is
being done on its own branch.
*(Over the 60-line prose ceiling: checked for redundancy against
`spa.list-completeness-vs-bounded-pickers` in `archive/` and declined to cut. The length is six
distinct findings — the search bound, the compile rule, selection preservation, the
clear-what-you-cannot-name prohibition, the async-name keying, and the keyboard contract — most of
which came from review rounds, and each of which names a specific way the obvious implementation is
wrong. The recurring error across four review rounds was always the same: patching the named
instance instead of covering its class — which is why the record states the rules as classes. Summarising any of them back out would lose the counter-example that makes it actionable.)*
+200 -35
View File
@@ -121,7 +121,7 @@ Convention — when a screen keeps stale results visible during a refetch:
current (compare against a ref that always holds the committed value — `SearchScreen` reuses
`lastQueryRef`) and **discard** otherwise. Checking only `activeRef` (mounted) is insufficient.
## 3b. Paged list endpoints clamp server-side — page to completeness ONLY for bounded lists, never a media-library picker
## 3b. Paged list endpoints clamp server-side — page to completeness ONLY for bounded lists; a media-library picker searches instead
Every paged `/api/v1` list endpoint (rerun-collections, multi-collections, library/browse, search,
trakt-lists, …) clamps `pageSize` to its own controller's `MaxPageSize` (100, as of #644) regardless
@@ -131,14 +131,14 @@ UI to notice the gap. This was issue #644 (following on from #634, which fixed t
`SchedulesScreen`'s rerun-collections picker load).
**Two classes of call site, treated differently** (decision record:
`docs/decisions/records/spa/list-completeness-vs-bounded-pickers.md`, `spa.list-completeness-vs-bounded-pickers`
— a #644 follow-up review found the original blanket "use `loadAllPages` for any picker" guidance
below was itself the defect for one class of caller):
`docs/decisions/records/spa/library-pickers-resolve-by-search.md`,
`spa.library-pickers-resolve-by-search`, superseding `spa.list-completeness-vs-bounded-pickers` —
the #644 follow-up got Class A right and Class B only half right):
- **Bounded-by-construction lists** (rerun collections, multi-collections, playlists — admin-created,
hundreds of rows at most): genuinely need the complete list, and completeness is cheap. Use the
shared `loadAllPages` helper (`web/src/api/paging.ts`, re-exported via `web/src/api/index.ts`)
instead of an inflated `pageSize`:
- **Class A — bounded-by-construction lists** (collections, multi-collections, smart collections,
playlists — admin-created, hundreds of rows at most): genuinely need the complete list, and
completeness is cheap. Use the shared `loadAllPages` helper (`web/src/api/paging.ts`, re-exported
via `web/src/api/index.ts`) instead of an inflated `pageSize`:
```ts
const { items, complete } = await loadAllPages(getMultiCollections); // pages against totalCount, cap defaults to 100
@@ -150,41 +150,206 @@ below was itself the defect for one class of caller):
a caller that needs the full list must not treat a resolved promise as proof the list is whole (a
partial result is otherwise silently indistinguishable from a complete one — the same defect class
as #644 itself, since `GetLibraryBrowseItemsHandler.HydrateMediaItems` can legitimately drop stale
Lucene hits and produce a short/empty page in normal operation). Pass an `AbortSignal` (4th arg)
from the caller's effect cleanup so a superseded load stops issuing further page requests instead
of hammering the server for a result nobody will see. **Do not raise the server-side cap to work
around this** — the `api.search-allitems-paging` precedent is that the client pages and the server
stays bounded; that's a backend decision, out of scope for a screen fix.
Lucene hits and produce a short/empty page in normal operation). Render `complete: false` as its own
copy ("List may be incomplete — retry to reload"), never through search-narrowing text — a
`loadPickerOptions` result that can come from either class carries a `hint: 'incomplete' | 'none'`
discriminator, not a boolean shared with an unrelated condition (#644 follow-up round-3 review F1).
Pass an `AbortSignal` (4th arg) from the caller's effect cleanup so a superseded load stops issuing
further page requests, and gate any `console.warn` on `!signal?.aborted` — a superseded or
user-aborted load returns `complete: false` too, and that's expected, not a defect. **Do not raise
the server-side cap to work around any of this** — the `api.search-allitems-paging` precedent is
that the client bounds itself and the server stays bounded.
- **Media-library pickers** (`getLibraryBrowseItems` backing a `<select>` for Episode / Song / Image /
Movie / MusicVideo / etc. — the largest tables in an install, tens of thousands of rows possible):
must **NOT** use `loadAllPages`. Paging to completeness here means on the order of 200 serial
requests for a 20k-row library — each more expensive than the last, since
`LuceneSearchIndex.Search` computes `hitsLimit = skip + limit` — to populate a native `<select>`
with thousands of `<option>` nodes. That is worse than the truncation bug it would "fix". Instead,
fetch **one bounded page** directly (`pageSize` at the cap) and make the truncation **visible**
rather than silent — e.g. a `ctv-field-help` hint next to the picker: `Showing the first 100 of
5000 — use search to narrow.` (wire the response's real `totalCount`). See
`RerunCollectionsScreen.tsx`/`PlaylistsScreen.tsx`/`FillerPresetsScreen.tsx`'s `loadPickerOptions`
for the pattern. A full typeahead/search-driven picker is a separate, larger feature — out of scope
for this fix.
- **Class B — media-library pickers** (Episode / Song / Image / Movie / MusicVideo / TelevisionShow /
TelevisionSeason / Artist / OtherVideo / RemoteStream — the largest tables in an install, tens of
thousands of rows possible): **resolve by search, do not window the type at all** (#651). Neither
`loadAllPages` (~200 serial requests for a 20k-row library, each more expensive than the last since
`LuceneSearchIndex.Search` computes `hitsLimit = skip + limit`) nor a single bounded page (an
arbitrary alphabetical prefix, unusable as a picker even once the truncation is made visible) is
acceptable. Render the shared `SearchPicker` (`web/src/schedules/pickers.tsx`) over
`searchLibraryPickerOptions` (`web/src/api/libraryBrowse.ts`):
**A Class B truncation and a Class A `complete: false` are different conditions — don't collapse
them into one boolean** (#644 follow-up round-3 review F1): a `loadPickerOptions` result that can
come from either a Class A (`loadAllPages`) or Class B (single bounded page) source should carry a
`hint: 'incomplete' | 'none' | 'truncated'` discriminator, not a `truncated: boolean` reused for
both. `'truncated'` (Class B, an expected cap) keeps the "Showing the first N of M — use search to
narrow" copy; `'incomplete'` (Class A, `loadAllPages`'s `complete: false`) renders different copy
("List may be incomplete — retry to reload") — rendering both through the search-narrowing text
produces a self-contradictory "Showing the first 47 of 47" when a Class A load doesn't converge.
Also gate any `console.warn` on a Class A `complete: false` with `!signal?.aborted` — a superseded
or user-aborted load returns `complete: false` too, and that's expected, not a defect.
```ts
const searchLibrary = useCallback( // memoize: SearchPicker lists `search` in its effect deps
(q: string) => searchLibraryPickerOptions('Episode', q),
[]
);
```
The helper owns both bounds: at most ONE `getLibraryBrowseItems` request per settled query, at most
`LIBRARY_PICKER_RESULTS` (25) rows, and no request at all below `LIBRARY_PICKER_MIN_QUERY` (2)
characters. Selecting a media-library type must issue **zero** requests. There is no truncation, so
there is no truncation hint — the old `Showing the first 100 of 5000 — use search to narrow.` copy
is gone from these pickers along with the window it described. Prove the bound with a
**request-count assertion against a large (20k-row) fixture**, not by inspection.
- **Compile typed text; never forward raw Lucene.** Send `titleContainsQuery(text)` →
`title:*<escaped>*`. The index's default field does not match bare title words (`Alpha` finds
nothing for "Show Alpha" — see `e2e-local.md`), so a raw forward looks broken in a *name* picker.
Reuse the helper; do not re-implement the escaping (same rule as the #440 Auto-Tune typeahead,
same shape `builder/rules/compile.ts` emits for `contains`). The escaped set includes `&` and
`|`, because Lucene's boolean operators are `&&`/`||` and a title like `Rock & Roll` otherwise
compiles to something Lucene parses as syntax. **Drive the escaping test from the exported
character set** (`LIBRARY_PICKER_LUCENE_SPECIALS`), one character per case — a test carrying its
own hand-copied "every special" sample cannot see what is missing from that sample.
- **The bound belongs to the helper, not the caller.** `searchLibraryPickerOptions` *clamps*
`pageSize` to `LIBRARY_PICKER_RESULTS`; a documented bound a caller can exceed by passing a
bigger number is not a bound.
- **Render the current selection from the owning record, not from the result set.** An item already
selected but outside the current results must still display — losing it on edit is data loss, not
a cosmetic defect. Rerun collections and playlist items carry `selectedName` on their own DTOs;
`FillerPresetFullResponseModel` stores only an id, so its edit path resolves the name with a
single by-id detail read (`getShow`/`getSeason`/`getArtist`) and degrades to `#id` on failure —
never to a cleared field.
- **A read model that derives an id and its name from the same eager-loaded navigation reports
*no selection at all* when that navigation isn't loaded** — a successful 200 indistinguishable
from "the user cleared it". (`RerunCollectionsController.ProjectToResponseModel` does exactly
this, and `MediaCollections/Mapper` maps RemoteStream through `_ => null`; tracked as **#671**.)
An earlier revision of this section required a client-side guard that preserved the id across
such a response. **That guard is gone and must not be rebuilt** — it only ever preserved a value
seeded from the list row, which is itself null in production for every row, and the reconciliation
it required is what the initialize-once rule below replaced. The correct handling is to show the
server's answer honestly: no selection, Save disabled, and the validation badge saying why.
- **An id NEVER travels without its namespace — in results, in options, in cached result sets.**
A media/collection id only means anything inside the type that produced it, so any structure
holding ids must hold the type too, and identity is compared as `(type, id)`. Three places this
bites, all the same bug:
1. A typeahead's cached results must be keyed on `(source, query)`, not the query text. Same
query, different source ⇒ the results are not *stale*, they are *wrong*: hide them and
re-query. Keying on text alone lets a re-query guard **suppress** the new source's request
and leave the old namespace's hit clickable under the new label.
2. List-backed `<select>` options must carry the type they were loaded for and be dropped the
moment the active type differs — otherwise the previous type's rows stay selectable during
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).
- **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.
- **Fail CLOSED on a missing concurrency token.** Writing the ETag in the same callback that
sets the draft is *not* the same as "a draft implies an ETag" — the response can simply omit
the header, and then the PUT carries no `If-Match` and silently force-writes. No token ⇒ no
editable draft (error + Retry/Back). Note this makes your test mocks load-bearing: a detail
mock that omits `ETag` was previously exercising the force-write path without saying so, so
give every single-record GET mock a real ETag and test the absent case explicitly.
- **Bound the load and always offer a way out.** A caller-supplied fetch with no abort signal can
hang forever; race it against a deadline, and give the loading view a Back control so a hung
request is never a dead end.
- **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.
`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
while the id — and therefore what gets saved — says otherwise. Keep the guard at the *writer*,
where it is reachable and testable; a second render-time id comparison is unreachable once
every writer sets the label and the id together, and an unreachable guard is an untested one.
- **Only Lucene-backed types.** `GetLibraryBrowseItemsHandler` applies `query` as a Lucene clause
for media items but as a plain SQL `LIKE` on `Name` for the collection-family types (Collection /
SmartCollection / MultiCollection / RerunCollection / Playlist). A compiled `title:*x*` sent at
those matches nothing literally. Keep the collection-family pickers on their Class A / bounded
single-page loads — `FillerPresetsScreen`'s `COLLECTION_TYPES` marks the search-driven entries
with `searchable: true` for exactly this reason.
**If a screen shows a bounded preview or has real paging UI** (a "load more" button, a page-size
selector, a fixed-size typeahead result list), a `pageSize` at or below the cap is correct as-is —
`loadAllPages` is only for "I need literally everything, and the list is small by construction"
call sites.
**Debounced typeaheads: arm on focus, and guard on mounted as well as on sequence.** A typeahead that
fetches on *mount* multiplies by the number of rows on screen (an N-rule tree fired N unrequested
facet lookups before #578); arm the effect on the input's `onFocus` instead. And pair the monotonic
`seqRef` stale-response guard with the shared `useIsMountedRef()` (`web/src/hooks.ts`) in every async
callback — `seqRef` drops an *older* response, but says nothing about whether the component still
exists.
**A custom picker replacing a native control owes you its keyboard behaviour.** A `<select>` is
fully keyboard-operable; swapping in a listbox-and-input is an accessibility *regression* unless it
implements the ARIA combobox pattern — `role="combobox"` + `aria-expanded`/`aria-controls`/
`aria-autocomplete` on the input, ArrowUp/ArrowDown to move a virtual cursor exposed via
`aria-activedescendant`, Enter to commit, Escape to dismiss, options as non-tab-stops
(`tabIndex={-1}`) marked with `aria-selected`. Note this changes what `getAllByRole('combobox')`
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 — 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.
- **Put a validity predicate at the BOUNDARY the class crosses, not at the site the bug was found.**
An entity-reference id (`selectedId`, `collectionId`, `mediaItemId`, …) is bound by the API as a
32-bit integer, so `1.5` or `2147483648` renders and commits fine and then fails on write. Such
ids enter editor state through *several* doors — search results, list-backed `<select>` options,
and the selection restored from a detail read — so a check added to whichever one surfaced the
defect leaves the others open (this is how #651 produced the same finding in two consecutive
rounds). Share one predicate (`isSelectionId` / `selectionIdOrNull` in `web/src/api/selectionId.ts`)
and apply it on every path — including the ones that don't look like pickers, such as a
`playlistGroupId` seeded from the wire into a create dialog. **Treat an unbindable id as ABSENT,
never coerce it** — rounding `1.5` to `1` would submit a *different* record — and **clear its
label with it**: a row still reading "Blade Runner" over a null id makes two contradictory
statements about the same item. Drop rather than render an option that cannot be selected safely.
"Surfaces as no selection" is only true if that screen's Save gate actually checks for one — on
`PlaylistsScreen` it did not, so this claim was false there for a full round after being written
here. **Verify an invariant on every screen it names before writing it down.** Prove it per
ingress by asserting zero writes are reachable *after attempting the write*: a write-count
assertion on a path that never attempts one is trivially true. And unit-test the predicate's
INCLUSIVE endpoints directly — once it is the single point of failure for every ingress, a `>`
for `>=` slip passes an entire screen suite.
- **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. Validate the **elements, not just the container**: `Array.isArray` accepts
`[null]`, which then throws on `option.id` during render, and an element with a wrong-typed `id`
commits an invalid value through `onSelect`. Treat any malformed payload as a failed attempt (so
it stays retryable), not as 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
**input change** (not when the next response arrives) and put the guard in the single `choose()`
sink rather than on each call site — gating Enter and leaving `onClick` open is the same defect in
another modality, and the next path added would be ungated too. Keep the stale list *visible*
(hiding it flickers on every keystroke) but genuinely inert: `aria-disabled` plus a dimmed style,
not merely a handler that silently no-ops on a normal-looking button.
- **Escape must not strand the user.** Closing the popup while focus stays in the input means
`onFocus` can never re-arm it, so typing does nothing and the user has to blur and refocus to
recover. Typing and ArrowDown must both reopen it — and reopening onto results that are already
current must **not** re-query: the duplicate response lands later and resets the cursor the user
has since moved, so Enter silently does nothing. Reopening also places the cursor (ARIA APG)
rather than swallowing the keypress.
**The web typecheck gate is `npm run typecheck`, never `npx tsc --noEmit`.** `web/tsconfig.json` is
solution-style (`"files": []` + `references`), so a bare `tsc --noEmit` resolves to zero input files
and exits 0 **without checking anything** — a green that means "I looked at nothing". CI runs
`npm run typecheck` (`tsc -b --pretty false`), which builds the referenced projects and includes the
test files. Verified by planting a deliberate type error: `--noEmit` stayed green, `-b` caught it.
**Testing an is-mounted guard: React 19 does not warn on a setState-after-unmount, and an unmounted
tree renders nothing either way** — so no DOM assertion can distinguish "the guard stopped it" from
"React discarded it". Prove the *mechanism* (a `useIsMountedRef` unit test, with a StrictMode
double-invoke for the re-arm) **and** the *integration* (mock the hook module and assert the
component actually read `current` — and saw `false` — when the late response landed). Verify each by
removing the mechanism and confirming the test fails.
## 4. API client modules
One file per domain in `web/src/api/`, e.g. `logs.ts`, `blocks.ts`, `playouts.ts`. Pattern (see
+1
View File
@@ -17,6 +17,7 @@ export * from './imageFolders';
export * from './languages';
export * from './libraries';
export * from './libraryBrowse';
export * from './selectionId';
export * from './logs';
export * from './maintenance';
export * from './mediaDetail';
+95 -1
View File
@@ -1,5 +1,11 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getLibraryBrowseItems } from './libraryBrowse';
import {
getLibraryBrowseItems,
searchLibraryPickerOptions,
titleContainsQuery,
LIBRARY_PICKER_LUCENE_SPECIALS,
LIBRARY_PICKER_RESULTS
} from './libraryBrowse';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
@@ -56,3 +62,91 @@ describe('getLibraryBrowseItems', () => {
expect(browseUrl(fetchMock).searchParams.has('parentId')).toBe(false);
});
});
describe('titleContainsQuery (#651 — compile typed text, never forward raw Lucene)', () => {
it('wraps the escaped text in boundary wildcards on the title field', () => {
expect(titleContainsQuery('Show Alpha')).toBe('title:*Show\\ Alpha*');
});
// The previous version of this test hand-copied a sample string and claimed to cover "every
// Lucene special" — it silently omitted `&` and `|`, and a completeness test that carries its own
// list of what to check cannot see what is missing from that list (#651 F2). Drive the assertion
// from the exported character set instead, one character at a time, so adding a character to the
// set without escaping it fails here.
it.each(LIBRARY_PICKER_LUCENE_SPECIALS.split(''))('escapes the Lucene special %j', (char) => {
expect(titleContainsQuery(`a${char}b`)).toBe(`title:*a\\${char}b*`);
});
it.each([' ', '\t', '\n'])('escapes whitespace %j so it cannot split the term', (char) => {
expect(titleContainsQuery(`a${char}b`)).toBe(`title:*a\\${char}b*`);
});
it('leaves every character that is NOT special untouched', () => {
const plain = 'abcXYZ019_,.\'@#$%';
for (const char of plain) {
expect(LIBRARY_PICKER_LUCENE_SPECIALS).not.toContain(char);
}
expect(titleContainsQuery(plain)).toBe(`title:*${plain}*`);
});
it('neutralises the && and || BOOLEAN operators, not just single characters (#651 F2)', () => {
// The regression: `Rock && Roll` used to compile with `&&` live, so Lucene parsed it as boolean
// syntax (or rejected the query) and an exactly-matching title returned nothing.
expect(titleContainsQuery('Rock && Roll')).toBe('title:*Rock\\ \\&\\&\\ Roll*');
expect(titleContainsQuery('A || B')).toBe('title:*A\\ \\|\\|\\ B*');
expect(titleContainsQuery('Rock & Roll')).toBe('title:*Rock\\ \\&\\ Roll*');
});
it('leaves a plain single word alone apart from the boundary stars', () => {
expect(titleContainsQuery('Alpha')).toBe('title:*Alpha*');
});
});
describe('searchLibraryPickerOptions (#651)', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('issues ONE bounded request with the compiled query and maps to {id, name}', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
jsonResponse({
page: [
{ id: 1, mediaItemId: 7, mediaType: 'Movie', title: 'Show Alpha' },
{ id: 2, mediaItemId: null, mediaType: 'Movie', title: null }
],
totalCount: 20000
})
);
const options = await searchLibraryPickerOptions('Movie', ' Show Alpha ');
expect(fetchMock).toHaveBeenCalledTimes(1);
const url = browseUrl(fetchMock);
expect(url.searchParams.get('query')).toBe('title:*Show\\ Alpha*');
expect(url.searchParams.get('mediaType')).toBe('Movie');
expect(url.searchParams.get('pageNum')).toBe('0');
expect(url.searchParams.get('pageSize')).toBe(String(LIBRARY_PICKER_RESULTS));
// `mediaItemId` wins when present; `id` is the fallback, and a missing title degrades to `#id`.
expect(options).toEqual([
{ id: 7, name: 'Show Alpha' },
{ id: 2, name: '#2' }
]);
});
it('#651 F4: CLAMPS an oversized pageSize rather than forwarding it', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 20000 }));
await searchLibraryPickerOptions('Episode', 'Alpha', 5000);
// The 25-row bound is a property of the helper, not of caller discipline.
expect(browseUrl(fetchMock).searchParams.get('pageSize')).toBe(String(LIBRARY_PICKER_RESULTS));
});
it('issues NO request for a query below the minimum length', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));
expect(await searchLibraryPickerOptions('Episode', 'a')).toEqual([]);
expect(await searchLibraryPickerOptions('Episode', ' ')).toEqual([]);
expect(fetchMock).not.toHaveBeenCalled();
});
});
+64
View File
@@ -47,6 +47,70 @@ export function getLibraryBrowseItems(params: GetLibraryBrowseItemsParams = {}):
return request<PagedLibraryBrowseItems>(`/api/v1/library/browse${queryString ? `?${queryString}` : ''}`);
}
// A library picker compiles typed text; it never forwards raw Lucene (#440, #651). The search
// index's default field does NOT match bare title words (`Alpha` finds nothing for "Show Alpha" —
// docs/e2e-local.md), so forwarding the user's literal text the way the explicit query box does
// would look broken in a *name* picker. Escape every Lucene special (and whitespace) so the
// boundary stars are the only live wildcards — the same shape `builder/rules/compile.ts` emits for
// its `contains` operator.
//
// The exhaustive set of characters Lucene's QueryParser treats as syntax. `&` and `|` are in it
// because the boolean operators are `&&`/`||`: escaping each character individually neutralises the
// pair. Leaving them live (as this helper's original AutoTuneScreen-local version did) meant a
// title like `Rock && Roll` compiled to a query Lucene parsed as boolean syntax — or rejected — so
// an exactly-matching title returned nothing (#651 F2). `LIBRARY_PICKER_LUCENE_SPECIALS` is
// exported so the test asserts against the character list itself rather than a hand-copied sample
// that cannot see its own omissions.
export const LIBRARY_PICKER_LUCENE_SPECIALS = '+-&|!(){}[]^"~*?:\\/';
const LUCENE_WILD_SPECIAL = /([\s+\-&|!(){}[\]^"~*?:\\/])/g;
export function titleContainsQuery(text: string): string {
return `title:*${text.replace(LUCENE_WILD_SPECIAL, '\\$1')}*`;
}
export interface LibraryPickerOption {
id: number;
name: string;
}
// How many matches a search-driven library picker offers, and the shortest query worth issuing.
// Both are hard bounds: such a picker NEVER loads more than one page of this size, whatever the
// media type's row count (#651 — decision key `spa.library-pickers-resolve-by-search`).
export const LIBRARY_PICKER_RESULTS = 25;
export const LIBRARY_PICKER_MIN_QUERY = 2;
// Resolve picker options for one media-library type by SEARCH rather than by loading a window of
// the whole type. Exactly one bounded request per (debounced) query; a too-short query issues none
// at all.
//
// `pageSize` is CLAMPED to `LIBRARY_PICKER_RESULTS`, not merely defaulted to it (#651 F4): the
// bound is documented as a property of this helper, so it must not be defeatable by a caller
// passing a larger number.
export function searchLibraryPickerOptions(
mediaType: LibraryBrowseMediaType,
text: string,
pageSize: number = LIBRARY_PICKER_RESULTS
): Promise<LibraryPickerOption[]> {
const trimmed = text.trim();
if (trimmed.length < LIBRARY_PICKER_MIN_QUERY) {
return Promise.resolve([]);
}
const boundedPageSize = Math.max(1, Math.min(Math.floor(pageSize), LIBRARY_PICKER_RESULTS));
return getLibraryBrowseItems({
mediaType,
pageNum: 0,
pageSize: boundedPageSize,
query: titleContainsQuery(trimmed)
}).then((result) =>
(result.page ?? []).map((item) => {
const id = item.mediaItemId ?? item.id;
return { id, name: item.title ?? `#${id}` };
})
);
}
export function messageFromLibraryBrowseError(error: unknown, fallback = 'Unable to load library items'): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
+3 -3
View File
@@ -16,9 +16,9 @@
* **This is only for lists that are bounded by construction** (admin-created collections/rerun
* entries/playlists — hundreds of rows at most). It must NOT be used as a picker/typeahead data
* source over a media library table (Episode/Song/Image/Movie/MusicVideo can run into the tens of
* thousands) — see `docs/decisions/records/spa/list-completeness-vs-bounded-pickers.md` (#644
* follow-up review). Those call sites fetch a single bounded page directly and surface the
* truncation instead.
* thousands) — see `docs/decisions/records/spa/library-pickers-resolve-by-search.md` (#651). Those
* call sites resolve by SEARCH instead: one bounded `searchLibraryPickerOptions` request per settled
* query, and no list load at all.
*/
export interface PagedResult<T> {
+5 -2
View File
@@ -37,8 +37,11 @@ export function getRerunCollection(id: number): Promise<RerunCollection> {
}
/** Load a single rerun collection together with its concurrency ETag (issue #253). */
export function getRerunCollectionWithMeta(id: number): Promise<ResponseWithMeta<RerunCollection>> {
return requestWithMeta<RerunCollection>(`/api/v1/rerun-collections/${id}`);
export function getRerunCollectionWithMeta(
id: number,
signal?: AbortSignal
): Promise<ResponseWithMeta<RerunCollection>> {
return requestWithMeta<RerunCollection>(`/api/v1/rerun-collections/${id}`, { signal });
}
export function createRerunCollection(body: CreateRerunCollectionRequest): Promise<RerunCollection> {
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { INT32_MAX, INT32_MIN, isSelectionId, selectionIdOrNull } from './selectionId';
// This predicate is the single point of failure for every id that reaches editor state across three
// screens (#651 round 8), and until now it was only exercised indirectly through screen tests. The
// endpoints matter most: swapping either `>=`/`<=` for a strict comparison is the classic mutation
// on exactly this code, and nothing else in the suite would notice.
describe('isSelectionId', () => {
it('accepts the INCLUSIVE int32 endpoints', () => {
expect(INT32_MAX).toBe(2_147_483_647);
expect(INT32_MIN).toBe(-2_147_483_648);
// A `>` for `>=` slip in either comparison fails here and nowhere else.
expect(isSelectionId(INT32_MAX)).toBe(true);
expect(isSelectionId(INT32_MIN)).toBe(true);
});
it('rejects values one step outside the range', () => {
expect(isSelectionId(INT32_MAX + 1)).toBe(false);
expect(isSelectionId(INT32_MIN - 1)).toBe(false);
});
it('accepts ordinary ids, including 0 and negatives', () => {
// Bindability, not existence — see the note in selectionId.ts. `id > 0` would break this.
expect(isSelectionId(1)).toBe(true);
expect(isSelectionId(0)).toBe(true);
expect(isSelectionId(-1)).toBe(true);
});
it('rejects non-integers and non-numbers', () => {
for (const value of [1.5, -0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) {
expect(isSelectionId(value)).toBe(false);
}
for (const value of ['1', null, undefined, {}, [], true, 1n]) {
expect(isSelectionId(value)).toBe(false);
}
});
});
describe('selectionIdOrNull', () => {
it('passes a bindable id through unchanged', () => {
expect(selectionIdOrNull(42)).toBe(42);
expect(selectionIdOrNull(INT32_MAX)).toBe(INT32_MAX);
expect(selectionIdOrNull(0)).toBe(0);
});
it('maps anything unbindable to null — never a coerced value', () => {
// Rounding 1.5 to 1 would submit a DIFFERENT record; absence is the only safe answer.
expect(selectionIdOrNull(1.5)).toBeNull();
expect(selectionIdOrNull(INT32_MAX + 1)).toBeNull();
expect(selectionIdOrNull('7')).toBeNull();
expect(selectionIdOrNull(null)).toBeNull();
expect(selectionIdOrNull(undefined)).toBeNull();
});
});
+30
View File
@@ -0,0 +1,30 @@
// A *selection id* is any id an editor stores and later submits as an entity reference —
// `selectedId` on a rerun collection, `collectionId`/`mediaItemId`/… on a playlist item or filler
// preset. The API binds every one of them as a 32-bit integer, so a value outside that domain is
// not merely odd: it renders and commits happily and then fails on write.
//
// This lives in ONE place on purpose. #651 round 7 added the check inside the search picker's
// option validator — the site where the defect was found — leaving list-backed options and the
// selection restored from a detail read unguarded, so the identical malformed value entered editor
// state through a different door (round 8). The predicate belongs at the BOUNDARY the class
// crosses: every path by which an id from the wire becomes editor state.
// DELIBERATELY not `id > 0`. Most id checks in this codebase (`routing.ts` and eight screens) use
// `Number.isInteger(id) && id > 0` because they are asking "could this id EXIST?". This predicate
// asks a different question — "can the API BIND this value as its `int` parameter?" — so `0` and
// negatives are accepted: they are perfectly bindable, and rejecting them here would silently
// convert a server-side 404/422 (a clear answer) into a client-side "no selection" (a confusing
// one). Do not "fix" the inconsistency; the two predicates are answering different questions.
export const INT32_MIN = -2_147_483_648;
export const INT32_MAX = 2_147_483_647;
export function isSelectionId(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value) && value >= INT32_MIN && value <= INT32_MAX;
}
// Normalize an id arriving from the wire into editor state. Anything the API cannot bind is treated
// as ABSENT rather than carried: the editor then shows "no selection" with Save disabled — visible
// and honest — instead of a value that looks selected and fails on submit. Never silently coerce
// (rounding 1.5 to 1 would submit a *different* record).
export function selectionIdOrNull(value: unknown): null | number {
return isSelectionId(value) ? value : null;
}
@@ -156,6 +156,15 @@ describe('RuleBuilder', () => {
const { container } = setupControlled({ match: 'all', children: [{ field: 'genre', operator: 'is', value: '' }] });
const input = screen.getByLabelText('Value') as HTMLInputElement;
// #578: nothing is fetched until the row is focused — mounting N text rules must not fire N
// requests nobody asked for.
await act(async () => {
await vi.advanceTimersByTimeAsync(400);
});
expect(getSearchFieldValues).not.toHaveBeenCalled();
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Ac' } });
expect(input.value).toBe('Ac');
+18 -4
View File
@@ -2,6 +2,7 @@ import { useEffect, useId, useRef, useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { Badge, Button, IconButton } from '../../components';
import { getSearchFieldValues } from '../../api/search';
import { useIsMountedRef } from '../../hooks';
import type { RuleField } from './fieldCatalog';
import {
isGroup,
@@ -48,29 +49,41 @@ function typeOf(fields: RuleField[], name: string): FieldType {
// Facet-value typeahead for text-field rules (#434): backed by a `<datalist>` so free-text is always
// accepted alongside the server-suggested values (the query preview count is the safety net for a
// value that doesn't match anything). Debounces the lookup ~200ms after each keystroke and drops any
// response that arrives after a newer request was issued or the field changed underneath it.
// response that arrives after a newer request was issued, the field changed underneath it, or the
// row unmounted.
//
// #578: the lookup is armed on FOCUS, not on mount. Fetching on mount meant a rule tree with N text
// rows issued N requests just to render — each one bounded server-side (`limit=50`) but none of them
// asked for, matching the `SearchPicker` precedent of not querying a picker nobody has touched. Once
// focused, an empty value still fetches: that top-50 list IS the datalist's browse affordance.
function TextValueInput({ field, value, onChange }: { field: string; value: string; onChange: (v: string) => void }) {
const [suggestions, setSuggestions] = useState<string[]>([]);
const [armed, setArmed] = useState(false);
const seqRef = useRef(0);
const mountedRef = useIsMountedRef();
const listId = useId();
useEffect(() => {
if (!armed) {
return;
}
const seq = ++seqRef.current;
const handle = window.setTimeout(() => {
getSearchFieldValues(field, value.trim())
.then((values) => {
if (seqRef.current === seq) {
if (mountedRef.current && seqRef.current === seq) {
setSuggestions(values);
}
})
.catch(() => {
if (seqRef.current === seq) {
if (mountedRef.current && seqRef.current === seq) {
setSuggestions([]);
}
});
}, 200);
return () => window.clearTimeout(handle);
}, [field, value]);
}, [armed, field, value, mountedRef]);
return (
<>
@@ -79,6 +92,7 @@ function TextValueInput({ field, value, onChange }: { field: string; value: stri
className="ctv-input"
value={value}
onChange={(e) => onChange(e.target.value)}
onFocus={() => setArmed(true)}
type="text"
list={listId}
autoComplete="off"
+53 -2
View File
@@ -20,12 +20,16 @@ const OPS: Record<FieldType, Operator[]> = {
date: ['before', 'after', 'between']
};
// Deterministic LCG so a failing case is reproducible.
// Deterministic LCG so a failing case is reproducible. Divide by 2^32, NOT by 0xffffffff (2^32-1):
// the latter returns exactly 1.0 for the maximum state, and `arr[Math.floor(1.0 * len)]` indexes one
// past the end. Deterministically unreachable on today's seeds, but a latent flake on any new one
// (#578). The generator's own contract is pinned by the "LCG generator" describe below, which
// drives `pick` at the boundary directly rather than waiting for a seed change to expose it.
function lcg(seed: number) {
let s = seed >>> 0;
return () => {
s = (1664525 * s + 1013904223) >>> 0;
return s / 0xffffffff;
return s / 0x100000000;
};
}
const pick = <T,>(rng: () => number, arr: T[]): T => arr[Math.floor(rng() * arr.length)];
@@ -98,3 +102,50 @@ describe('round-trip: parse(compile(tree)) === tree', () => {
expect(deepest).toBe(MAX_GROUP_DEPTH);
});
});
// #578 / #651 review round 2: drive the REAL `lcg` into its maximum state instead of recomputing
// the divisor in the test. The generator is `s -> (1664525*s + 1013904223) mod 2^32`, which is a
// bijection (the multiplier is odd), so the seed whose FIRST step lands on 0xffffffff can be solved
// exactly: seed = (0xffffffff - 1013904223) * 1664525^-1 mod 2^32 = 653637408. On the old
// `/ 0xffffffff` divisor that first value is exactly 1.0 and `pick` indexes one past the end; a
// test that recomputes the formula would pass either way and prove nothing.
const MAX_STATE_SEED = 653637408;
describe('LCG generator', () => {
it('never returns 1.0 — not even on the step that reaches the maximum 32-bit state', () => {
const value = lcg(MAX_STATE_SEED)();
// Guards the seed itself: if the recurrence ever changes, this stops silently testing a
// mid-range state that would pass under either divisor.
expect(value).toBeGreaterThan(0.9999999);
expect(value).toBeLessThan(1);
});
it('pick() stays in bounds on the maximum-state step', () => {
const arr = ['a', 'b', 'c'];
// `arr[Math.floor(1.0 * 3)]` is `arr[3]` — undefined — on the old divisor.
expect(pick(lcg(MAX_STATE_SEED), arr)).toBe('c');
expect(pick(lcg(MAX_STATE_SEED), ['only'])).toBe('only');
});
it('pick() stays in range across the whole output of a real generator', () => {
const arr = ['a', 'b', 'c', 'd'];
for (let seed = 0; seed < 50; seed += 1) {
const rng = lcg(seed);
for (let i = 0; i < 500; i += 1) {
expect(arr).toContain(pick(rng, arr));
}
}
});
it('stays within [0, 1) for every reachable state', () => {
// Every 32-bit state IS reachable from any seed (full-period LCG), so walking a long stream
// from the maximum-state seed covers the boundary rather than hoping to stumble on it.
const rng = lcg(MAX_STATE_SEED);
for (let i = 0; i < 20000; i += 1) {
const value = rng();
expect(value).toBeGreaterThanOrEqual(0);
expect(value).toBeLessThan(1);
}
});
});
+58
View File
@@ -0,0 +1,58 @@
import { cleanup, render } from '@testing-library/react';
import { StrictMode, useEffect } from 'react';
import { afterEach, describe, expect, it } from 'vitest';
import { useIsMountedRef } from './hooks';
afterEach(cleanup);
describe('useIsMountedRef (#578)', () => {
it('reads true while mounted and false after unmount', () => {
let captured: { readonly current: boolean } | null = null;
function Probe() {
captured = useIsMountedRef();
return null;
}
const { unmount } = render(<Probe />);
// The guard every async callback reads: true for as long as the component is on screen...
expect(captured).not.toBeNull();
expect((captured as unknown as { current: boolean }).current).toBe(true);
unmount();
// ...and false afterwards, so a fetch resolving late can be dropped instead of calling setState
// on a component that no longer exists. Without the effect's cleanup this stays true, which is
// exactly the defect the hook exists to prevent.
expect((captured as unknown as { current: boolean }).current).toBe(false);
});
it('is re-armed by a StrictMode double-invoke (mount → cleanup → mount)', () => {
let captured: { readonly current: boolean } | null = null;
let effectRuns = 0;
function Probe() {
captured = useIsMountedRef();
useEffect(() => {
effectRuns += 1;
});
return null;
}
render(
<StrictMode>
<Probe />
</StrictMode>
);
// StrictMode in a dev build mounts, tears down, and remounts every effect. If that did not
// happen, this test would not be exercising re-arming at all, so assert it explicitly rather
// than assume it.
expect(effectRuns).toBeGreaterThan(1);
// The first cleanup set the flag false; the remount must set it back to true. Remove
// `ref.current = true` from the effect body and this reads false.
expect((captured as unknown as { current: boolean }).current).toBe(true);
});
});
+21
View File
@@ -0,0 +1,21 @@
import { useEffect, useRef } from 'react';
// Shared is-mounted guard for async callbacks (#578). A monotonic `seqRef` drops a STALE response
// (an older request resolving after a newer one) but says nothing about whether the component is
// still there: a fetch that resolves after unmount still matches the latest seq and still calls
// setState. Read `ref.current` in every async callback alongside the seq check.
//
// The flag is (re-)armed inside the effect rather than only at `useRef` init so a StrictMode
// double-invoke — mount, unmount, remount on the same instance — leaves it true.
export function useIsMountedRef(): { readonly current: boolean } {
const ref = useRef(true);
useEffect(() => {
ref.current = true;
return () => {
ref.current = false;
};
}, []);
return ref;
}
@@ -435,6 +435,11 @@ function SourcePicker({
selectedId={selectedId ?? null}
selectedName={selectedName ?? null}
search={search}
// The picker is NOT remounted when the item's collection type changes, so results must be
// bound to the type that produced them — otherwise a Collection hit stays clickable under a
// SmartCollection label and stores a Collection id in the SmartCollection field (#651 round 4
// HIGH-1). `type` names both the search function and the id namespace, so it IS the source.
source={type}
onSelect={(id, name) => setSelection(id, name)}
onClear={() => setSelection(null, null)}
/>
+568
View File
@@ -0,0 +1,568 @@
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';
// Every value `SearchPicker` read out of the shared is-mounted guard, in order. This is what makes
// the unmount test non-vacuous (#651 F7): an unmounted tree renders nothing either way, so
// asserting on the DOM cannot distinguish "the guard stopped the update" from "React discarded it".
// Recording the reads proves the component actually CONSULTS the guard — and specifically that it
// consults it once the late response lands, seeing `false`.
const mountedReads: boolean[] = [];
vi.mock('../hooks', async (importOriginal) => {
const actual = await importOriginal<typeof import('../hooks')>();
const { useRef } = await import('react');
return {
...actual,
useIsMountedRef: () => {
const inner = actual.useIsMountedRef();
// Memoized so the returned object identity is stable across renders — it is an effect
// dependency in SearchPicker, and a fresh object each render would restart the debounce.
const proxyRef = useRef<{ readonly current: boolean } | null>(null);
proxyRef.current ??= {
get current() {
mountedReads.push(inner.current);
return inner.current;
}
};
return proxyRef.current;
}
};
});
beforeEach(() => {
mountedReads.length = 0;
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
function renderPicker(overrides: Partial<Parameters<typeof SearchPicker>[0]> = {}) {
const props = {
label: 'Movie',
onClear: vi.fn(),
onSelect: vi.fn(),
search: vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue([]),
selectedId: null,
selectedName: null,
source: 'Movie',
...overrides
};
return { props, ...render(<SearchPicker {...props} />) };
}
describe('SearchPicker', () => {
it('#578: a search resolving AFTER unmount consults the is-mounted guard and is dropped', async () => {
// Holder object, not a bare `let`: TS control-flow analysis cannot see that the Promise
// executor already ran, so a plain variable narrows to `null` and `release?.()` fails to
// typecheck as `never`. (The repo already uses this shape in RerunCollectionsScreen.test.)
const release: { resolve: ((items: SearchPickerOption[]) => void) | null } = { resolve: null };
const search = vi.fn(
() =>
new Promise<SearchPickerOption[]>((resolve) => {
release.resolve = resolve;
})
);
const { unmount } = renderPicker({ search });
fireEvent.focus(screen.getByLabelText('Movie search'));
fireEvent.change(screen.getByLabelText('Movie search'), { target: { value: 'Alpha' } });
await waitFor(() => expect(search).toHaveBeenCalledWith('Alpha'));
// While mounted, no guard read can be `false` (the debounce may not have read it yet at all).
expect(mountedReads).not.toContain(false);
unmount();
release.resolve?.([{ id: 1, name: 'Alpha Movie' }]);
// Let the resolved promise's .then run against an unmounted tree.
await new Promise((resolve) => setTimeout(resolve, 0));
// The response handler ran and asked "am I still mounted?", getting `false` — so it skipped the
// setState. Drop the `mountedRef.current &&` from the .then and this read never happens.
expect(mountedReads).toContain(false);
expect(screen.queryByText('Alpha Movie')).not.toBeInTheDocument();
});
it('issues no request below minQueryLength, then exactly one for the settled query', async () => {
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue([]);
renderPicker({ minQueryLength: 2, search });
const input = screen.getByLabelText('Movie search');
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'A' } });
await new Promise((resolve) => setTimeout(resolve, 400));
expect(search).not.toHaveBeenCalled();
fireEvent.change(input, { target: { value: 'Alpha' } });
await waitFor(() => expect(search).toHaveBeenCalledTimes(1));
expect(search).toHaveBeenCalledWith('Alpha');
});
it('renders the current selection from the props, independent of any result set', async () => {
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue([]);
renderPicker({ search, selectedId: 9999, selectedName: 'Stored Show' });
// Nothing was searched, and 9999 is in no result set — it must still display by name.
expect(screen.getByText('Stored Show')).toBeInTheDocument();
expect(search).not.toHaveBeenCalled();
});
it('falls back to #id when the selection has no name', () => {
renderPicker({ selectedId: 42, selectedName: null });
expect(screen.getByText('#42')).toBeInTheDocument();
});
it('reports no matches once a query has settled empty', async () => {
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue([]);
renderPicker({ search });
const input = screen.getByLabelText('Movie search');
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Nope' } });
expect(await screen.findByText(/No matches/)).toBeInTheDocument();
});
// ---- #651 F6: keyboard operability ----
// A native <select> was fully keyboard-operable; replacing it with a custom widget must not
// regress that. Standard ARIA combobox: focus stays on the input, Arrow keys move a virtual
// cursor exposed via aria-activedescendant, Enter commits, Escape dismisses.
describe('keyboard navigation', () => {
const OPTIONS: SearchPickerOption[] = [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
{ id: 3, name: 'Gamma' }
];
async function openWithResults(onSelect = vi.fn()) {
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue(OPTIONS);
renderPicker({ onSelect, search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'a' } });
await screen.findByRole('listbox', { name: 'Movie results' });
return { input, onSelect };
}
const activeOptionName = (input: HTMLInputElement) => {
const id = input.getAttribute('aria-activedescendant');
return id === null ? null : document.getElementById(id)?.textContent ?? null;
};
it('exposes the combobox contract on the input', async () => {
const { input } = await openWithResults();
expect(input).toHaveAttribute('role', 'combobox');
expect(input).toHaveAttribute('aria-expanded', 'true');
expect(input).toHaveAttribute('aria-autocomplete', 'list');
expect(input.getAttribute('aria-controls')).toBe(
screen.getByRole('listbox', { name: 'Movie results' }).getAttribute('id')
);
// Nothing highlighted until the user navigates.
expect(input).not.toHaveAttribute('aria-activedescendant');
});
it('ArrowDown/ArrowUp move the active option and wrap at both ends', async () => {
const { input } = await openWithResults();
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(activeOptionName(input)).toBe('Alpha');
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(activeOptionName(input)).toBe('Beta');
fireEvent.keyDown(input, { key: 'ArrowUp' });
expect(activeOptionName(input)).toBe('Alpha');
// Wrap backwards past the first option...
fireEvent.keyDown(input, { key: 'ArrowUp' });
expect(activeOptionName(input)).toBe('Gamma');
// ...and forwards past the last.
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(activeOptionName(input)).toBe('Alpha');
});
it('ArrowUp from nothing highlighted starts at the LAST option', async () => {
const { input } = await openWithResults();
fireEvent.keyDown(input, { key: 'ArrowUp' });
expect(activeOptionName(input)).toBe('Gamma');
});
it('Home/End jump to the first and last option', async () => {
const { input } = await openWithResults();
fireEvent.keyDown(input, { key: 'End' });
expect(activeOptionName(input)).toBe('Gamma');
fireEvent.keyDown(input, { key: 'Home' });
expect(activeOptionName(input)).toBe('Alpha');
});
it('marks the active option with aria-selected', async () => {
const { input } = await openWithResults();
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'ArrowDown' });
const options = screen.getAllByRole('option');
expect(options.map((option) => option.getAttribute('aria-selected'))).toEqual(['false', 'true', 'false']);
});
it('Enter commits the highlighted option and closes the list', async () => {
const { input, onSelect } = await openWithResults();
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onSelect).toHaveBeenCalledWith(2, 'Beta');
await waitFor(() => expect(screen.queryByRole('listbox', { name: 'Movie results' })).not.toBeInTheDocument());
});
it('Enter with nothing highlighted selects nothing (a form submit is not hijacked)', async () => {
const { input, onSelect } = await openWithResults();
fireEvent.keyDown(input, { key: 'Enter' });
expect(onSelect).not.toHaveBeenCalled();
expect(screen.getByRole('listbox', { name: 'Movie results' })).toBeInTheDocument();
});
it('Escape dismisses the list but keeps the typed text', async () => {
const { input, onSelect } = await openWithResults();
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('listbox', { name: 'Movie results' })).not.toBeInTheDocument());
expect(input.value).toBe('a');
expect(onSelect).not.toHaveBeenCalled();
});
it('drops the highlight when a NEW result set arrives', async () => {
const search = vi
.fn<(query: string) => Promise<SearchPickerOption[]>>()
.mockResolvedValueOnce(OPTIONS)
.mockResolvedValue([{ id: 9, name: 'Zeta' }]);
renderPicker({ search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'a' } });
await screen.findByRole('listbox', { name: 'Movie results' });
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(activeOptionName(input)).toBe('Alpha');
// Index 0 of the OLD list is not index 0 of the new one — the cursor must reset, not carry
// over onto whatever now happens to sit at that position.
fireEvent.change(input, { target: { value: 'ab' } });
await waitFor(() => expect(screen.getByRole('option', { name: 'Zeta' })).toBeInTheDocument());
expect(input).not.toHaveAttribute('aria-activedescendant');
});
it('BLOCKER 2: Enter cannot commit a result from the PREVIOUS query', async () => {
const onSelect = vi.fn();
const release: { resolve: ((items: SearchPickerOption[]) => void) | null } = { resolve: null };
const search = vi
.fn<(query: string) => Promise<SearchPickerOption[]>>()
.mockResolvedValueOnce(OPTIONS)
.mockImplementation(() => new Promise((resolve) => { release.resolve = resolve; }));
renderPicker({ onSelect, search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Al' } });
await screen.findByRole('listbox', { name: 'Movie results' });
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(activeOptionName(input)).toBe('Alpha');
// Retype: the results still describe "Al" until the next response lands.
fireEvent.change(input, { target: { value: 'Be' } });
// The highlight is dropped IMMEDIATELY, not when the response happens to arrive.
expect(input).not.toHaveAttribute('aria-activedescendant');
// Neither re-highlighting nor Enter may commit a stale option while the box reads "Be".
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onSelect).not.toHaveBeenCalled();
// Once the response for "Be" lands, the keyboard is live again.
await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
release.resolve?.([{ id: 7, name: 'Beta Two' }]);
await waitFor(() => expect(screen.getByRole('option', { name: 'Beta Two' })).toBeInTheDocument());
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'Enter' });
expect(onSelect).toHaveBeenCalledWith(7, 'Beta Two');
});
it('BLOCKER 3: the picker recovers from Escape by typing, without a blur', async () => {
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue(OPTIONS);
renderPicker({ search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'a' } });
await screen.findByRole('listbox', { name: 'Movie results' });
fireEvent.keyDown(input, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('listbox', { name: 'Movie results' })).not.toBeInTheDocument());
// Focus never left the input, so onFocus cannot re-arm it. Typing must.
fireEvent.change(input, { target: { value: 'al' } });
expect(await screen.findByRole('listbox', { name: 'Movie results' })).toBeInTheDocument();
});
it('BLOCKER 3 / round 3: reopening onto CURRENT results re-queries nothing and stays navigable', async () => {
const onSelect = vi.fn();
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue(OPTIONS);
renderPicker({ onSelect, search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'a' } });
await screen.findByRole('listbox', { name: 'Movie results' });
expect(search).toHaveBeenCalledTimes(1);
fireEvent.keyDown(input, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('listbox', { name: 'Movie results' })).not.toBeInTheDocument());
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(await screen.findByRole('listbox', { name: 'Movie results' })).toBeInTheDocument();
// The cached results are already current, so reopening must NOT re-search: a duplicate
// response would land later and reset the highlight the user has since moved, leaving Enter
// silently doing nothing. Give the debounce more than its 250ms to prove no request follows.
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(activeOptionName(input)).toBe('Beta');
await new Promise((resolve) => setTimeout(resolve, 400));
expect(search).toHaveBeenCalledTimes(1);
// The highlight survived, and Enter still commits it.
expect(activeOptionName(input)).toBe('Beta');
fireEvent.keyDown(input, { key: 'Enter' });
expect(onSelect).toHaveBeenCalledWith(2, 'Beta');
});
it('round 3 HIGH: a stale result cannot be committed by POINTER either', async () => {
const onSelect = vi.fn();
const release: { resolve: ((items: SearchPickerOption[]) => void) | null } = { resolve: null };
const search = vi
.fn<(query: string) => Promise<SearchPickerOption[]>>()
.mockResolvedValueOnce(OPTIONS)
.mockImplementation(() => new Promise((resolve) => { release.resolve = resolve; }));
renderPicker({ onSelect, search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Al' } });
await screen.findByRole('listbox', { name: 'Movie results' });
// Retype; Alpha is still on screen because hiding the list would flicker every keystroke.
fireEvent.change(input, { target: { value: 'Be' } });
const staleOption = screen.getByRole('option', { name: 'Alpha' });
expect(staleOption).toBeInTheDocument();
// Visible, but marked inert rather than merely looking normal.
expect(staleOption).toHaveAttribute('aria-disabled', 'true');
// Clicking it must not commit a result from the superseded query.
fireEvent.click(staleOption);
expect(onSelect).not.toHaveBeenCalled();
// Once "Be" resolves, pointer commits work again.
await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
release.resolve?.([{ id: 7, name: 'Beta Two' }]);
const fresh = await screen.findByRole('option', { name: 'Beta Two' });
expect(fresh).toHaveAttribute('aria-disabled', 'false');
fireEvent.click(fresh);
expect(onSelect).toHaveBeenCalledWith(7, 'Beta Two');
});
});
// ---- #651 review round 4: results carry their SOURCE, not just their query text ----
describe('result provenance', () => {
const COLLECTION_HITS: SearchPickerOption[] = [{ id: 5, name: 'News Collection' }];
const SMART_HITS: SearchPickerOption[] = [{ id: 8, name: 'News Smart' }];
const OPTIONS: SearchPickerOption[] = [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' }
];
it('HIGH-1: changing the SOURCE re-queries and retires the old namespace\'s results', async () => {
const onSelect = vi.fn();
const search = vi
.fn<(query: string) => Promise<SearchPickerOption[]>>()
.mockResolvedValueOnce(COLLECTION_HITS)
.mockResolvedValue(SMART_HITS);
const { rerender } = renderPicker({ onSelect, search, source: 'Collection' });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'news' } });
expect(await screen.findByRole('option', { name: 'News Collection' })).toBeInTheDocument();
expect(search).toHaveBeenCalledTimes(1);
// Same component instance (no `key`), same query text — only the id namespace changed. The
// round-3 re-query guard keyed on query alone, which SUPPRESSED this request and left the
// Collection hit clickable under the new source.
rerender(
<SearchPicker
label="Movie"
onClear={vi.fn()}
onSelect={onSelect}
search={search}
selectedId={null}
selectedName={null}
source="SmartCollection"
/>
);
// The other namespace's result is gone immediately — not merely dimmed. It is not stale, it
// is wrong: a Collection id offered under a SmartCollection label.
expect(screen.queryByRole('option', { name: 'News Collection' })).not.toBeInTheDocument();
await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
expect(await screen.findByRole('option', { name: 'News Smart' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('option', { name: 'News Smart' }));
expect(onSelect).toHaveBeenCalledWith(8, 'News Smart');
expect(onSelect).not.toHaveBeenCalledWith(5, 'News Collection');
});
it('MEDIUM-5: a FAILED search is retried on reopen, not cached as "no matches" forever', async () => {
const search = vi
.fn<(query: string) => Promise<SearchPickerOption[]>>()
.mockRejectedValueOnce(new Error('boom'))
.mockResolvedValue(OPTIONS);
renderPicker({ search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Alien' } });
// The transient failure is reported AS a failure, not as an authoritative empty result...
expect(await screen.findByRole('alert')).toHaveTextContent(/Search failed/i);
expect(search).toHaveBeenCalledTimes(1);
// ...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.queryByRole('alert')).not.toBeInTheDocument());
fireEvent.keyDown(input, { key: 'ArrowDown' });
await waitFor(() => expect(search).toHaveBeenCalledTimes(2));
expect(await screen.findByRole('option', { name: 'Alpha' })).toBeInTheDocument();
});
it('a SUCCESSFUL empty result is still cached — the retry is for failures only', async () => {
const search = vi.fn<(query: string) => Promise<SearchPickerOption[]>>().mockResolvedValue([]);
renderPicker({ search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Nope' } });
expect(await screen.findByText(/No matches/)).toBeInTheDocument();
fireEvent.keyDown(input, { key: 'Escape' });
fireEvent.keyDown(input, { key: 'ArrowDown' });
await new Promise((resolve) => setTimeout(resolve, 400));
// "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 reports the malformed body as a FAILED attempt.
expect(await screen.findByRole('alert')).toHaveTextContent(/Search failed/i);
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.each([
{ label: 'a null element', payload: [null] },
{ label: 'an element with no id', payload: [{ name: 'Nameless' }] },
{ label: 'an element with a string id', payload: [{ id: '7', name: 'Stringly' }] },
{ label: 'an element with no name', payload: [{ id: 7 }] },
{ label: 'an element with a non-string name', payload: [{ id: 7, name: 42 }] },
{ label: 'a NaN id', payload: [{ id: Number.NaN, name: 'Not a number' }] },
{ label: 'one bad element among good ones', payload: [{ id: 1, name: 'Alpha' }, null] },
// The API binds `selectedId` as a 32-bit integer, so these render and commit happily and
// then fail server-side — another adjacent shape (#651 round 7).
{ label: 'a fractional id', payload: [{ id: 1.5, name: 'Fractional' }] },
{ label: 'an id above int32', payload: [{ id: 2_147_483_648, name: 'Too big' }] },
{ label: 'an id below int32', payload: [{ id: -2_147_483_649, name: 'Too small' }] },
{ label: 'an Infinity id', payload: [{ id: Number.POSITIVE_INFINITY, name: 'Infinite' }] }
])('MEDIUM-3 (round 6): rejects $label rather than rendering or committing it', async ({ payload }) => {
// `Array.isArray` checks the CONTAINER, not the CONTENTS: `[null]` passes it, reaches
// `setResults`, and throws on `option.id` during render. A wrong-typed id would commit an
// invalid value through `onSelect`.
const onSelect = vi.fn();
const search = vi
.fn<(query: string) => Promise<SearchPickerOption[]>>()
.mockResolvedValueOnce(payload as unknown as SearchPickerOption[])
.mockResolvedValue(OPTIONS);
renderPicker({ onSelect, search });
const input = screen.getByLabelText('Movie search') as HTMLInputElement;
fireEvent.focus(input);
fireEvent.change(input, { target: { value: 'Alpha' } });
// Renders (does not throw) and offers nothing — a malformed list is not a partial answer.
// And it must READ as a failure: "No matches" would tell the user the library genuinely has
// nothing, with no hint that anything went wrong or that reopening retries (#651 round 7).
expect(await screen.findByRole('alert')).toHaveTextContent(/Search failed/i);
expect(screen.queryByText(/No matches/)).not.toBeInTheDocument();
expect(screen.queryAllByRole('option')).toHaveLength(0);
expect(onSelect).not.toHaveBeenCalled();
// ...and it is a FAILED attempt, so it stays retryable rather than being cached.
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 AS a
// failure — not as "no matches", which would misreport a timeout as an empty library.
await act(async () => {
await vi.advanceTimersByTimeAsync(11_000);
});
expect(screen.getByRole('alert')).toHaveTextContent(/Search failed/i);
} finally {
vi.useRealTimers();
}
});
});
});
+273 -27
View File
@@ -1,37 +1,106 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useId, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { Check, Search, X } from 'lucide-react';
import { Spinner } from '../components';
import type { SchedulingPickerOption } from '../api';
import { useIsMountedRef } from '../hooks';
import { isSelectionId } from '../api';
// The shape every search-backed picker resolves to. Deliberately structural rather than the
// generated `SchedulingPickerOption` DTO: the scheduling pickers pass that DTO straight through,
// while the media-library pickers (#651) map `LibraryBrowseItem` onto the same two fields.
export interface SearchPickerOption {
id: number;
name: string;
}
// A debounced async autocomplete for the search-backed source pickers (shows/seasons/artists and
// collection/multi/smart searches). Renders the current selection (label) with a clear button, an
// input that queries `search(query)` after a 250ms debounce, and a results list.
// collection/multi/smart searches, plus the media-library pickers from #651). Renders the current
// selection (label) with a clear button, an input that queries `search(query)` after a 250ms
// debounce, and a results list.
export interface SearchPickerProps {
label: string;
selectedId: null | number;
selectedName: null | string;
search: (query: string) => Promise<SchedulingPickerOption[]>;
search: (query: string) => Promise<SearchPickerOption[]>;
// Identifies WHAT `search` queries — the id NAMESPACE its results live in. Results are cached and
// validated against `(source, query)`, never the query alone: an id is only meaningful inside its
// own namespace, so a source change invalidates a result set exactly as a query change does.
// Required, deliberately: a defaulted source would silently opt every caller out of the check.
source: string;
onSelect: (id: number, name: string) => void;
onClear: () => void;
ariaDescribedBy?: string;
disabled?: boolean;
// Hide the visible field label (the surrounding row already renders one) without dropping the
// aria labels that name the input and the results list.
labelHidden?: boolean;
// Shortest query worth issuing a request for. Below it the picker fetches nothing at all.
minQueryLength?: number;
placeholder?: string;
}
// Upper bound on how long a picker will wait for a caller-supplied search promise.
const SEARCH_TIMEOUT_MS = 10_000;
// `Array.isArray` checks the CONTAINER, not the CONTENTS: `[null]` passes it, reaches `setResults`,
// and throws on `option.id` during render; an element with a missing or wrong-typed `id`/`name`
// yields a broken option or commits an invalid value (#651 round 6). Nothing between the network
// and `onSelect` re-checks these, so validate every element before storing it.
// The id must be what the API can actually BIND — see `isSelectionId`. This is one of several
// ingresses for the same class; the predicate is shared so they cannot drift apart (#651 round 8).
function isSearchPickerOption(value: unknown): value is SearchPickerOption {
if (typeof value !== 'object' || value === null) {
return false;
}
const candidate = value as { id?: unknown; name?: unknown };
return isSelectionId(candidate.id) && typeof candidate.name === 'string';
}
export function SearchPicker({
label,
selectedId,
selectedName,
search,
source,
onSelect,
onClear,
ariaDescribedBy,
disabled = false,
labelHidden = false,
minQueryLength = 1,
placeholder = 'Search…'
}: SearchPickerProps) {
const [query, setQuery] = useState('');
const [open, setOpen] = useState(false);
const [results, setResults] = useState<SchedulingPickerOption[]>([]);
const [results, setResults] = useState<SearchPickerOption[]>([]);
// The PROVENANCE of `results`: which source and query produced them, and whether that attempt
// succeeded. All three matter.
// - source: results from another namespace are not stale, they are wrong (#651 round 4 HIGH-1);
// - query: distinguishes an empty result set from "hasn't searched yet", so the no-matches
// copy doesn't flash between a keystroke and its debounce;
// - ok: a FAILED search must not be cached as a successful empty result, or the re-query
// guard below turns a transient 500 into a permanent "No matches" that reopening,
// blurring and refocusing can never retry (#651 round 4 MEDIUM-5).
const [resultsFor, setResultsFor] = useState<null | { ok: boolean; query: string; source: string }>(null);
const [loading, setLoading] = useState(false);
// -1 = no option highlighted (the ARIA combobox "virtual cursor" is parked).
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).
@@ -40,37 +109,178 @@ export function SearchPicker({
return;
}
const trimmed = query.trim();
// 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).
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(() => {
if (trimmed.length === 0) {
if (seqRef.current === seq) {
if (tooShort) {
if (mountedRef.current && seqRef.current === seq) {
setResults([]);
setResultsFor(null);
setActiveIndex(-1);
setLoading(false);
}
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 (seqRef.current === seq) {
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 anything that is not a well-formed
// list of options as a FAILED attempt — not an authoritative empty answer — so it is
// retryable rather than cached (#651 round 5 MEDIUM-3, round 6).
if (!Array.isArray(items) || !items.every(isSearchPickerOption)) {
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
// of the new one.
setActiveIndex(-1);
setLoading(false);
}
})
.catch(() => {
if (seqRef.current === seq) {
if (mountedRef.current && seqRef.current === seq) {
setResults([]);
// ok: false — a failure, not an authoritative empty result. Marked so the guard above
// retries instead of caching the outage forever.
setResultsFor({ ok: false, query: trimmed, source });
setActiveIndex(-1);
setLoading(false);
}
});
}, trimmed.length === 0 ? 0 : 250);
}, tooShort ? 0 : 250);
return () => window.clearTimeout(handle);
}, [query, open, search]);
}, [query, open, search, source, minQueryLength, mountedRef, resultsFor]);
const trimmedQuery = query.trim();
// Results from a DIFFERENT source aren't stale, they're wrong — a Collection id offered under a
// SmartCollection label — so they are not shown at all. Results from the same source but an older
// query stay VISIBLE while the next response loads (hiding them flickers on every keystroke) but
// become inert: typing "Al", highlighting Alpha, retyping "Be" and pressing Enter must not select
// Alpha (#651 round 2 BLOCKER 2, round 4 HIGH-1).
const sameSource = resultsFor !== null && resultsFor.source === source;
const resultsCurrent = sameSource && resultsFor.query === trimmedQuery;
// A failed attempt (network error, timeout, or a malformed payload rejected wholesale) must NOT
// read as an authoritative "no matches": the user would have no signal that anything went wrong,
// nor that reopening retries (#651 round 7).
const searchFailed = open && !loading && resultsCurrent && !resultsFor.ok;
const noMatches = open && !loading && results.length === 0 && resultsCurrent && resultsFor.ok;
const listboxOpen = open && sameSource && results.length > 0;
const keyboardArmed = listboxOpen && resultsCurrent;
// Keyboard navigation (#651 F6). Replacing a native <select> with a custom widget removed
// keyboard operability, which is a regression, not a pre-existing gap: without this the only way
// to reach a result is to Tab through to its button. This is the standard ARIA combobox pattern —
// focus stays on the input and `aria-activedescendant` points at the visually-highlighted option.
const choose = (option: SearchPickerOption) => {
// ONE gate for every commit path — keyboard, pointer, and anything added later. Gating the two
// call sites individually is what let a stale option stay clickable after Enter was fixed
// (#651 review round 3, HIGH): the class is "committing a result from a superseded query", not
// "pressing Enter".
if (!resultsCurrent) {
return;
}
onSelect(option.id, option.name);
setQuery('');
setResults([]);
setResultsFor(null);
setActiveIndex(-1);
setOpen(false);
};
const onKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Escape') {
// Dismiss the list but keep what was typed — Escape closes the popup, it doesn't undo input.
setActiveIndex(-1);
setOpen(false);
return;
}
// Escape (or a selection) closes the popup while focus stays in the input, so ArrowDown has to
// be able to REOPEN it. Without this the picker is stuck until the user blurs and refocuses,
// because `onFocus` never fires again (#651 review round 2, BLOCKER 3).
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.
if (resultsCurrent && results.length > 0) {
setActiveIndex(event.key === 'ArrowDown' ? 0 : results.length - 1);
}
return;
}
if (!keyboardArmed) {
return;
}
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
const delta = event.key === 'ArrowDown' ? 1 : -1;
setActiveIndex((current) => {
// From "nothing active", ArrowDown lands on the first option and ArrowUp on the last.
const next = current < 0 ? (delta === 1 ? 0 : results.length - 1) : current + delta;
return (next + results.length) % results.length;
});
return;
}
if (event.key === 'Home' || event.key === 'End') {
event.preventDefault();
setActiveIndex(event.key === 'Home' ? 0 : results.length - 1);
return;
}
if (event.key === 'Enter' && activeIndex >= 0 && activeIndex < results.length) {
// Only swallow Enter when it actually commits a highlighted option, so a form's default
// submit behaviour is untouched otherwise.
event.preventDefault();
choose(results[activeIndex]);
}
};
const optionId = (index: number) => `${listboxId}-option-${index}`;
return (
<div className="ctv-field ctv-field-full">
<span className="ctv-field-label">{label}</span>
{!labelHidden && <span className="ctv-field-label">{label}</span>}
{selectedId != null && !open ? (
<div className="ctv-picker-selected">
<span>{selectedName ?? `#${selectedId}`}</span>
@@ -95,27 +305,63 @@ export function SearchPicker({
value={query}
disabled={disabled}
placeholder={placeholder}
role="combobox"
aria-label={`${label} search`}
onChange={(event) => setQuery(event.target.value)}
onFocus={() => setOpen(true)}
aria-describedby={ariaDescribedBy}
aria-expanded={listboxOpen}
aria-controls={listboxId}
aria-autocomplete="list"
aria-activedescendant={
keyboardArmed && activeIndex >= 0 && activeIndex < results.length ? optionId(activeIndex) : undefined
}
onChange={(event) => {
setQuery(event.target.value);
// The highlight described the OLD result set; drop it now rather than when the next
// response happens to arrive (BLOCKER 2). Typing also reopens a popup Escape closed,
// so the picker recovers without a blur (BLOCKER 3).
setActiveIndex(-1);
setOpen(true);
rearm();
}}
onFocus={() => {
setOpen(true);
rearm();
}}
onKeyDown={onKeyDown}
/>
{loading && <span className="ctv-field-trailing"><Spinner size={13} tone="muted" /></span>}
</span>
{open && results.length > 0 && (
<ul className="ctv-picker-results" role="listbox" aria-label={`${label} results`}>
{results.map((option) => (
{noMatches && <div className="ctv-picker-empty">No matches — try a different title.</div>}
{searchFailed && (
<div className="ctv-picker-empty ctv-picker-error" role="alert">
Search failed — press Escape and reopen, or edit your search, to try again.
</div>
)}
{listboxOpen && (
<ul
className={`ctv-picker-results${resultsCurrent ? '' : ' ctv-picker-results-stale'}`}
role="listbox"
id={listboxId}
aria-label={`${label} results`}
>
{results.map((option, index) => (
<li key={option.id}>
<button
type="button"
role="option"
aria-selected={option.id === selectedId}
className="ctv-picker-result"
onClick={() => {
onSelect(option.id, option.name);
setQuery('');
setResults([]);
setOpen(false);
}}
id={optionId(index)}
// The option is never a tab stop: the ARIA combobox pattern keeps focus on the
// input and moves a virtual cursor via aria-activedescendant. It stays a
// <button> so pointer users get the same click target as before.
tabIndex={-1}
// Superseded results are inert until their replacement lands. `aria-disabled`
// (not `disabled`) keeps them announced and hoverable while `choose` refuses
// them, so the list doesn't flicker away on every keystroke.
aria-disabled={!resultsCurrent}
aria-selected={keyboardArmed && index === activeIndex}
className={`ctv-picker-result${keyboardArmed && index === activeIndex ? ' ctv-picker-result-active' : ''}`}
onMouseEnter={() => setActiveIndex(index)}
onClick={() => choose(option)}
>
{option.name}
</button>
+1 -11
View File
@@ -54,6 +54,7 @@ import {
messageFromAutoTuneError,
messageFromChannelTemplateError,
messageFromSearchError,
titleContainsQuery,
uploadArtwork,
previewAutoTune,
type AutoTuneAxis,
@@ -1465,17 +1466,6 @@ function DetailPanel({
const ADD_SOURCE_RESULTS = 8;
const ADD_SOURCE_MIN_QUERY = 2;
// The picker takes plain typed text, not Lucene: the index's default field does NOT match bare title
// words (`Alpha` finds nothing for "Show Alpha" — docs/e2e-local.md), so a raw forward like the search
// box does would look broken here. Compile a substring title match instead, escaping every Lucene
// special (and whitespace) so the boundary stars are the only live wildcards — the same shape the rule
// builder's `contains` operator emits (builder/rules/compile.ts).
const LUCENE_WILD_SPECIAL = /([\s+\-!(){}[\]^"~*?:\\/])/g;
function titleContainsQuery(text: string): string {
return `title:*${text.replace(LUCENE_WILD_SPECIAL, '\\$1')}*`;
}
type AddSearchState =
| { status: 'idle' }
| { status: 'error'; query: string; message: string }
+140 -10
View File
@@ -1,4 +1,4 @@
import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { FillerPresetsScreen } from './FillerPresetsScreen';
@@ -87,6 +87,11 @@ function mockApi(options: MockOptions = {}) {
return Promise.resolve(jsonResponse(browsePage(browseCount, browseTotal)));
}
// The by-id detail read the search-driven picker uses to name an already-stored media item.
if (pathname === '/api/v1/shows/9999' && method === 'GET') {
return Promise.resolve(jsonResponse({ id: 9999, libraryId: 1, mediaSourceKind: 'Local', title: 'Stored Show' }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
@@ -141,19 +146,144 @@ describe('FillerPresetsScreen', () => {
expect(screen.queryByText(/Showing the first/)).not.toBeInTheDocument();
});
it('F2: injects the out-of-list current selection so an id outside the loaded page still renders as selected', async () => {
it('#651: an edit-loaded media-item selection is NAMED by one by-id read, with no library load', async () => {
window.history.pushState({}, '', '/app/filler-presets/1');
mockApi();
const fetchMock = mockApi();
render(<FillerPresetsScreen />);
await waitFor(() => expect(screen.getByDisplayValue('Bumper')).toBeInTheDocument());
// Select order: Kind, Mode, Pad to nearest minute, Collection type, then the activeConfig
// ("Movie") picker last — it shows the out-of-list #9999 option, selected, never falling back
// to "(none)" even though 9999 isn't in the 3-item loaded page.
const comboboxes = await screen.findAllByRole('combobox');
const pickerSelect = comboboxes[comboboxes.length - 1];
expect((pickerSelect as HTMLSelectElement).value).toBe('9999');
expect(within(pickerSelect).getByText('#9999')).toBeInTheDocument();
// The stored media item (id 9999) is displayed by NAME, resolved through a single by-id detail
// read — never by scanning a browse window it may well not be in.
expect(await screen.findByText('Stored Show')).toBeInTheDocument();
expect(screen.getByLabelText('Clear Television Show')).toBeInTheDocument();
const calls = (pathname: string) =>
fetchMock.mock.calls.filter(([u]) => new URL(u.toString(), 'http://localhost').pathname === pathname);
expect(calls('/api/v1/shows/9999')).toHaveLength(1);
// A searchable (media-library) type list-loads NOTHING.
expect(calls('/api/v1/library/browse')).toHaveLength(0);
});
it('#651: the media-library picker compiles typed text and stays bounded against a huge library', async () => {
window.history.pushState({}, '', '/app/filler-presets/add');
const TOTAL = 20000;
const fetchMock = mockApi({
onRequest: (url) => {
if (!url.startsWith('/api/v1/library/browse')) {
return null;
}
const parsed = new URL(url, 'http://localhost');
const pageSize = Number(parsed.searchParams.get('pageSize') ?? '100');
return jsonResponse({
page: Array.from({ length: pageSize }, (_, i) => ({
id: i + 1,
mediaItemId: i + 1,
mediaType: 'TelevisionShow' as const,
title: `Show ${i + 1}`
})),
totalCount: TOTAL
});
}
});
render(<FillerPresetsScreen />);
// Switch the collection type to the media-library-backed Television Show.
const typeSelect = (await screen.findAllByRole('combobox')).find((el) =>
within(el).queryByText('Television Show')
) as HTMLSelectElement;
fireEvent.change(typeSelect, { target: { value: 'TelevisionShow' } });
// Scoped to the searchable type: the default 'Collection' draft does one bounded (non-Lucene,
// LIKE-filtered) load of its own, which #651 deliberately leaves alone.
const browseCalls = () =>
fetchMock.mock.calls.filter(([u]) => {
const parsed = new URL(u.toString(), 'http://localhost');
return parsed.pathname === '/api/v1/library/browse' && parsed.searchParams.get('mediaType') === 'TelevisionShow';
});
const searchInput = await screen.findByLabelText('Television Show search');
expect(browseCalls()).toHaveLength(0);
fireEvent.focus(searchInput);
fireEvent.change(searchInput, { target: { value: 'Show Alpha' } });
await waitFor(() => expect(browseCalls().length).toBe(1));
// Give any (nonexistent) paging loop room to fire.
await new Promise((resolve) => setTimeout(resolve, 400));
expect(browseCalls()).toHaveLength(1);
const url = new URL(browseCalls()[0][0].toString(), 'http://localhost');
expect(url.searchParams.get('query')).toBe('title:*Show\\ Alpha*');
expect(url.searchParams.get('mediaType')).toBe('TelevisionShow');
expect(Number(url.searchParams.get('pageSize'))).toBe(25);
const results = screen.getByRole('listbox', { name: 'Television Show results' });
expect(within(results).getAllByRole('option')).toHaveLength(25);
});
it('#651 F3: a SLOW edit-load name resolution never relabels a newer selection', async () => {
window.history.pushState({}, '', '/app/filler-presets/1');
// Hold the by-id read for the STORED show (9999) open, so it resolves only after the user has
// already picked a different show. One bespoke mock — layering a second spy over mockApi's
// would re-enter itself.
// Holder object rather than a bare `let` — TS narrows a closure-assigned variable to `null`.
const releaseStoredName: { resolve: ((response: Response) => void) | null } = { resolve: null };
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const pathname = new URL(input.toString(), 'http://localhost').pathname;
const method = (init?.method ?? 'GET').toUpperCase();
if (pathname === '/api/v1/shows/9999') {
return new Promise<Response>((resolve) => {
releaseStoredName.resolve = resolve;
});
}
if (pathname === '/api/v1/filler-presets' && method === 'GET') {
return Promise.resolve(jsonResponse(presetList));
}
if (pathname === '/api/v1/filler-presets/1' && method === 'GET') {
return Promise.resolve(jsonResponse(editPreset));
}
if (pathname === '/api/v1/library/browse' && method === 'GET') {
return Promise.resolve(
jsonResponse({
page: [{ id: 123, mediaItemId: 123, mediaType: 'TelevisionShow', title: 'New Show' }],
totalCount: 1
})
);
}
return Promise.resolve(new Response(null, { status: 204 }));
});
render(<FillerPresetsScreen />);
await waitFor(() => expect(screen.getByDisplayValue('Bumper')).toBeInTheDocument());
// No name yet — the read is still in flight, so the picker shows the id it definitely has.
expect(await screen.findByText('#9999')).toBeInTheDocument();
// The user picks a different show while the stored name is still resolving.
fireEvent.click(screen.getByRole('button', { name: 'Change' }));
const searchInput = await screen.findByLabelText('Television Show search');
fireEvent.focus(searchInput);
fireEvent.change(searchInput, { target: { value: 'New Show' } });
fireEvent.click(await screen.findByRole('option', { name: 'New Show' }));
const chip = () => screen.getByLabelText('Clear Television Show').closest('.ctv-picker-selected');
await waitFor(() => expect(chip()?.textContent).toContain('New Show'));
// NOW the stale read lands. It must not relabel the newer selection: the draft holds 123, so a
// title resolved for 9999 is simply not about the current selection.
releaseStoredName.resolve?.(
new Response(JSON.stringify({ id: 9999, libraryId: 1, mediaSourceKind: 'Local', title: 'Stored Show' }), {
headers: { 'Content-Type': 'application/json' },
status: 200
})
);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(chip()?.textContent).toContain('New Show');
expect(chip()?.textContent).not.toContain('Stored Show');
});
});
+155 -35
View File
@@ -6,25 +6,32 @@ import { Badge, Button, Card, Checkbox, ConfirmDialog, IconButton, Input, Select
import {
createFillerPreset,
deleteFillerPreset,
getArtist,
getFillerPreset,
getFillerPresets,
getLibraryBrowseItems,
getSeason,
getShow,
messageFromFillerPresetError,
searchLibraryPickerOptions,
selectionIdOrNull,
updateFillerPreset,
isSelectionId,
LIBRARY_PICKER_MIN_QUERY,
type CreateFillerPresetRequest,
type FillerPreset,
type LibraryBrowseItem,
type LibraryBrowseMediaType
} from '../api';
import { SearchPicker } from '../schedules/pickers';
const BASE_PATH = '/app/filler-presets';
// Class B picker (#644 follow-up): the filler-preset collection-type picker browses the largest
// media-library tables (Episode, Song, Image, Movie, MusicVideo, ...), which can run into the tens
// of thousands of rows. Paging to completeness would mean ~200 serial requests — each more
// expensive than the last (LuceneSearchIndex.Search computes hitsLimit = skip + limit) — to
// populate a native <select> with thousands of <option> nodes. Load ONE bounded page instead and
// surface the truncation (see docs/decisions/records/spa/list-completeness-vs-bounded-pickers.md).
// The bounded page size for the picker types that are NOT media-library tables (Collection /
// MultiCollection / SmartCollection / Playlist — admin-created, bounded by construction, and
// filtered server-side by a plain SQL LIKE rather than Lucene). The media-library types
// (TelevisionShow / TelevisionSeason / Artist) do not list-load at all: they resolve by search
// (#651, decision key `spa.library-pickers-resolve-by-search`).
const LIBRARY_BROWSE_PAGE_CAP = 100;
type Draft = CreateFillerPresetRequest;
@@ -50,23 +57,49 @@ const MODE_OPTIONS = [
const PAD_OPTIONS = [5, 10, 15, 30, 60].map((minutes) => ({ label: String(minutes), value: String(minutes) }));
// CollectionType -> the library-browse media type + which request id field it fills.
// `searchable` marks the media-library types: those resolve by search (#651) and are never
// list-loaded. The rest are admin-created lists filtered server-side by a plain SQL LIKE — which
// a compiled Lucene query would NOT match — so they keep the bounded single-page load.
const COLLECTION_TYPES: Array<{
browse: LibraryBrowseMediaType;
field: 'collectionId' | 'mediaItemId' | 'multiCollectionId' | 'playlistId' | 'smartCollectionId';
itemId: (item: LibraryBrowseItem) => null | number | undefined;
label: string;
playlistOnly?: boolean;
searchable?: boolean;
value: CollectionType;
}> = [
{ browse: 'Collection', field: 'collectionId', itemId: (item) => item.collectionId, label: 'Collection', value: 'Collection' },
{ browse: 'TelevisionShow', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Television Show', value: 'TelevisionShow' },
{ browse: 'TelevisionSeason', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Television Season', value: 'TelevisionSeason' },
{ browse: 'Artist', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Artist', value: 'Artist' },
{ browse: 'TelevisionShow', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Television Show', searchable: true, value: 'TelevisionShow' },
{ browse: 'TelevisionSeason', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Television Season', searchable: true, value: 'TelevisionSeason' },
{ browse: 'Artist', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Artist', searchable: true, value: 'Artist' },
{ browse: 'MultiCollection', field: 'multiCollectionId', itemId: (item) => item.multiCollectionId, label: 'Multi Collection', value: 'MultiCollection' },
{ browse: 'SmartCollection', field: 'smartCollectionId', itemId: (item) => item.smartCollectionId, label: 'Smart Collection', value: 'SmartCollection' },
{ browse: 'Playlist', field: 'playlistId', itemId: (item) => item.playlistId, label: 'Playlist', playlistOnly: true, value: 'Playlist' }
];
// Unlike a rerun collection or a playlist item, a filler preset stores ONLY the media item's id —
// there is no name on `FillerPresetFullResponseModel`. So the edit path resolves the stored id's
// title through the by-id detail endpoint: exactly ONE bounded request, and the picker can show the
// real selection instead of a bare `#id` whether or not it would have been in any browse window.
function resolveMediaItemName(type: CollectionType, id: number): Promise<null | string> {
switch (type) {
case 'TelevisionShow':
return getShow(id).then((show) => show.title || null);
case 'TelevisionSeason':
// Mirror the browse label for a season ("Show - Season 3"): the detail DTO splits it into the
// show title and the season name.
return getSeason(id).then((season) => {
const parts = [season.title, season.name].filter((part) => part != null && part.trim().length > 0);
return parts.length > 0 ? parts.join(' - ') : null;
});
case 'Artist':
return getArtist(id).then((artist) => artist.name || null);
default:
return Promise.resolve(null);
}
}
const COLLECTION_ID_FIELDS = ['collectionId', 'mediaItemId', 'multiCollectionId', 'smartCollectionId', 'playlistId'] as const;
/* ---------- TimeSpan (constant "c" format) helpers ---------- */
@@ -184,19 +217,22 @@ function defaultDraft(): Draft {
function draftFromPreset(preset: FillerPreset & Draft): Draft {
return {
allowWatermarks: preset.allowWatermarks,
collectionId: preset.collectionId,
// Every entity-reference id is normalized on the way in: a value the API cannot bind is treated
// as ABSENT so it surfaces as "no selection" (Save disabled) rather than as an apparently-valid
// selection that fails on submit (#651 round 8).
collectionId: selectionIdOrNull(preset.collectionId),
collectionType: preset.collectionType,
count: preset.count,
duration: preset.duration,
expression: preset.expression,
fillerKind: preset.fillerKind,
fillerMode: preset.fillerMode,
mediaItemId: preset.mediaItemId,
multiCollectionId: preset.multiCollectionId,
mediaItemId: selectionIdOrNull(preset.mediaItemId),
multiCollectionId: selectionIdOrNull(preset.multiCollectionId),
name: preset.name,
padToNearestMinute: preset.padToNearestMinute,
playlistId: preset.playlistId,
smartCollectionId: preset.smartCollectionId,
playlistId: selectionIdOrNull(preset.playlistId),
smartCollectionId: selectionIdOrNull(preset.smartCollectionId),
useChaptersAsMediaItems: preset.useChaptersAsMediaItems
};
}
@@ -454,6 +490,16 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
const [pickerError, setPickerError] = useState<null | string>(null);
const [pickerTruncated, setPickerTruncated] = useState(false);
const [pickerTotalCount, setPickerTotalCount] = useState<null | number>(null);
// The searchable (media-library) picker's current selection LABEL. The draft holds only the id,
// so this is what keeps an already-selected item displayable while it sits outside — or ahead
// of — any search result set.
//
// It is stored WITH the id it names (#651 F3) rather than as a bare string. A slow edit-load name
// resolution for the stored id can otherwise land after the user has already picked something
// else, labelling the new id with the old item's title while `mediaItemId` — and therefore what
// gets saved — says otherwise. The id travels with the name so the resolution callback can tell
// whether it is still describing the current selection.
const [selectedLabel, setSelectedLabel] = useState<null | { id: number; name: string }>(null);
const isEdit = mode.kind === 'edit';
@@ -469,8 +515,34 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
getFillerPreset(loadEditId)
.then((preset) => {
if (active) {
setDraft(draftFromPreset(preset as FillerPreset & Draft));
if (!active) {
return;
}
const loaded = draftFromPreset(preset as FillerPreset & Draft);
setDraft(loaded);
// Resolve the stored media item's name for the search-driven picker (one bounded request).
// A failure here is cosmetic — the picker falls back to `#id` and the id is still saved —
// so it must never surface as a load error.
const config = COLLECTION_TYPES.find((entry) => entry.value === loaded.collectionType);
const requestedId = loaded.mediaItemId;
if (config?.searchable && requestedId != null) {
resolveMediaItemName(loaded.collectionType, requestedId)
.then((name) => {
if (active && name) {
// Tagged with the id it was resolved FOR — see `selectedLabel` above — and refused
// outright if the label we already hold names a DIFFERENT id, i.e. the user picked
// something else while this was in flight. The render-time id check alone would
// stop the mislabelling but still discard the newer, correct label.
setSelectedLabel((current) =>
current !== null && current.id !== requestedId ? current : { id: requestedId, name }
);
}
})
.catch(() => {
/* cosmetic only — keep the `#id` fallback */
});
}
})
.catch((error: unknown) => {
@@ -487,17 +559,17 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
const collectionType = draft?.collectionType;
// Load the browse items for the active collection type so the picker can show names. All
// resets happen in the async callbacks (never synchronously in the effect body).
// resets happen in the async callbacks (never synchronously in the effect body). Searchable
// (media-library) types load NOTHING here — they resolve by search (#651).
useEffect(() => {
const config = COLLECTION_TYPES.find((entry) => entry.value === collectionType);
if (!config) {
if (!config || config.searchable) {
return;
}
let active = true;
// Class B (#644 follow-up) — load ONE bounded page rather than paging to completeness; see the
// module-level comment on LIBRARY_BROWSE_PAGE_CAP.
// Bounded single page — see the module-level comment on LIBRARY_BROWSE_PAGE_CAP.
getLibraryBrowseItems({ mediaType: config.browse, pageNum: 0, pageSize: LIBRARY_BROWSE_PAGE_CAP })
.then((result) => {
if (active) {
@@ -523,6 +595,16 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
};
}, [collectionType]);
const searchConfig = COLLECTION_TYPES.find((entry) => entry.value === collectionType && entry.searchable);
const searchBrowseType = searchConfig?.browse;
// Stable across renders: `SearchPicker`'s debounce effect lists `search` in its deps, so a fresh
// closure every render would restart the debounce on each keystroke's re-render.
const searchLibrary = useCallback(
(query: string) => (searchBrowseType ? searchLibraryPickerOptions(searchBrowseType, query) : Promise.resolve([])),
[searchBrowseType]
);
if (loadError) {
return (
<div className="ctv-settings-error" role="alert">
@@ -549,6 +631,8 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
const setKind = (fillerKind: FillerKind) => setDraft((current) => (current ? applyKind(current, fillerKind) : current));
const setCollectionType = (type: CollectionType) => {
// The id refs are cleared below, so the search picker's label must go with them.
setSelectedLabel(null);
setDraft((current) => {
if (!current) {
return current;
@@ -581,10 +665,9 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
const pickerSelectedInList =
pickerSelectedId != null &&
pickerItems.some((item) => activeConfig?.itemId(item) === pickerSelectedId);
// Out-of-list injection (round-3 review F2): the Class B picker loads only ONE bounded page
// (LIBRARY_BROWSE_PAGE_CAP), so a preset whose stored id sits outside that page would otherwise
// render as "(none)" while the draft still holds the id — mirrors RerunCollectionsScreen's and
// PlaylistsScreen's `selectedInList` prepend.
// Out-of-list injection (round-3 review F2): the non-searchable picker loads only ONE bounded
// page (LIBRARY_BROWSE_PAGE_CAP), so a preset whose stored id sits outside that page would
// otherwise render as "(none)" while the draft still holds the id.
const pickerOptions = [
{ label: '(none)', value: '' },
...(pickerSelectedId != null && !pickerSelectedInList
@@ -592,15 +675,18 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
: []),
...pickerItems.flatMap((item) => {
const id = activeConfig?.itemId(item);
return id == null ? [] : [{ label: item.title ?? `#${id}`, value: String(id) }];
// Drop, don't offer: an option whose id the API cannot bind is unselectable by construction.
return isSelectionId(id) ? [{ label: item.title ?? `#${id}`, value: String(id) }] : [];
})
];
const pickerHelp = pickerError
? pickerError
: pickerTruncated
? `Showing the first ${pickerItems.length} of ${pickerTotalCount} — use search to narrow.`
: undefined;
: searchBrowseType
? `Type at least ${LIBRARY_PICKER_MIN_QUERY} characters to search the library.`
: pickerTruncated
? `Showing the first ${pickerItems.length} of ${pickerTotalCount} — use search to narrow.`
: undefined;
const collectionTypeOptions = COLLECTION_TYPES.filter(
(entry) => !entry.playlistOnly || (draft.fillerKind !== 'Fallback' && draft.fillerKind !== 'Tail')
@@ -739,13 +825,47 @@ function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: '
</Row>
{activeConfig && (
<Row control={360} help={pickerHelp} label={activeConfig.label}>
<Select
onChange={(event) =>
set({ [activeConfig.field]: event.target.value === '' ? null : Number(event.target.value) })
}
options={pickerOptions}
value={pickerValue}
/>
{searchBrowseType ? (
// #651: the media library is resolved by search, never list-loaded. The current
// selection renders from `selectedLabel` (resolved once by id on edit-load), not from
// the result set, so an already-selected item survives every search — and even a
// failed name resolution degrades to `#id` rather than losing the id.
<SearchPicker
key={activeConfig.value}
label={activeConfig.label}
labelHidden
minQueryLength={LIBRARY_PICKER_MIN_QUERY}
onClear={() => {
setSelectedLabel(null);
set({ [activeConfig.field]: null });
}}
onSelect={(id, name) => {
setSelectedLabel({ id, name });
set({ [activeConfig.field]: id });
}}
placeholder={`Search ${activeConfig.label.toLowerCase()}…`}
search={searchLibrary}
source={activeConfig.value}
selectedId={pickerSelectedId}
// No id comparison here: there is no reachable path TODAY on which `selectedLabel`
// names an id other than the draft's while a selection is shown. (Not "every writer
// sets both" — the initial load writes the id alone, and a stale resolver can
// repopulate the label after a clear because `current === null`; in both cases the
// draft id is null, so the picker renders its search input and the label is unused.)
// Adding a render-time check back would be defensive, not a fix, and an unreachable
// guard is an untested one — so if a path ever appears, add the guard WITH the test
// that reaches it. #651 review round 3.
selectedName={selectedLabel?.name ?? null}
/>
) : (
<Select
onChange={(event) =>
set({ [activeConfig.field]: event.target.value === '' ? null : Number(event.target.value) })
}
options={pickerOptions}
value={pickerValue}
/>
)}
</Row>
)}
<Row
+189 -2
View File
@@ -253,10 +253,197 @@ describe('PlaylistsScreen', () => {
// Select the Movie item row to open the detail form.
fireEvent.click(await screen.findByText('Cool Movie'));
// Detail-form selects: [0] Collection Type, [1] Selection, [2] Playback Order.
// Movie is a media-library type, so its Selection picker is a search typeahead (#651), not a
// combobox: [0] Collection Type, [1] Playback Order.
const selects = await screen.findAllByRole('combobox');
const orderSelect = selects[2];
const orderSelect = selects[1];
expect(orderSelect).toBeDisabled();
expect(within(orderSelect).getAllByRole('option').map((o) => o.textContent)).toEqual(['None']);
});
it('media-library picker: keeps the stored selection and resolves by compiled search (#651)', async () => {
const fetchMock = mockApi({
// A 20,000-row library: an unbounded loader would show up both as extra requests and as a
// huge option list.
onRequest: (url) => {
if (!url.startsWith('/api/v1/library/browse')) {
return null;
}
const pageSize = Number(new URL(url, 'http://localhost').searchParams.get('pageSize') ?? '100');
return jsonResponse({
page: [
{ id: 42, mediaItemId: 42, mediaType: 'Movie', title: 'Another Movie' },
...Array.from({ length: pageSize - 1 }, (_, i) => ({
id: i + 100,
mediaItemId: i + 100,
mediaType: 'Movie' as const,
title: `Filler Movie ${i + 1}`
}))
],
totalCount: 20000
});
}
});
render(<PlaylistsScreen />);
fireEvent.click(await screen.findByText('Bumps'));
fireEvent.click(await screen.findByText('Cool Movie'));
const browseCalls = () =>
fetchMock.mock.calls.filter(
([u]) => new URL(u.toString(), 'http://localhost').pathname === '/api/v1/library/browse'
);
// The already-selected media item (id 7, outside any result set) renders from the draft item's
// own `selectedName` — with NO library load at all.
expect(await screen.findByLabelText('Clear Movie')).toBeInTheDocument();
expect(browseCalls()).toHaveLength(0);
// "Change" reveals the typeahead; typed text is compiled, never forwarded raw.
fireEvent.click(screen.getByRole('button', { name: 'Change' }));
const searchInput = await screen.findByLabelText('Movie search');
fireEvent.focus(searchInput);
fireEvent.change(searchInput, { target: { value: 'Show Alpha' } });
await waitFor(() => expect(browseCalls().length).toBe(1));
const url = new URL(browseCalls()[0][0].toString(), 'http://localhost');
expect(url.searchParams.get('query')).toBe('title:*Show\\ Alpha*');
expect(url.searchParams.get('mediaType')).toBe('Movie');
// Picking a result replaces the selection (and its label) without any further load.
// One bounded page of options — not 20,000 nodes, and not a paging loop.
const results = screen.getByRole('listbox', { name: 'Movie results' });
expect(within(results).getAllByRole('option')).toHaveLength(25);
fireEvent.click(await screen.findByRole('option', { name: 'Another Movie' }));
const chip = (await screen.findByLabelText('Clear Movie')).closest('.ctv-picker-selected');
expect(chip?.textContent).toContain('Another Movie');
expect(browseCalls()).toHaveLength(1);
});
it('HIGH-2: options from the PREVIOUS item type are not selectable while the new type loads', async () => {
// Same defect as RerunCollectionsScreen, second screen: switching a playlist item's type on a
// slow connection must not leave the old namespace's options on offer under the new label
// (#651 round 4 HIGH-2).
const smartRelease: { resolve: (() => void) | null } = { resolve: null };
const fetchMock = mockApi();
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/smart-collections' && (init?.method ?? 'GET').toUpperCase() === 'GET') {
return new Promise<Response>((resolve) => {
smartRelease.resolve = () => resolve(jsonResponse([{ id: 77, name: 'Smart Pick' }]));
});
}
return inner(input, init);
});
render(<PlaylistsScreen />);
fireEvent.click(await screen.findByText('Bumps'));
fireEvent.click(await screen.findByText('Favorites'));
// The Collection item's picker is offering its own options.
const picker = () => screen.getAllByRole('combobox')[1];
await within(picker()).findByRole('option', { name: 'Favorites' });
const typeSelect = screen.getAllByRole('combobox')[0];
fireEvent.change(typeSelect, { target: { value: 'SmartCollection' } });
// Mid-load: no options from the previous namespace.
expect(within(picker()).queryByRole('option', { name: 'Favorites' })).not.toBeInTheDocument();
smartRelease.resolve?.();
expect(await within(picker()).findByRole('option', { name: 'Smart Pick' })).toBeInTheDocument();
expect(within(picker()).queryByRole('option', { name: 'Favorites' })).not.toBeInTheDocument();
});
// ---- #651 round 9: making the stated invariant actually true on this screen ----
it.each([
{ id: 1.5, label: 'a fractional mediaItemId' },
{ id: 2_147_483_648, label: 'a mediaItemId above int32' }
])('round 9: $label drops its NAME too, blocks Save, and cannot reach a PUT', async ({ id }) => {
// The invariant claimed in spa-conventions — "surfaces as no selection, Save disabled, zero
// writes reachable" — was false here in all three respects: the name survived the dropped id
// (so the row read "Cool Movie" while the draft held null), Save had no selection check, and
// clicking it issued the PUT with `mediaItemId: null`.
const fetchMock = mockApi({
onRequest: (url, method) => {
if (url === '/api/v1/playlists/10/items' && method === 'GET') {
return jsonResponse([
{
...(playlistItems[10] as Array<Record<string, unknown>>)[1],
mediaItemId: id,
mediaItemName: 'Cool Movie'
}
]);
}
return null;
}
});
render(<PlaylistsScreen />);
fireEvent.click(await screen.findByText('Bumps'));
// LOAD-BEARING 1: the label goes with the id — no row claiming a selection the draft lacks.
expect(await screen.findByText(/no movie selected/i)).toBeInTheDocument();
expect(screen.queryByText('Cool Movie')).not.toBeInTheDocument();
// LOAD-BEARING 2: Save is gated on it, with a visible reason. Asserted as the EXACT string —
// a loose /need a selection/i matched both "1 item need" and "1 items needs", so it could not
// see the grammar it appeared to cover, and singular is the common case.
expect(screen.getByText('1 item needs a selection')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Save playlist' })).toBeDisabled();
// LOAD-BEARING 3: and the write is genuinely unreachable. Clicking a disabled button is usually
// a no-op restatement of `toBeDisabled()` (see RerunCollectionsScreen.test.tsx, where it is
// deliberately omitted) — it earns its place HERE because on the parent this button was
// ENABLED, so the click actually issued the PUT and this assertion is what discriminates.
fireEvent.click(screen.getByRole('button', { name: 'Save playlist' }));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(
fetchMock.mock.calls.filter(([u, i]) => u === '/api/v1/playlists/10/items' && (i?.method ?? '').toUpperCase() === 'PUT')
).toHaveLength(0);
});
it('round 9: an unbindable playlist GROUP id is not offered and cannot be posted', async () => {
// `playlistGroupId` is seeded from the wire and submitted as an entity reference — the same
// class, on the same screen, which the round-8 sweep missed.
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/v1/playlists/groups' && method === 'GET'
? jsonResponse([
{ id: 2_147_483_648, isSystem: false, name: 'Bogus Group', playlistCount: 0 },
{ id: 1, isSystem: false, name: 'Idents', playlistCount: 1 }
])
: null
});
render(<PlaylistsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'Add playlist' }));
const dialog = await screen.findByRole('dialog');
const groupSelect = within(dialog).getByRole('combobox');
// LOAD-BEARING: the unbindable group is not offered, so it cannot be chosen or submitted.
expect(within(groupSelect).getByRole('option', { name: 'Idents' })).toBeInTheDocument();
expect(within(groupSelect).queryByRole('option', { name: 'Bogus Group' })).not.toBeInTheDocument();
fireEvent.change(groupSelect, { target: { value: '2147483648' } });
fireEvent.change(within(dialog).getByPlaceholderText('Playlist name'), { target: { value: 'New' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));
await new Promise((resolve) => setTimeout(resolve, 0));
const posts = fetchMock.mock.calls.filter(
([u, i]) => u === '/api/v1/playlists' && (i?.method ?? '').toUpperCase() === 'POST'
);
// Unconditional FIRST: `posts` is empty on the fixed build (the unmatched value leaves the
// select at '', so Create is disabled and jsdom won't dispatch its onClick), which means the
// loop below runs ZERO assertions on its own. Without this line a future change that re-enabled
// Create and POSTed `playlistGroupId: null` would still pass.
expect(posts).toHaveLength(0);
for (const post of posts) {
expect(JSON.parse(String(post[1]?.body)).playlistGroupId).not.toBe(2_147_483_648);
}
});
});
+114 -60
View File
@@ -24,7 +24,6 @@ import {
deletePlaylist,
deletePlaylistGroup,
getCollections,
getLibraryBrowseItems,
getMultiCollections,
getPlaylistById,
getPlaylistGroups,
@@ -34,8 +33,12 @@ import {
loadAllPages,
messageFromPlaylistError,
previewPlaylist,
searchLibraryPickerOptions,
selectionIdOrNull,
isSelectionId,
updatePlaylist,
updatePlaylistGroup,
LIBRARY_PICKER_MIN_QUERY,
type LibraryBrowseMediaType,
type Playlist,
type PlaylistGroup,
@@ -43,6 +46,7 @@ import {
type PlaylistItemRequest,
type PlaylistPreviewItem
} from '../api';
import { SearchPicker } from '../schedules/pickers';
type CollectionType = PlaylistItemRequest['collectionType'];
type PlaybackOrder = PlaylistItemRequest['playbackOrder'];
@@ -52,22 +56,17 @@ interface PickerOption {
name: string;
}
// #644 follow-up: `browse` (media-library) picker sources are Class B — bounded to one page, with
// `hint: 'truncated'`/`totalCount` telling the caller there's more than fits (a real, expected
// cap — narrow via search). `collection`/`multi`/`smart` sources stay Class A (page to
// completeness) since they're inherently small, admin-created lists; `hint: 'incomplete'` there
// instead reflects `loadAllPages`'s `complete` flag, i.e. a defensive load that did not converge,
// not a cap. These two are NOT the same condition and must render different copy (round-3 review
// F1): "showing the first N of M" is arithmetically vacuous — and points at a search box that
// doesn't exist for this picker — when N === M on an incomplete Class A load.
// #651: `browse` (media-library) picker sources are no longer list-loaded at all — they resolve by
// SEARCH through a `SearchPicker`, so `loadPickerOptions` never returns items for them and the
// truncation hint they used to carry is gone with the truncation. `collection`/`multi`/`smart`
// sources stay Class A (page to completeness) since they're inherently small, admin-created lists;
// `hint: 'incomplete'` reflects `loadAllPages`'s `complete` flag, i.e. a defensive load that did
// not converge.
interface PickerLoadResult {
items: PickerOption[];
totalCount: number | null;
hint: 'incomplete' | 'none' | 'truncated';
hint: 'incomplete' | 'none';
}
const LIBRARY_BROWSE_PAGE_CAP = 100;
// The 12 playlist item types (mirrors PlaylistEditor.razor's Collection Type select).
// Playlist / RemoteStream and the rerun-only types are intentionally excluded here.
// Each entry knows how to load its picker options; every media-item type maps to a
@@ -156,48 +155,45 @@ function orderOptionsWithCurrent(type: CollectionType, current: PlaybackOrder):
return options.some((option) => option.value === current) ? options : [...options, orderOption(current)];
}
// See RerunCollectionsScreen: one ingress for list-backed options, dropping ids the API cannot bind.
function toPickerOptions(list: Array<{ id: unknown; name?: null | string }>): PickerOption[] {
return list.flatMap((entry) =>
isSelectionId(entry.id) ? [{ id: entry.id, name: entry.name ?? `#${entry.id}` }] : []
);
}
function loadPickerOptions(type: CollectionType, signal?: AbortSignal): Promise<PickerLoadResult> {
const config = configFor(type);
if (!config) {
return Promise.resolve({ hint: 'none', items: [], totalCount: 0 });
return Promise.resolve({ hint: 'none', items: [] });
}
switch (config.source) {
case 'collection':
return getCollections().then((list) => {
const items = list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }));
return { hint: 'none' as const, items, totalCount: items.length };
const items = toPickerOptions(list);
return { hint: 'none' as const, items };
});
case 'multi':
return loadAllPages(getMultiCollections, undefined, undefined, signal).then(({ complete, items: list }) => {
const items = list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }));
const items = toPickerOptions(list);
if (!complete && !signal?.aborted) {
// #644 follow-up F3: a superseded/aborted load (a type switch mid-load) also returns
// `complete: false` — that's expected, not a defect, so don't warn on it.
console.warn('PlaylistsScreen: multi-collection picker load did not complete; some items may be missing');
}
return { hint: complete ? ('none' as const) : ('incomplete' as const), items, totalCount: items.length };
return { hint: complete ? ('none' as const) : ('incomplete' as const), items };
});
case 'smart':
return getSmartCollections().then((list) => {
const items = list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }));
return { hint: 'none' as const, items, totalCount: items.length };
const items = toPickerOptions(list);
return { hint: 'none' as const, items };
});
default:
// Class B (#644 follow-up): a media-library picker over the largest tables (Episode, Song,
// Image, Movie, MusicVideo, ...), which can run into the tens of thousands of rows. Paging to
// completeness here would mean ~200 serial requests — each more expensive than the last
// (LuceneSearchIndex.Search computes hitsLimit = skip + limit) — to populate a native <select>
// with thousands of <option> nodes. Load ONE bounded page instead and surface the truncation
// (see docs/decisions/records/spa/list-completeness-vs-bounded-pickers.md).
return getLibraryBrowseItems({ mediaType: config.browse, pageNum: 0, pageSize: LIBRARY_BROWSE_PAGE_CAP }).then(
(result) => {
const page = result.page ?? [];
const items = page.map((item) => ({ id: item.mediaItemId ?? item.id, name: item.title ?? `#${item.id}` }));
const totalCount = result.totalCount ?? items.length;
return { hint: totalCount > items.length ? ('truncated' as const) : ('none' as const), items, totalCount };
}
);
// A media-library picker over the largest tables (Episode, Song, Image, Movie, MusicVideo,
// ...) loads NOTHING up front (#651): it resolves by search through `SearchPicker` below, so
// no path here can load an unbounded — or even a 100-row — window of the media library.
return Promise.resolve({ hint: 'none', items: [] });
}
}
@@ -237,25 +233,34 @@ function draftFromItem(item: PlaylistItem): DraftItem {
const source = configFor(item.collectionType)?.source ?? 'browse';
let selectedId: number | null;
let selectedName: string;
// NOTE the name is cleared with the id below whenever `selectionIdOrNull` rejects one: keeping a
// label for an id we refused to store makes the row claim "Blade Runner" while the draft holds
// null — two contradictory statements about the same item, and no "no selection" signal
// (#651 round 9).
switch (source) {
case 'collection':
selectedId = item.collectionId ?? null;
selectedId = selectionIdOrNull(item.collectionId);
selectedName = item.collectionName ?? '';
break;
case 'multi':
selectedId = item.multiCollectionId ?? null;
selectedId = selectionIdOrNull(item.multiCollectionId);
selectedName = item.multiCollectionName ?? '';
break;
case 'smart':
selectedId = item.smartCollectionId ?? null;
selectedId = selectionIdOrNull(item.smartCollectionId);
selectedName = item.smartCollectionName ?? '';
break;
default:
selectedId = item.mediaItemId ?? null;
selectedId = selectionIdOrNull(item.mediaItemId);
selectedName = item.mediaItemName ?? '';
}
if (selectedId === null) {
// An id we declined to store cannot have a valid label.
selectedName = '';
}
return {
collectionType: item.collectionType,
count: item.count != null ? String(item.count) : '',
@@ -356,10 +361,14 @@ function AddPlaylistDialog({
onSubmit: (values: { name: string; playlistGroupId: number }) => void;
open: boolean;
}) {
const [groupId, setGroupId] = useState(() => (groups[0] ? String(groups[0].id) : ''));
// The group id is seeded from the wire and submitted as an entity reference, so it is a selection
// id by `selectionId.ts`'s own definition and gets the same boundary treatment — otherwise "every
// path by which an id from the wire becomes editor state" is not literally true (#651 round 9).
const bindableGroups = groups.filter((group) => isSelectionId(group.id));
const [groupId, setGroupId] = useState(() => (bindableGroups[0] ? String(bindableGroups[0].id) : ''));
const [name, setName] = useState('');
const trimmed = name.trim();
const numericGroupId = groupId === '' ? null : Number(groupId);
const numericGroupId = selectionIdOrNull(groupId === '' ? null : Number(groupId));
return (
<Dialog
@@ -386,7 +395,7 @@ function AddPlaylistDialog({
<Select
label="Playlist group"
onChange={(event) => setGroupId(event.target.value)}
options={groups.map((group) => ({ label: group.name, value: String(group.id) }))}
options={bindableGroups.map((group) => ({ label: group.name, value: String(group.id) }))}
value={groupId}
/>
<div style={{ marginTop: 12 }}>
@@ -413,10 +422,11 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
const [name, setName] = useState('');
const [items, setItems] = useState<DraftItem[]>([]);
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [pickerItems, setPickerItems] = useState<PickerOption[]>([]);
// Options carry the TYPE that produced them — the previous type's options must not stay
// selectable under the new type's label while its load is in flight (#651 round 4 HIGH-2).
const [pickerFor, setPickerFor] = useState<{ items: PickerOption[]; type: CollectionType } | null>(null);
const [pickerError, setPickerError] = useState<string | null>(null);
const [pickerHint, setPickerHint] = useState<PickerLoadResult['hint']>('none');
const [pickerTotalCount, setPickerTotalCount] = useState<number | null>(null);
const pickerHelpId = useId();
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
@@ -480,20 +490,18 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
const controller = new AbortController();
loadPickerOptions(selectedType, controller.signal)
.then(({ hint, items, totalCount }) => {
.then(({ hint, items }) => {
if (!controller.signal.aborted) {
setPickerItems(items);
setPickerFor({ items, type: selectedType });
setPickerError(null);
setPickerHint(hint);
setPickerTotalCount(totalCount);
}
})
.catch((error: unknown) => {
if (!controller.signal.aborted) {
setPickerItems([]);
setPickerFor({ items: [], type: selectedType });
setPickerError(messageFromPlaylistError(error, 'Unable to load picker items'));
setPickerHint('none');
setPickerTotalCount(null);
}
});
@@ -502,6 +510,19 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
};
}, [selectedType]);
// 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 === selectedType ? pickerFor.items : [];
const browseMediaType = selectedType !== undefined ? configFor(selectedType)?.browse : undefined;
// Stable across renders: `SearchPicker`'s debounce effect lists `search` in its deps, so a fresh
// closure every render would restart the debounce on each keystroke's re-render.
const searchLibrary = useCallback(
(query: string) => (browseMediaType ? searchLibraryPickerOptions(browseMediaType, query) : Promise.resolve([])),
[browseMediaType]
);
const updateItem = (key: string, patch: Partial<DraftItem>) => {
setItems((current) => current.map((item) => (item.key === key ? { ...item, ...patch } : item)));
};
@@ -563,8 +584,20 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
const buildRequest = () => ({ items: items.map(toItemRequest), name: name.trim() });
// Every item must carry a selection the API can bind. Without this the screen happily PUT an item
// with a null id — the server 422s it (`ReplacePlaylistItemsHandler.CollectionTypeMustBeValid`),
// but the DB would persist it (`PlaylistItemConfiguration` marks all four FKs `IsRequired(false)`),
// so that handler check is the only thing standing there. Fail closed on the client too.
const itemsMissingSelection = items.filter((item) => item.selectedId == null).length;
const validationError =
name.trim().length === 0
? 'Name is required'
: itemsMissingSelection > 0
? `${itemsMissingSelection} item${itemsMissingSelection === 1 ? '' : 's'} need${itemsMissingSelection === 1 ? 's' : ''} a selection`
: null;
const save = async () => {
if (isSystem || saving || name.trim().length === 0) {
if (isSystem || saving || validationError !== null) {
return;
}
@@ -676,8 +709,9 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
>
Add item
</Button>
{!isSystem && validationError && <Badge tone="neutral">{validationError}</Badge>}
<Button
disabled={isSystem || saving || name.trim().length === 0}
disabled={isSystem || saving || validationError !== null}
loading={saving}
onClick={() => void save()}
size="sm"
@@ -779,24 +813,44 @@ function PlaylistEditor({ playlistId, onBack, onSaved }: { playlistId: number; o
/>
<div style={{ marginTop: 12 }}>
<Select
ariaDescribedBy={pickerError || pickerHint !== 'none' ? pickerHelpId : undefined}
label={activeConfig?.label ?? 'Selection'}
onChange={(event) => setItemSelection(selectedItem.key, event.target.value)}
options={pickerOptions}
value={selectedItem.selectedId == null ? '' : String(selectedItem.selectedId)}
/>
{browseMediaType ? (
// #651: the media library is resolved by search, never list-loaded. The current
// selection renders from the DRAFT ITEM (`selectedName`, loaded with the playlist),
// not from the result set — so editing an existing item shows its real selection
// before, during and after any search, and never silently loses it.
<SearchPicker
ariaDescribedBy={pickerHelpId}
key={`${selectedItem.key}:${selectedItem.collectionType}`}
label={activeConfig?.label ?? 'Selection'}
minQueryLength={LIBRARY_PICKER_MIN_QUERY}
onClear={() => updateItem(selectedItem.key, { selectedId: null, selectedName: '' })}
onSelect={(id, name) => updateItem(selectedItem.key, { selectedId: id, selectedName: name })}
placeholder={`Search ${(activeConfig?.label ?? 'items').toLowerCase()}…`}
search={searchLibrary}
source={selectedItem.collectionType}
selectedId={selectedItem.selectedId}
selectedName={selectedItem.selectedName || null}
/>
) : (
<Select
ariaDescribedBy={pickerError || pickerHint !== 'none' ? pickerHelpId : undefined}
label={activeConfig?.label ?? 'Selection'}
onChange={(event) => setItemSelection(selectedItem.key, event.target.value)}
options={pickerOptions}
value={selectedItem.selectedId == null ? '' : String(selectedItem.selectedId)}
/>
)}
{pickerError && (
<span className="ctv-field-error" id={pickerHelpId} role="alert">
{pickerError}
</span>
)}
{!pickerError && pickerHint === 'truncated' && (
{!pickerError && browseMediaType && (
<span className="ctv-field-help" id={pickerHelpId}>
Showing the first {pickerItems.length} of {pickerTotalCount} — use search to narrow.
Type at least {LIBRARY_PICKER_MIN_QUERY} characters to search the library.
</span>
)}
{!pickerError && pickerHint === 'incomplete' && (
{!pickerError && !browseMediaType && pickerHint === 'incomplete' && (
<span className="ctv-field-help" id={pickerHelpId}>
List may be incomplete — retry to reload.
</span>
+693 -42
View File
@@ -1,7 +1,17 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RerunCollectionsScreen } from './RerunCollectionsScreen';
// A single-record GET response. It ALWAYS carries an ETag, because a real server does and because
// the editor now refuses to open without one (#651 round 6): mocks that omitted the header were
// silently exercising a force-write path that must not exist. Use this for every detail GET.
function detailResponse(body: unknown, etag = '"v1"'): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json', ETag: etag },
status: 200
});
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
@@ -27,13 +37,27 @@ const manualCollections = [
const multiCollections = [{ id: 8, items: [], name: 'Bundle' }];
// A stored rerun collection whose selection the DETAIL endpoint may fail to name (#651 F1).
const storedSelection = {
collectionType: 'RemoteStream',
firstRunPlaybackOrder: 'Chronological',
id: 9,
name: 'Stored Rerun',
rerunPlaybackOrder: 'Chronological',
selectedId: 42,
selectedName: 'Stored Item'
};
interface MockOptions {
browsePage?: unknown;
list?: unknown[];
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
const list = options.list ?? rerunCollections;
const browsePage = options.browsePage ?? { page: [], totalCount: 0 };
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
@@ -52,7 +76,7 @@ function mockApi(options: MockOptions = {}) {
const rerunById = url.match(/^\/api\/v1\/rerun-collections\/(\d+)$/);
if (rerunById && method === 'GET') {
const found = (list as Array<{ id: number }>).find((r) => String(r.id) === rerunById[1]) ?? list[0];
return Promise.resolve(jsonResponse(found));
return Promise.resolve(detailResponse(found));
}
if (url.startsWith('/api/v1/rerun-collections') && method === 'GET') {
@@ -72,7 +96,7 @@ function mockApi(options: MockOptions = {}) {
}
if (url.startsWith('/api/v1/library/browse')) {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
return Promise.resolve(jsonResponse(browsePage));
}
return Promise.resolve(new Response(null, { status: 204 }));
@@ -162,37 +186,19 @@ describe('RerunCollectionsScreen', () => {
expect(await within(refreshed[1]).findByText('Bundle')).toBeInTheDocument();
});
it('Class B picker: a media-library type issues exactly ONE /library/browse request and surfaces the truncation hint (#644 follow-up)', async () => {
const total = 5000;
const cap = 100;
const page = Array.from({ length: cap }, (_, i) => ({
id: i + 1,
mediaItemId: i + 1,
mediaType: 'Movie' as const,
title: `Movie ${i + 1}`
}));
const fetchMock = mockApi({ list: [] });
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(input.toString(), 'http://localhost');
const method = (init?.method ?? 'GET').toUpperCase();
if (url.pathname === '/api/v1/library/browse' && method === 'GET') {
return Promise.resolve(jsonResponse({ page, totalCount: total }));
}
if (url.pathname === '/api/v1/rerun-collections' && method === 'GET') {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
if (url.pathname === '/api/v1/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manualCollections));
}
if (url.pathname === '/api/v1/multi-collections' && method === 'GET') {
return Promise.resolve(jsonResponse({ page: multiCollections, totalCount: multiCollections.length }));
}
if (url.pathname === '/api/v1/smart-collections' && method === 'GET') {
return Promise.resolve(jsonResponse([]));
}
return Promise.resolve(new Response(null, { status: 204 }));
it('media-library picker: resolves by SEARCH — zero browse requests until the user types (#651)', async () => {
const fetchMock = mockApi({
list: [],
onRequest: (url) =>
url.startsWith('/api/v1/library/browse')
? jsonResponse({
page: [
{ id: 1, mediaItemId: 1, mediaType: 'Movie', title: 'Movie 1' },
{ id: 2, mediaItemId: 2, mediaType: 'Movie', title: 'Movie 2' }
],
totalCount: 2
})
: null
});
render(<RerunCollectionsScreen />);
@@ -201,16 +207,96 @@ describe('RerunCollectionsScreen', () => {
const typeSelect = (await screen.findAllByRole('combobox'))[0];
fireEvent.change(typeSelect, { target: { value: 'Movie' } });
// The bounded page renders (100 options) and the truncation hint appears.
expect(await screen.findByText(/Showing the first 100 of 5000/)).toBeInTheDocument();
const picker = (await screen.findAllByRole('combobox'))[1];
expect(await within(picker).findByText('Movie 100')).toBeInTheDocument();
// The picker is a typeahead, not a <select>: only the three type/order selects remain as
// native <select>s (the typeahead input carries role="combobox" per the ARIA pattern, so count
// elements, not roles).
const searchInput = await screen.findByLabelText('Movie search');
expect(document.querySelectorAll('select')).toHaveLength(3);
expect(screen.getByText(/Type at least 2 characters to search the library/)).toBeInTheDocument();
// Selecting the type loads NOTHING from the media library.
const browseCalls = () =>
fetchMock.mock.calls.filter(
([u]) => new URL(u.toString(), 'http://localhost').pathname === '/api/v1/library/browse'
);
expect(browseCalls()).toHaveLength(0);
// A single character is below the minimum — still no request.
fireEvent.focus(searchInput);
fireEvent.change(searchInput, { target: { value: 'S' } });
await new Promise((resolve) => setTimeout(resolve, 400));
expect(browseCalls()).toHaveLength(0);
// Typed text is COMPILED to a bounded, escaped title-contains query — never forwarded raw.
fireEvent.change(searchInput, { target: { value: 'Show Alpha' } });
await waitFor(() => expect(browseCalls().length).toBeGreaterThan(0));
const url = new URL(browseCalls()[0][0].toString(), 'http://localhost');
expect(url.searchParams.get('query')).toBe('title:*Show\\ Alpha*');
expect(url.searchParams.get('mediaType')).toBe('Movie');
expect(url.searchParams.get('pageNum')).toBe('0');
expect(Number(url.searchParams.get('pageSize'))).toBeLessThanOrEqual(25);
expect(await screen.findByRole('option', { name: 'Movie 1' })).toBeInTheDocument();
});
it('media-library picker: a HUGE library stays bounded — one request per settled query, one page each (#651)', async () => {
// 20,000 rows: the exact shape that made paging-to-completeness untenable. Whatever pageSize is
// asked for, the fixture returns at most that many rows, so an unbounded loader would show up
// BOTH as extra requests and as a huge option list.
const TOTAL = 20000;
const fetchMock = mockApi({ list: [] });
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(input.toString(), 'http://localhost');
const method = (init?.method ?? 'GET').toUpperCase();
if (url.pathname === '/api/v1/library/browse' && method === 'GET') {
const pageSize = Number(url.searchParams.get('pageSize') ?? '100');
const pageNum = Number(url.searchParams.get('pageNum') ?? '0');
return Promise.resolve(
jsonResponse({
page: Array.from({ length: Math.min(pageSize, TOTAL - pageNum * pageSize) }, (_, i) => ({
id: pageNum * pageSize + i + 1,
mediaItemId: pageNum * pageSize + i + 1,
mediaType: 'Episode' as const,
title: `Episode ${pageNum * pageSize + i + 1}`
})),
totalCount: TOTAL
})
);
}
if (url.pathname === '/api/v1/rerun-collections' && method === 'GET') {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
if (url.pathname === '/api/v1/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manualCollections));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'New rerun collection' }));
const typeSelect = (await screen.findAllByRole('combobox'))[0];
fireEvent.change(typeSelect, { target: { value: 'Episode' } });
const searchInput = await screen.findByLabelText('Episode search');
fireEvent.focus(searchInput);
fireEvent.change(searchInput, { target: { value: 'Episode' } });
const results = () => screen.queryByRole('listbox', { name: 'Episode results' });
await waitFor(() => expect(results()).not.toBeNull());
// Let any (nonexistent) follow-up paging loop have time to fire.
await new Promise((resolve) => setTimeout(resolve, 500));
// Exactly ONE /library/browse request — no paging-to-completeness loop over the media library.
const browseCalls = fetchMock.mock.calls.filter(
([u]) => new URL(u.toString(), 'http://localhost').pathname === '/api/v1/library/browse'
);
// ONE request for the settled query — not ~200 pages against a 20k-row table.
expect(browseCalls).toHaveLength(1);
expect(Number(new URL(browseCalls[0][0].toString(), 'http://localhost').searchParams.get('pageSize'))).toBe(25);
// ...and at most one bounded page of options rendered.
expect(within(results() as HTMLElement).getAllByRole('option').length).toBeLessThanOrEqual(25);
});
it('preserves an out-of-set stored playback order on edit-load and re-saves it unchanged', async () => {
@@ -236,10 +322,20 @@ describe('RerunCollectionsScreen', () => {
fireEvent.click(await screen.findByText('Odd Order Reruns'));
// combobox order: [0] Collection Type, [1] selection picker, [2] First Run, [3] Rerun.
// Artist is a media-library type, so its selection picker is a search typeahead, not a
// combobox: [0] Collection Type, [1] First Run, [2] Rerun.
const comboboxes = await screen.findAllByRole('combobox');
const firstRunSelect = comboboxes[2];
const rerunSelect = comboboxes[3];
const firstRunSelect = comboboxes[1];
const rerunSelect = comboboxes[2];
// #651: the stored selection is shown from the RECORD's own selectedName, with no library load
// at all — an edit must never lose (or fail to name) the item it already points at.
expect(await screen.findByText('Some Artist')).toBeInTheDocument();
expect(
fetchMock.mock.calls.filter(
([u]) => new URL(u.toString(), 'http://localhost').pathname === '/api/v1/library/browse'
)
).toHaveLength(0);
// Artist's normal order set (Chronological / Random / Shuffle) does not include
// SeasonEpisode, but the stored value must still be present and selected.
@@ -378,4 +474,559 @@ describe('RerunCollectionsScreen', () => {
).toBe(true);
});
});
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. 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' }],
onRequest: (url, method) => {
if (url === '/api/v1/rerun-collections/9' && method === 'GET') {
detailCalls += 1;
return detailResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null });
}
return null;
}
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByText('Stored Rerun'));
await waitFor(() => expect(detailCalls).toBe(1));
await new Promise((resolve) => setTimeout(resolve, 0));
const typeSelect = (await screen.findAllByRole('combobox'))[0] as HTMLSelectElement;
expect(typeSelect.value).toBe('RemoteStream');
// The Collection id must NOT have been carried across into the RemoteStream id space.
expect(screen.queryByText('Favorites')).not.toBeInTheDocument();
expect(screen.queryByText('#5')).not.toBeInTheDocument();
expect(screen.getByLabelText('Remote Stream search')).toBeInTheDocument();
});
it('HIGH-2: options from the PREVIOUS type are not selectable while the new type loads', async () => {
// Slow connection: switching Collection -> SmartCollection clears the selection immediately but
// the smart-collections request is still in flight. The old Collection options must not remain
// on offer under the SmartCollection label — picking one would write a Collection id into the
// SmartCollection namespace (#651 round 4 HIGH-2).
const smartRelease: { resolve: (() => void) | null } = { resolve: null };
const fetchMock = mockApi({ list: [] });
fetchMock.mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(input.toString(), 'http://localhost');
const method = (init?.method ?? 'GET').toUpperCase();
if (url.pathname === '/api/v1/smart-collections' && method === 'GET') {
return new Promise<Response>((resolve) => {
smartRelease.resolve = () => resolve(jsonResponse([{ id: 77, name: 'Smart Pick' }]));
});
}
if (url.pathname === '/api/v1/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manualCollections));
}
if (url.pathname === '/api/v1/rerun-collections' && method === 'GET') {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'New rerun collection' }));
const picker = () => (screen.getAllByRole('combobox'))[1];
await within(picker()).findByText('Favorites');
const typeSelect = screen.getAllByRole('combobox')[0];
fireEvent.change(typeSelect, { target: { value: 'SmartCollection' } });
// Mid-load: the picker offers nothing rather than the wrong namespace's rows.
expect(within(picker()).queryByText('Favorites')).not.toBeInTheDocument();
expect(within(picker()).queryByRole('option', { name: 'Favorites' })).not.toBeInTheDocument();
smartRelease.resolve?.();
expect(await within(picker()).findByText('Smart Pick')).toBeInTheDocument();
expect(within(picker()).queryByText('Favorites')).not.toBeInTheDocument();
});
// ---- #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 };
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') {
return new Promise<Response>((resolve) => {
detailRelease.resolve = () => resolve(detailResponse(storedSelection));
});
}
return inner(input, init);
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByText('Stored Rerun'));
// 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?.();
expect(await screen.findByPlaceholderText('Rerun collection name')).toBeInTheDocument();
});
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 === 'GET'
? detailResponse({ ...storedSelection, collectionType: 'Collection', name: 'Server Name', selectedId: 5, selectedName: 'Favorites' })
: null
});
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'));
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: the form is ABSENT while pending, and a dirty selection is discarded even when the server sends none', async () => {
// Replaces the deleted "conflict Reload with a null server selection" regression. Both halves
// matter and the previous version had neither: its second GET resolved immediately (so it never
// observed a pending Reload) and returned a non-null selection (so removing `setDraft(null)`
// could leave it green). Here the reload is HELD OPEN and returns `selectedId: null` — the #671
// shape that round 3 showed could resurrect the user's dirty id over a collaborator's change.
const reloadRelease: { resolve: (() => void) | null } = { resolve: null };
let detailCalls = 0;
const fetchMock = mockApi({
browsePage: { page: [{ id: 99, mediaItemId: 99, mediaType: 'RemoteStream', title: 'New Stream' }], totalCount: 1 },
list: [{ ...storedSelection, collectionType: 'RemoteStream' }],
onRequest: (url, method) =>
url === '/api/v1/rerun-collections/9' && method === 'PUT' ? new Response(null, { status: 412 }) : 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(
detailResponse({ ...storedSelection, collectionType: 'RemoteStream', selectedId: 42, selectedName: 'Stored Stream' })
);
}
return new Promise<Response>((resolve) => {
reloadRelease.resolve = () =>
resolve(
detailResponse(
{ ...storedSelection, collectionType: 'RemoteStream', selectedId: null, selectedName: null },
'"v2"'
)
);
});
}
return inner(input, init);
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByText('Stored Rerun'));
await screen.findByPlaceholderText('Rerun collection name');
// Dirty the selection, then hit the conflict and choose Reload.
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' }));
expect(screen.getByLabelText(/^Clear /)).toBeInTheDocument();
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));
// (1) While the reload is PENDING the form does not exist — nothing to edit, nothing to preserve.
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();
reloadRelease.resolve?.();
await screen.findByPlaceholderText('Rerun collection name');
// (2) The server sent NO selection, and the user's dirty id 99 is gone rather than resurrected.
expect(screen.queryByText('New Stream')).not.toBeInTheDocument();
expect(screen.queryByLabelText(/^Clear /)).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeDisabled();
expect(
fetchMock.mock.calls.filter(([u, i]) => u === '/api/v1/rerun-collections/9' && (i?.method ?? '').toUpperCase() === 'PUT')
).toHaveLength(1);
});
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'
? detailResponse({ ...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();
});
// Absent, empty and whitespace-only are not three cases — they are one: "no usable concurrency
// token". Validating only `null` let an empty ETag through the gate into an editable draft, where
// `updateRerunCollection`'s `ifMatch ? … : undefined` dropped it as falsy and force-wrote over a
// collaborator (#651 round 7 HIGH). Each shape must be unable to produce a draft at all.
it.each([
{ etag: undefined, label: 'no ETag header at all' },
{ etag: '', label: 'an empty ETag' },
{ etag: ' ', label: 'a whitespace-only ETag' },
{ etag: '\t\n', label: 'a tab/newline ETag' }
])('HIGH: $label yields an error, never an editable draft and never a PUT', async ({ etag }) => {
const fetchMock = mockApi({
list: [storedSelection],
onRequest: (url, method) =>
url === '/api/v1/rerun-collections/9' && method === 'GET'
? new Response(JSON.stringify(storedSelection), {
headers:
etag === undefined
? { 'Content-Type': 'application/json' }
: { 'Content-Type': 'application/json', ETag: etag },
status: 200
})
: null
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByText('Stored Rerun'));
expect(await screen.findByRole('alert')).toBeInTheDocument();
expect(screen.getByText(/without a version tag/i)).toBeInTheDocument();
expect(screen.queryByPlaceholderText('Rerun collection name')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Save rerun collection' })).not.toBeInTheDocument();
// The decisive assertion: no unconditional write is reachable at all.
expect(
fetchMock.mock.calls.filter(([u, i]) => u === '/api/v1/rerun-collections/9' && (i?.method ?? '').toUpperCase() === 'PUT')
).toHaveLength(0);
});
it('a padded ETag is TRIMMED and sent as If-Match, not dropped', async () => {
// The other half of "one class": a usable token surrounded by whitespace must still be USED.
// NOTE this is a regression guard, not a demonstration of a defect — `Headers` strips outer
// HTTP whitespace before the app sees it, so this passes pre-#651-round-7 too. It exists so a
// future `usableEtag` that rejects (rather than trims) padding cannot land silently.
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: ' "v3" ' },
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, i]) => u === '/api/v1/rerun-collections/9' && (i?.method ?? '').toUpperCase() === 'PUT'
);
expect(put).toBeDefined();
expect((put?.[1]?.headers as Record<string, string>)['If-Match']).toBe('"v3"');
});
});
// A fetch that honours its AbortSignal, as the real one does. A stub that ignores the signal
// would let an abandoned request live forever and hide exactly what these tests pin.
function abortableDetailFetch() {
const state = { aborts: 0, inFlight: 0, starts: 0 };
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
if (url === '/api/v1/rerun-collections/9') {
state.starts += 1;
state.inFlight += 1;
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
state.aborts += 1;
state.inFlight -= 1;
reject(new DOMException('Aborted', 'AbortError'));
});
});
}
if (url.startsWith('/api/v1/rerun-collections')) {
return Promise.resolve(jsonResponse({ page: [storedSelection], totalCount: 1 }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
return state;
}
it('a never-settling detail GET is ABORTED at the deadline, with a way back and a working Retry', async () => {
vi.useFakeTimers();
try {
const state = abortableDetailFetch();
render(<RerunCollectionsScreen />);
await act(async () => {
await vi.advanceTimersByTimeAsync(10);
});
fireEvent.click(screen.getByText('Stored Rerun'));
await act(async () => {
await vi.advanceTimersByTimeAsync(10);
});
// A route out exists while waiting — a hung request is never a dead end.
expect(screen.getByRole('button', { name: 'All rerun collections' })).toBeInTheDocument();
expect(state.inFlight).toBe(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(16_000);
});
// The deadline CANCELS the work rather than merely abandoning the wait: otherwise each Retry
// would stack another live connection (#651 round 7).
expect(state.aborts).toBe(1);
expect(state.inFlight).toBe(0);
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.getByText(/timed out/i)).toBeInTheDocument();
// Retry reissues exactly one new request — not one per previous attempt.
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
await act(async () => {
await vi.advanceTimersByTimeAsync(10);
});
expect(state.starts).toBe(2);
expect(state.inFlight).toBe(1);
expect(screen.getByText('Loading rerun collection…')).toBeInTheDocument();
} finally {
vi.useRealTimers();
}
});
it('unmounting aborts the in-flight detail read and clears its deadline', async () => {
vi.useFakeTimers();
try {
const state = abortableDetailFetch();
const { unmount } = render(<RerunCollectionsScreen />);
await act(async () => {
await vi.advanceTimersByTimeAsync(10);
});
fireEvent.click(screen.getByText('Stored Rerun'));
await act(async () => {
await vi.advanceTimersByTimeAsync(10);
});
expect(state.inFlight).toBe(1);
unmount();
expect(state.aborts).toBe(1);
expect(state.inFlight).toBe(0);
// The deadline timer is cleared too, so it cannot fire against an unmounted tree.
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000);
});
expect(state.aborts).toBe(1);
} finally {
vi.useRealTimers();
}
});
// Guards the ABORT/RACE COMPOSITION, not a round-6 defect: round 6's race guard already covered
// the ordinary case. What this fails is an abort-ONLY implementation whose fetch ignores its
// signal — which is exactly the mutation it was written for, and why the stub below deliberately
// ignores `init.signal`.
it('a detail read that settles LATE, after the deadline, cannot revive the editor', async () => {
vi.useFakeTimers();
try {
const late: { resolve: ((r: Response) => void) | null } = { resolve: null };
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
const url = input.toString();
if (url === '/api/v1/rerun-collections/9') {
// Deliberately IGNORES the abort signal — the worst case, to prove the `active`/error
// state does not depend on cancellation actually working.
return new Promise<Response>((resolve) => {
late.resolve = resolve;
});
}
if (url.startsWith('/api/v1/rerun-collections')) {
return Promise.resolve(jsonResponse({ page: [storedSelection], totalCount: 1 }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
render(<RerunCollectionsScreen />);
await act(async () => {
await vi.advanceTimersByTimeAsync(10);
});
fireEvent.click(screen.getByText('Stored Rerun'));
await act(async () => {
await vi.advanceTimersByTimeAsync(16_000);
});
expect(screen.getByRole('alert')).toBeInTheDocument();
// The abandoned request finally answers. It must not resurrect a form the user was told failed.
await act(async () => {
late.resolve?.(
new Response(JSON.stringify(storedSelection), {
headers: { 'Content-Type': 'application/json', ETag: '"late"' },
status: 200
})
);
await vi.advanceTimersByTimeAsync(10);
});
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.queryByPlaceholderText('Rerun collection name')).not.toBeInTheDocument();
} finally {
vi.useRealTimers();
}
});
// ---- #651 round 8: the int32 boundary, on EVERY ingress ----
//
// Round 7 put the predicate inside the search picker's option validator — the site the defect was
// found at — leaving the two other doors into `draft.selectedId` open. These pin them.
it.each([
{ id: 1.5, label: 'a fractional selectedId' },
{ id: 2_147_483_648, label: 'a selectedId above int32' },
{ id: -2_147_483_649, label: 'a selectedId below int32' }
])('round 8: $label in the DETAIL response cannot enable Save or reach a PUT', async ({ id }) => {
mockApi({
list: [storedSelection],
onRequest: (url, method) =>
url === '/api/v1/rerun-collections/9' && method === 'GET'
? detailResponse({ ...storedSelection, collectionType: 'Collection', selectedId: id, selectedName: 'Bogus' })
: null
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByText('Stored Rerun'));
await screen.findByPlaceholderText('Rerun collection name');
// Treated as ABSENT — visibly, with the reason — rather than as a selection that fails on write.
// These two ARE the load-bearing assertions. Clicking the disabled Save is deliberately NOT done
// here: this button is disabled on the parent too, so the click would only restate
// `toBeDisabled()`. (PlaylistsScreen.test.tsx does click it — there the parent left the button
// enabled, so the click genuinely discriminates. The difference is what the parent did, not a
// difference of policy.)
expect(screen.getByText('A selection is required')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Save rerun collection' })).toBeDisabled();
});
it.each([
{ id: 1.5, label: 'a fractional id' },
{ id: 2_147_483_648, label: 'an id above int32' }
])('round 8: a LIST-BACKED option with $label is not offered, so it cannot be selected or saved', async ({ id }) => {
const fetchMock = mockApi({
list: [],
onRequest: (url, method) =>
url === '/api/v1/collections' && method === 'GET'
? jsonResponse([
{ collectionType: 'Collection', id, name: 'Bogus Collection', state: 'Normal', useCustomPlaybackOrder: false },
{ collectionType: 'Collection', id: 5, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: false }
])
: null
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'New rerun collection' }));
const picker = (await screen.findAllByRole('combobox'))[1];
// LOAD-BEARING: the bindable option is offered, the malformed one is not rendered at all.
expect(await within(picker).findByText('Favorites')).toBeInTheDocument();
expect(within(picker).queryByText('Bogus Collection')).not.toBeInTheDocument();
// Now actually try to submit it. Selecting a value the <select> never offered leaves the draft
// without a selection, so the save is refused — asserting a POST count without attempting one
// would be trivially true and would pass against the unguarded parent too.
fireEvent.change(picker, { target: { value: String(id) } });
fireEvent.change(screen.getByPlaceholderText('Rerun collection name'), { target: { value: 'Attempted' } });
fireEvent.click(screen.getByRole('button', { name: 'Add rerun collection' }));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(
fetchMock.mock.calls.filter(([u, i]) => u === '/api/v1/rerun-collections' && (i?.method ?? '').toUpperCase() === 'POST')
).toHaveLength(0);
});
});
+252 -82
View File
@@ -8,18 +8,22 @@ import {
createRerunCollection,
deleteRerunCollection,
getCollections,
getLibraryBrowseItems,
getMultiCollections,
getRerunCollectionWithMeta,
getRerunCollections,
getSmartCollections,
loadAllPages,
messageFromRerunCollectionError,
searchLibraryPickerOptions,
selectionIdOrNull,
updateRerunCollection,
isSelectionId,
LIBRARY_PICKER_MIN_QUERY,
type CreateRerunCollectionRequest,
type LibraryBrowseMediaType,
type RerunCollection
} from '../api';
import { SearchPicker } from '../schedules/pickers';
type RerunCollectionType = CreateRerunCollectionRequest['collectionType'];
type PlaybackOrder = CreateRerunCollectionRequest['firstRunPlaybackOrder'];
@@ -29,22 +33,17 @@ interface PickerOption {
name: string;
}
// #644 follow-up: `browse` (media-library) picker sources are Class B — bounded to one page, with
// `hint: 'truncated'`/`totalCount` telling the caller there's more than fits (a real, expected
// cap — narrow via search). `collection`/`multi`/`smart` sources stay Class A (page to
// completeness) since they're inherently small, admin-created lists; `hint: 'incomplete'` there
// instead reflects `loadAllPages`'s `complete` flag, i.e. a defensive load that did not converge,
// not a cap. These two are NOT the same condition and must render different copy (round-3 review
// F1): "showing the first N of M" is arithmetically vacuous — and points at a search box that
// doesn't exist for this picker — when N === M on an incomplete Class A load.
// #651: `browse` (media-library) picker sources are no longer list-loaded at all — they resolve by
// SEARCH through a `SearchPicker`, so `loadPickerOptions` never returns items for them and the
// truncation hint they used to carry is gone with the truncation. `collection`/`multi`/`smart`
// sources stay Class A (page to completeness) since they're inherently small, admin-created lists;
// `hint: 'incomplete'` reflects `loadAllPages`'s `complete` flag, i.e. a defensive load that did
// not converge.
interface PickerLoadResult {
items: PickerOption[];
totalCount: number | null;
hint: 'incomplete' | 'none' | 'truncated';
hint: 'incomplete' | 'none';
}
const LIBRARY_BROWSE_PAGE_CAP = 100;
// The REST-supported selection types (RerunCollectionRequestMapping.IsSupportedSelectionType).
// Playlist / RerunFirstRun / RerunRerun / SearchQuery / Fake* are intentionally excluded.
// Each entry knows how to load its picker options; every media-item type maps to a
@@ -109,48 +108,47 @@ function orderOptionsWithCurrent(type: RerunCollectionType, current: PlaybackOrd
return options.some((option) => option.value === current) ? options : [...options, orderOption(current)];
}
// One ingress for list-backed options. An id the API cannot bind is DROPPED rather than offered:
// an unselectable option is better than one that fails on save (#651 round 8 — the boundary, not
// the site).
function toPickerOptions(list: Array<{ id: unknown; name?: null | string }>): PickerOption[] {
return list.flatMap((entry) =>
isSelectionId(entry.id) ? [{ id: entry.id, name: entry.name ?? `#${entry.id}` }] : []
);
}
function loadPickerOptions(type: RerunCollectionType, signal?: AbortSignal): Promise<PickerLoadResult> {
const config = COLLECTION_TYPES.find((entry) => entry.value === type);
if (!config) {
return Promise.resolve({ hint: 'none', items: [], totalCount: 0 });
return Promise.resolve({ hint: 'none', items: [] });
}
switch (config.source) {
case 'collection':
return getCollections().then((list) => {
const items = list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }));
return { hint: 'none' as const, items, totalCount: items.length };
const items = toPickerOptions(list);
return { hint: 'none' as const, items };
});
case 'multi':
return loadAllPages(getMultiCollections, undefined, undefined, signal).then(({ complete, items: list }) => {
const items = list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }));
const items = toPickerOptions(list);
if (!complete && !signal?.aborted) {
// #644 follow-up F3: a superseded/aborted load (Retry, or a type switch mid-load) also
// returns `complete: false` — that's expected, not a defect, so don't warn on it.
console.warn('RerunCollectionsScreen: multi-collection picker load did not complete; some items may be missing');
}
return { hint: complete ? ('none' as const) : ('incomplete' as const), items, totalCount: items.length };
return { hint: complete ? ('none' as const) : ('incomplete' as const), items };
});
case 'smart':
return getSmartCollections().then((list) => {
const items = list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }));
return { hint: 'none' as const, items, totalCount: items.length };
const items = toPickerOptions(list);
return { hint: 'none' as const, items };
});
default:
// Class B (#644 follow-up): a media-library picker over the largest tables (Episode, Song,
// Image, Movie, MusicVideo, ...), which can run into the tens of thousands of rows. Paging to
// completeness here would mean ~200 serial requests — each more expensive than the last
// (LuceneSearchIndex.Search computes hitsLimit = skip + limit) — to populate a native <select>
// with thousands of <option> nodes. Load ONE bounded page instead and surface the truncation
// (see docs/decisions/records/spa/list-completeness-vs-bounded-pickers.md).
return getLibraryBrowseItems({ mediaType: config.browse, pageNum: 0, pageSize: LIBRARY_BROWSE_PAGE_CAP }).then(
(result) => {
const page = result.page ?? [];
const items = page.map((item) => ({ id: item.mediaItemId ?? item.id, name: item.title ?? `#${item.id}` }));
const totalCount = result.totalCount ?? items.length;
return { hint: totalCount > items.length ? ('truncated' as const) : ('none' as const), items, totalCount };
}
);
// A media-library picker over the largest tables (Episode, Song, Image, Movie, MusicVideo,
// ...) loads NOTHING up front (#651): it resolves by search through `SearchPicker` below, so
// no path here can load an unbounded — or even a 100-row — window of the media library.
return Promise.resolve({ hint: 'none', items: [] });
}
}
@@ -231,17 +229,49 @@ interface Draft {
selectedName: string;
}
// Upper bound on the detail read. A never-settling request must not strand the editor.
const LOAD_TIMEOUT_MS = 15_000;
// The ONE place that decides whether a concurrency token is usable. `null`, `''` and a
// whitespace-only header are not three cases — they are one: "no usable token". Treating only
// `null` as absent let an empty ETag through the fail-closed gate and into an editable draft, where
// `updateRerunCollection`'s `ifMatch ? … : undefined` then dropped it as falsy and force-wrote over
// a collaborator (#651 round 7 HIGH). Returning the TRIMMED token means `etagRef` can only ever
// hold something that will actually be sent.
function usableEtag(etag: string | null | undefined): string | null {
const trimmed = etag?.trim() ?? '';
return trimmed.length > 0 ? trimmed : null;
}
function draftFromRerun(rerun: RerunCollection): Draft {
return {
collectionType: rerun.collectionType,
firstRunPlaybackOrder: rerun.firstRunPlaybackOrder,
name: rerun.name ?? '',
rerunPlaybackOrder: rerun.rerunPlaybackOrder,
selectedId: rerun.selectedId ?? null,
// The other ingress: a malformed id in an otherwise-successful detail response must not become
// an apparently-valid selection. Treated as absent, so Save is disabled and says why.
selectedId: selectionIdOrNull(rerun.selectedId),
selectedName: rerun.selectedName ?? ''
};
}
// 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,
onBack,
@@ -251,9 +281,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',
@@ -263,71 +297,127 @@ function RerunCollectionEditor({
selectedName: ''
}
);
const [pickerItems, setPickerItems] = useState<PickerOption[]>([]);
// Options carry the TYPE that produced them. Keeping a bare array meant the previous type's
// options stayed on screen under the new type's label while its load was in flight, so a slow
// connection let the user store e.g. a Collection id in the SmartCollection namespace (#651
// round 4 HIGH-2). Same rule as the search picker's `source`: an id is only meaningful inside
// the namespace it came from.
const [pickerFor, setPickerFor] = useState<{ items: PickerOption[]; type: RerunCollectionType } | null>(null);
const [pickerError, setPickerError] = useState<string | null>(null);
const [pickerHint, setPickerHint] = useState<PickerLoadResult['hint']>('none');
const [pickerTotalCount, setPickerTotalCount] = useState<number | null>(null);
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);
const [reloadKey, setReloadKey] = useState(0);
// 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);
const { collectionType } = draft;
const collectionType = draft?.collectionType;
// 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 reloadKey.
// 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;
let timeoutId = 0;
// The deadline ABORTS the request rather than just abandoning the wait: an abandoned GET stays
// in flight, so each Retry would stack another outstanding connection and eventually delay the
// very retry meant to recover (#651 round 7). Cleared on settlement and on unmount.
const controller = new AbortController();
let timedOutFlag = false;
// Two jobs, deliberately BOTH: `abort` cancels the work so retries cannot stack connections,
// and the rejected race stops the UI waiting even if the abort never propagates (a fetch that
// ignores its signal, or one already past the point of cancellation, would otherwise leave the
// editor on a spinner forever — cancellation and giving-up are not the same guarantee).
const timeout = new Promise<never>((_resolve, reject) => {
timeoutId = window.setTimeout(() => {
timedOutFlag = true;
controller.abort(new Error('timeout'));
reject(new Error('Timed out loading rerun collection'));
}, LOAD_TIMEOUT_MS);
});
const timedOut = () => timedOutFlag;
getRerunCollectionWithMeta(initial.id)
Promise.race([getRerunCollectionWithMeta(initial.id, controller.signal), timeout])
.then((meta) => {
if (active) {
etagRef.current = meta.etag;
setDraft(draftFromRerun(meta.data));
if (!active) {
return;
}
// FAIL CLOSED on the absence of a USABLE concurrency token. "The draft is only created
// here, alongside the ETag" is not the same as "a draft implies a token": the header can be
// absent, empty, or whitespace, and each of those ends with `updateRerunCollection` sending
// no `If-Match` at all — a silent force-write. An editor that cannot save safely must not
// exist (#651 rounds 6 and 7).
const token = usableEtag(meta.etag);
if (token === null) {
setLoadError(
'This rerun collection was served without a version tag, so it cannot be edited safely. Reload the page or try again.'
);
return;
}
etagRef.current = token;
setDraft(draftFromRerun(meta.data));
})
.catch((error: unknown) => {
if (active) {
setSaveError(messageFromRerunCollectionError(error, 'Unable to load rerun collection'));
if (!active) {
return;
}
setLoadError(
timedOut()
? 'Timed out loading this rerun collection.'
: messageFromRerunCollectionError(error, 'Unable to load rerun collection')
);
})
.finally(() => {
window.clearTimeout(timeoutId);
});
return () => {
active = false;
window.clearTimeout(timeoutId);
// Cancel the in-flight read on unmount/reload so a superseded request cannot outlive it.
controller.abort(new Error('superseded'));
};
}, [initial, reloadKey]);
}, [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)
.then(({ hint, items, totalCount }) => {
.then(({ hint, items }) => {
if (!controller.signal.aborted) {
setPickerItems(items);
setPickerFor({ items, type: collectionType });
setPickerError(null);
setPickerHint(hint);
setPickerTotalCount(totalCount);
}
})
.catch((error: unknown) => {
if (!controller.signal.aborted) {
setPickerItems([]);
setPickerFor({ items: [], type: collectionType });
setPickerError(messageFromRerunCollectionError(error, 'Unable to load picker items'));
setPickerHint('none');
setPickerTotalCount(null);
}
});
@@ -336,24 +426,84 @@ function RerunCollectionEditor({
};
}, [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;
// Stable across renders: `SearchPicker`'s debounce effect lists `search` in its deps, so a fresh
// closure every render would restart the debounce on each keystroke's re-render.
const searchLibrary = useCallback(
(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={() => {
setLoadError(null);
setLoadKey((key) => key + 1);
}}
size="sm"
variant="secondary"
>
Retry
</Button>
<Button onClick={onBack} size="sm" variant="ghost">
All rerun collections
</Button>
</div>
);
}
if (!draft) {
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
{/* A way out while loading: a hung request must never be a dead end (#651 round 6). */}
<Button onClick={onBack} size="sm" startIcon={<ArrowLeft aria-hidden="true" size={14} />} variant="ghost">
All rerun collections
</Button>
</div>
<div className="ctv-collections-loading" role="status">
<Spinner size={18} />
<span>Loading rerun collection…</span>
</div>
</div>
);
}
const patch = (delta: Partial<Draft>) => setDraft((current) => (current ? { ...current, ...delta } : current));
const setCollectionType = (type: RerunCollectionType) => {
setDraft((current) => ({
...current,
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, selectedId: id, selectedName: match?.name ?? current.selectedName }));
setDraft((current) =>
current ? { ...current, selectedId: id, selectedName: match?.name ?? current.selectedName } : current
);
};
const activeConfig = COLLECTION_TYPES.find((entry) => entry.value === collectionType);
// 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;
@@ -397,7 +547,11 @@ function RerunCollectionEditor({
const reloadAfterConflict = () => {
setConflictOpen(false);
setSaveError(null);
setReloadKey((key) => key + 1);
// 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
@@ -411,8 +565,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">
@@ -440,7 +594,7 @@ function RerunCollectionEditor({
<Card title="Rerun collection">
<Input
label="Name"
onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
onChange={(event) => patch({ name: event.target.value })}
placeholder="Rerun collection name"
value={draft.name}
/>
@@ -455,24 +609,44 @@ function RerunCollectionEditor({
</div>
<div style={{ marginTop: 12 }}>
<Select
ariaDescribedBy={pickerError || pickerHint !== 'none' ? pickerHelpId : undefined}
label={activeConfig?.label ?? 'Selection'}
onChange={(event) => setSelected(event.target.value)}
options={pickerOptions}
value={draft.selectedId == null ? '' : String(draft.selectedId)}
/>
{browseMediaType ? (
// #651: the media library is resolved by search, never list-loaded. The current
// selection renders from the DRAFT (`selectedName`, loaded with the record), not from
// the result set — so editing an existing rerun collection shows its real selection
// before, during and after any search, and never silently loses it.
<SearchPicker
ariaDescribedBy={pickerHelpId}
key={draft.collectionType}
label={activeConfig?.label ?? 'Selection'}
minQueryLength={LIBRARY_PICKER_MIN_QUERY}
onClear={() => patch({ selectedId: null, selectedName: '' })}
onSelect={(id, name) => patch({ selectedId: id, selectedName: name })}
placeholder={`Search ${(activeConfig?.label ?? 'items').toLowerCase()}…`}
search={searchLibrary}
source={draft.collectionType}
selectedId={draft.selectedId}
selectedName={draft.selectedName || null}
/>
) : (
<Select
ariaDescribedBy={pickerError || pickerHint !== 'none' ? pickerHelpId : undefined}
label={activeConfig?.label ?? 'Selection'}
onChange={(event) => setSelected(event.target.value)}
options={pickerOptions}
value={draft.selectedId == null ? '' : String(draft.selectedId)}
/>
)}
{pickerError && (
<span className="ctv-field-error" id={pickerHelpId} role="alert">
{pickerError}
</span>
)}
{!pickerError && pickerHint === 'truncated' && (
{!pickerError && browseMediaType && (
<span className="ctv-field-help" id={pickerHelpId}>
Showing the first {pickerItems.length} of {pickerTotalCount} — use search to narrow.
Type at least {LIBRARY_PICKER_MIN_QUERY} characters to search the library.
</span>
)}
{!pickerError && pickerHint === 'incomplete' && (
{!pickerError && !browseMediaType && pickerHint === 'incomplete' && (
<span className="ctv-field-help" id={pickerHelpId}>
List may be incomplete — retry to reload.
</span>
@@ -482,9 +656,7 @@ function RerunCollectionEditor({
<div style={{ marginTop: 12 }}>
<Select
label="First Run Playback Order"
onChange={(event) =>
setDraft((current) => ({ ...current, firstRunPlaybackOrder: event.target.value as PlaybackOrder }))
}
onChange={(event) => patch({ firstRunPlaybackOrder: event.target.value as PlaybackOrder })}
options={firstRunOrderOptions}
value={draft.firstRunPlaybackOrder}
/>
@@ -493,9 +665,7 @@ function RerunCollectionEditor({
<div style={{ marginTop: 12 }}>
<Select
label="Rerun Playback Order"
onChange={(event) =>
setDraft((current) => ({ ...current, rerunPlaybackOrder: event.target.value as PlaybackOrder }))
}
onChange={(event) => patch({ rerunPlaybackOrder: event.target.value as PlaybackOrder })}
options={rerunOrderOptions}
value={draft.rerunPlaybackOrder}
/>
+20 -1
View File
@@ -1612,11 +1612,30 @@ body {
font-size: 13px;
}
.ctv-picker-result:hover,
/* Results for a superseded query: still visible (hiding them flickers on every keystroke) but
plainly not actionable until their replacement lands. `choose` refuses them regardless — this is
the affordance, not the guard. */
.ctv-picker-results-stale {
opacity: 0.5;
}
.ctv-picker-results-stale .ctv-picker-result {
cursor: default;
}
/* `-active` is the keyboard virtual cursor (aria-activedescendant); it deliberately shares the
hover treatment so pointer and keyboard users get the same affordance. */
.ctv-picker-results:not(.ctv-picker-results-stale) .ctv-picker-result:hover,
.ctv-picker-result-active,
.ctv-picker-result[aria-selected='true'] {
background: var(--surface-3, rgba(255, 255, 255, 0.08));
}
.ctv-picker-error {
color: var(--status-error, #f87171);
border-color: currentColor;
}
.ctv-picker-empty {
padding: 8px 10px;
font-size: 12px;