fix(685): test the helper's bound; delete the masking duplicate gate

Independent review round 2 returned BLOCKED on two findings, both correct.

- The helper's bound was dead code to the suite. searchLibraryBrowseItems had
  zero tests, so deleting its clamp OR its gate left the whole suite green —
  while the registry note claimed a caller "cannot skip the bound". That is the
  previous round's finding relocated, not removed. It now has the three tests
  its sibling searchLibraryPickerOptions already had (clamp, gate, compile),
  plus one pinning the full-row return that is its reason to exist.

- The screen kept a second copy of the min-query check, and the two masked each
  other: the 1-character boundary test passed with EITHER gate alone, so it
  pinned nothing. The screen's copy is deleted; the helper is the sole gate.
  Measured before/after: with the duplicate present, removing the helper's gate
  left that test green; with it gone, the same removal reddens it.

- §3b contradicted itself two lines apart — the parent still said "there is no
  truncation, so there is no truncation hint" above a sub-bullet mandating one.
  Reworded so a hint is permitted, required only where bulk selection makes the
  count actionable. Same correction to the 'search-bounded' definition.

- A failed search left results/totalMatches stale, rendering a confident
  "Showing 75 of 60000 matches" beside the error banner. The catch clears them.

- Results now carry a `Results for "<query>"` heading and the guidance is keyed
  to the settled query, not the live input, so rows are never shown without
  saying which search produced them. `selected` persists across queries (correct
  for a multi-select picker); the Add button's count keeps it discoverable.

- The hint sums pre-filter totalCount against post-filter rows, which is only
  correct because every filterable kind is addable. MediaKindFilter is now
  derived from ADDABLE_TYPE_LIST, making that a compile error rather than prose.

- aria-live on the hint; the #740 doc caveat no longer overstates the typeahead
  rule as a mandate this screen violates.

Declined: the NaN pageSize edge (copied faithfully from the sibling helper) and
the registry's same-identity substitution gap (already disclosed in that file).

refs #740
This commit is contained in:
2026-08-05 19:08:13 +02:00
parent 4be3f247d8
commit b6bf94f129
5 changed files with 226 additions and 49 deletions
+13 -6
View File
@@ -178,10 +178,14 @@ the #644 follow-up got Class A right and Class B only half right):
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.
characters. Selecting a media-library type must issue **zero** requests. The per-kind
`LIBRARY_PICKER_RESULTS` cap is the only truncation this class has — there is no whole-type window
left to hint at, so the old `Showing the first 100 of 5000 — use search to narrow.` copy is gone
from these pickers along with the window it described. Surfacing the per-kind cap is *permitted*
wherever it is reachable, and *required* only where bulk selection makes the count actionable — see
the `AddItemsDialog` sub-bullet below, which sums the cap across kinds and renders a `Showing N of
M matches` hint for exactly that reason. Prove the bound with a **request-count assertion against a
large (20k-row) fixture**, not by inspection.
- **`SearchPicker` is the single-select SHAPE, not the rule itself.** A MULTI-select picker
(`CollectionsScreen`'s `AddItemsDialog` — checkbox rows, many items added at once, fanned out
@@ -200,8 +204,11 @@ the #644 follow-up got Class A right and Class B only half right):
click), and #685's first fix duplicated the check at one of them, which measurably tested
nothing — deleting the duplicate reddened no test, while deleting the sink's gate reddened both
paths. **Outstanding on this screen**: `AddItemsDialog` still lacks the monotonic `seqRef`
stale-response guard and `useIsMountedRef()` this section mandates elsewhere (see "Debounced
typeaheads" below) — tracked in **ersatztv#740**, not yet fixed here.
stale-response guard and `useIsMountedRef()` — the same class of guard "Debounced typeaheads"
below mandates there, applied to a debounced-while-typing fetch; `AddItemsDialog` is an explicit
Search-button submission, not a typeahead, so that mandate doesn't reach it directly, but the
same race (a superseded search settling after a newer one) can still occur here — tracked in
**ersatztv#740**, not yet fixed here.
- **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
+51
View File
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
getLibraryBrowseItems,
searchLibraryBrowseItems,
searchLibraryPickerOptions,
titleContainsQuery,
LIBRARY_PICKER_LUCENE_SPECIALS,
@@ -150,3 +151,53 @@ describe('searchLibraryPickerOptions (#651)', () => {
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe('searchLibraryBrowseItems (#685 — AddItemsDialog sibling of searchLibraryPickerOptions)', () => {
afterEach(() => {
vi.restoreAllMocks();
});
// The reviewer proved this helper was dead code to the suite: deleting its clamp, or deleting
// its gate, both left the whole suite green. These three tests mirror the ones above for
// searchLibraryPickerOptions so the same bound is pinned for the sibling helper.
it('#651 F4: CLAMPS an oversized pageSize rather than forwarding it', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 20000 }));
await searchLibraryBrowseItems('Episode', 'Alpha', 5000);
expect(browseUrl(fetchMock).searchParams.get('pageSize')).toBe(String(LIBRARY_PICKER_RESULTS));
});
it('issues NO request for a query below the minimum length, and resolves an empty result', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));
expect(await searchLibraryBrowseItems('Episode', 'a')).toEqual({ items: [], totalCount: 0 });
expect(await searchLibraryBrowseItems('Episode', ' ')).toEqual({ items: [], totalCount: 0 });
expect(fetchMock).not.toHaveBeenCalled();
});
it('compiles/escapes the trimmed query, and returns the FULL row (mediaType present) plus totalCount', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
jsonResponse({
page: [{ id: 1, mediaItemId: 7, mediaType: 'Movie', title: 'Show Alpha' }],
totalCount: 42
})
);
const result = await searchLibraryBrowseItems('Movie', ' Show Alpha ');
expect(fetchMock).toHaveBeenCalledTimes(1);
const url = browseUrl(fetchMock);
expect(url.searchParams.get('query')).toBe(titleContainsQuery('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));
// The reason this helper exists rather than reusing searchLibraryPickerOptions: the full row
// (mediaType included), not the {id, name} shape.
expect(result).toEqual({
items: [{ id: 1, mediaItemId: 7, mediaType: 'Movie', title: 'Show Alpha' }],
totalCount: 42
});
});
});
+22 -15
View File
@@ -83,12 +83,15 @@ import { scanPageSizeSites } from './pageSizeScan';
* mechanism, and the row bound is a property of the CODE rather than of a
* caller's discipline (a clamp inside the shared helper for #651's
* library picker; a fixed small constant at the inline preview sites).
* Nothing is list-loaded, so there is no truncation to surface and the
* absence of a truncation hint is correct — which is why such a site
* cannot be filed under 'class-b', whose defining evidence IS a surfaced
* `totalCount`. Applies only where the query is genuinely required: a
* site that degrades to an unfiltered browse when the query is empty is
* NOT search-bounded (see 'deviation').
* Nothing is list-loaded, so a truncation hint is not REQUIRED here — but,
* unlike 'class-b', it is not the defining evidence either: a search-bounded
* site MAY surface its own per-kind cap (e.g. summed across kinds) once that
* count is actionable, without that hint reclassifying it as 'class-b'. What
* distinguishes the two classes is the SHAPE of the bound (one clamped
* search request per settled query vs. one bounded page of a list), not
* whether a hint is rendered. Applies only where the query is genuinely
* required: a site that degrades to an unfiltered browse when the query is
* empty is NOT search-bounded (see 'deviation').
* - 'class-b' — one bounded page at (or under) the cap, with the real truncation
* (`totalCount` vs items shown) surfaced to the user. Post-#651 this no
* longer covers media-library pickers (those are 'search-bounded').
@@ -175,15 +178,19 @@ const REGISTRY: RegistryEntry[] = [
'full LibraryBrowseItem rows plus totalCount cannot skip the bound either. A deliberate ' +
'second occurrence of the same (file, kind, value) identity — the multiset comparison ' +
'requires it be discovered twice. No request is issued below LIBRARY_PICKER_MIN_QUERY (a ' +
'blank form submit and a kind-chip click below the gate both issue zero requests, and ' +
'AddItemsDialog clears results instead), the typed text is compiled via titleContainsQuery ' +
'rather than forwarded raw, and each kind is bounded to one request per settled query at ' +
'LIBRARY_PICKER_RESULTS rows. Unlike the #685 first fix, this is NOT "nothing left to hint ' +
'at": the per-kind cap can still truncate the real match count below what totalCount reports, ' +
"and AddItemsDialog now sums each kind's totalCount and renders a 'Showing N of M' hint when " +
"it exceeds the rendered rows. The only remaining client-side filter in AddItemsDialog " +
"(ADDABLE_TYPES.has(item.mediaType)) is inert, not a silent drop — every mediaType " +
'AddItemsDialog requests is already in ADDABLE_TYPE_LIST.'
'blank form submit and a kind-chip click below the gate both resolve every kind to ' +
'{items: [], totalCount: 0} via the HELPER\'s own gate — CollectionsScreen no longer keeps a ' +
'second copy of this check; the #685 second review proved the two masked each other), the ' +
'typed text is compiled via titleContainsQuery rather than forwarded raw, and each kind is ' +
'bounded to one request per settled query at LIBRARY_PICKER_RESULTS rows. Unlike the #685 ' +
'first fix, this is NOT "nothing left to hint at": the per-kind cap can still truncate the ' +
"real match count below what totalCount reports, and AddItemsDialog now sums each kind's " +
"totalCount and renders a 'Showing N of M' hint when it exceeds the rendered rows. The only " +
'remaining client-side filter in AddItemsDialog (ADDABLE_TYPES.has(item.mediaType)) is inert, ' +
'not a silent drop, and this is now enforced by the type system rather than by convention: ' +
"MediaKindFilter is derived from ADDABLE_TYPE_LIST (`(typeof ADDABLE_TYPE_LIST)[number]`), so " +
'adding a non-addable kind to MEDIA_KIND_FILTERS is a compile error, not a silently-possible ' +
'mismatch.'
},
{
file: 'api/paging.ts',
@@ -551,6 +551,98 @@ describe('CollectionsScreen', () => {
expect(within(dialog).queryByText(/Showing .* of .* matches/)).not.toBeInTheDocument();
});
it(
'labels the results with the query that produced them, and clearing without re-submitting keeps rows + label (#685 review)',
async () => {
mockAddItemsApi();
const dialog = await openAddItemsDialog();
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'za' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
expect(await within(dialog).findByText('Zathura')).toBeInTheDocument();
expect(
within(dialog).getByText(
(_content, element) => element?.tagName === 'P' && element.textContent === 'Results for “za”'
)
).toBeInTheDocument();
// Clear the input WITHOUT re-submitting: the rows and their label must still describe the
// original ("za") search — nothing says which query produced an on-screen row otherwise.
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: '' }
});
expect(within(dialog).getByText('Zathura')).toBeInTheDocument();
expect(
within(dialog).getByText(
(_content, element) => element?.tagName === 'P' && element.textContent === 'Results for “za”'
)
).toBeInTheDocument();
}
);
it(
'clearing the input and re-submitting shows the min-query guidance while the selection stays discoverable (#685 review)',
async () => {
mockAddItemsApi();
const dialog = await openAddItemsDialog();
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'za' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
expect(await within(dialog).findByText('Zathura')).toBeInTheDocument();
fireEvent.click(within(dialog).getByText('Zathura'));
expect(within(dialog).getByRole('button', { name: /Add 1 item/ })).toBeInTheDocument();
// Clear the input and re-submit: the helper's gate resolves every kind to
// { items: [], totalCount: 0 }, so the (now query-less) results are empty.
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: '' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
await waitFor(() => {
expect(
within(dialog).getByText(`Type at least ${LIBRARY_PICKER_MIN_QUERY} characters to search.`)
).toBeInTheDocument();
});
// `selected` persists across queries (correct for a multi-select picker) — it must never be
// invisible-but-counted, and the Add button's count is where that stays discoverable even
// though the previously-ticked row isn't in the (now empty) result set.
expect(within(dialog).getByRole('button', { name: /Add 1 item/ })).toBeInTheDocument();
// And the "Results for" heading is gone, not showing a stale/misleading query.
expect(within(dialog).queryByText(/^Results for /)).not.toBeInTheDocument();
}
);
it('clears the truncation hint on a failed search (#685 review)', async () => {
const fetchMock = mockApi({
onRequest: (url) => {
if (url.startsWith('/api/v1/library/browse')) {
return jsonResponse({ page: [], totalCount: 0 }, 500);
}
return null;
}
});
const dialog = await openAddItemsDialog();
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'za' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
await waitFor(() => {
expect(within(dialog).getByRole('alert')).toBeInTheDocument();
});
expect(within(dialog).queryByText(/Showing .* of .* matches/)).not.toBeInTheDocument();
expect(fetchMock).toHaveBeenCalled();
});
/* ---------- add-items search bounds (#685) ---------- */
function buildLibraryFixture(mediaType: string, count: number): { id: number; mediaItemId: number; mediaType: string; title: string }[] {
+48 -28
View File
@@ -53,8 +53,13 @@ import { SmartCollectionDialog } from '../builder/SmartCollectionDialog';
type Tab = 'manual' | 'smart';
// Every kind that can be added to a manual collection from the picker.
const ADDABLE_TYPE_LIST: LibraryBrowseItem['mediaType'][] = [
// Every kind that can be added to a manual collection from the picker. `as const satisfies`
// keeps this a literal-string tuple (rather than widening to the whole `mediaType` union) while
// still checking each entry against it, so `MediaKindFilter` below can be DERIVED from this list:
// adding a non-addable kind to `MEDIA_KIND_FILTERS` becomes a compile error instead of a
// convention nothing enforces (#685 review — the sum-of-totalCount hint is only correct because
// every filterable kind is addable, and this makes that structural rather than a comment).
const ADDABLE_TYPE_LIST = [
'Movie',
'TelevisionShow',
'TelevisionSeason',
@@ -65,7 +70,7 @@ const ADDABLE_TYPE_LIST: LibraryBrowseItem['mediaType'][] = [
'OtherVideo',
'Image',
'RemoteStream'
];
] as const satisfies readonly LibraryBrowseItem['mediaType'][];
const ADDABLE_TYPES = new Set<LibraryBrowseItem['mediaType']>(ADDABLE_TYPE_LIST);
// The default fan-out excludes seasons so a multi-season show doesn't flood the
@@ -73,7 +78,7 @@ const ADDABLE_TYPES = new Set<LibraryBrowseItem['mediaType']>(ADDABLE_TYPE_LIST)
// added for #211) stay reachable via the explicit media-kind filter below.
const DEFAULT_SEARCH_KINDS: LibraryBrowseItem['mediaType'][] = ['Movie', 'TelevisionShow', 'Artist'];
type MediaKindFilter = 'all' | LibraryBrowseItem['mediaType'];
type MediaKindFilter = 'all' | (typeof ADDABLE_TYPE_LIST)[number];
const MEDIA_KIND_FILTERS: { label: string; value: MediaKindFilter }[] = [
{ label: 'All', value: 'all' },
@@ -219,30 +224,26 @@ function AddItemsDialog({
const [query, setQuery] = useState('');
const [results, setResults] = useState<LibraryBrowseItem[]>([]);
const [totalMatches, setTotalMatches] = useState(0);
// The query a *settled* search actually ran for — never the live input. Rendered as a heading
// over the results so a submitted-then-cleared input, or a selection made under an earlier
// query, is never shown without saying which query produced it (#685 review). Reset to '' when
// a search settles below LIBRARY_PICKER_MIN_QUERY (nothing was actually searched) or errors.
const [submittedQuery, setSubmittedQuery] = useState('');
const [searching, setSearching] = useState(false);
const [selected, setSelected] = useState<Map<string, LibraryBrowseItem>>(() => new Map());
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [kindFilter, setKindFilter] = useState<MediaKindFilter>('all');
// Below LIBRARY_PICKER_MIN_QUERY, this issues NOTHING: a blank/short form submit and a
// kind-chip click (see selectKindFilter) both route through here, and #685 was exactly this
// gate missing — an empty query degraded into an unfiltered browse of the whole
// media-library type, per kind, with no truncation indicator. The gate itself — along with the
// pageSize clamp and the raw-Lucene-vs-compiled-query choice — now lives in
// `searchLibraryBrowseItems` (§3b: "the bound belongs to the helper, not the caller"), so this is
// the only early return left here, kept to avoid flipping the searching spinner for a sub-gate
// query rather than to re-implement the gate.
// `searchLibraryBrowseItems` owns the min-query gate, the pageSize clamp, and the
// raw-Lucene-vs-compiled-query choice (§3b: "the bound belongs to the helper, not the caller").
// This screen used to keep a SECOND copy of the min-query check here — the #685 review proved
// the two masked each other (deleting either one left the whole suite green, so the boundary
// test pinned nothing) — so there is now exactly one gate, in the helper, and every caller
// (blank form submit, kind-chip click) routes through it unconditionally.
const runSearch = async (filter: MediaKindFilter = kindFilter) => {
const trimmed = query.trim();
if (trimmed.length < LIBRARY_PICKER_MIN_QUERY) {
setResults([]);
setTotalMatches(0);
setError(null);
return;
}
setSearching(true);
setError(null);
@@ -259,8 +260,18 @@ function AddItemsDialog({
// below via totalMatches (#685 review finding 4).
setResults(merged);
setTotalMatches(perKind.reduce((sum, result) => sum + result.totalCount, 0));
// Below LIBRARY_PICKER_MIN_QUERY, the helper's own gate resolves every kind to
// { items: [], totalCount: 0 } without issuing a request — so `merged`/`totalMatches` above
// are already empty in that case, but `submittedQuery` must say "nothing was actually
// searched" rather than name the sub-gate text.
setSubmittedQuery(trimmed.length < LIBRARY_PICKER_MIN_QUERY ? '' : trimmed);
} catch (searchError) {
setError(messageFromCollectionError(searchError, 'Unable to search library'));
// A failed search must not leave a stale results/totalMatches pair rendering a confident
// "Showing N of M matches" hint beside the error banner (#685 review).
setResults([]);
setTotalMatches(0);
setSubmittedQuery('');
} finally {
setSearching(false);
}
@@ -268,9 +279,8 @@ function AddItemsDialog({
// A kind-chip click is the second path into runSearch (a blank form submit is the other), and it
// is deliberately NOT gated here: runSearch is the single sink and owns the min-query gate for
// every caller. A duplicate check at this one call site was verified non-load-bearing (removing
// it changed no test), and §3b is explicit that an unreachable guard is an untested one — the
// next path added would be the one nobody remembers to gate.
// every caller via searchLibraryBrowseItems. §3b is explicit that an unreachable guard is an
// untested one — the next path added would be the one nobody remembers to gate.
const selectKindFilter = (filter: MediaKindFilter) => {
setKindFilter(filter);
void runSearch(filter);
@@ -372,17 +382,27 @@ function AddItemsDialog({
{error}
</span>
)}
{totalMatches > results.length && (
{submittedQuery !== '' && (
// Names the query the CURRENT results (or the empty-results/"no matches" state) belong
// to — never the live input, so a submitted-then-cleared query, or a selection made under
// an earlier query, is never shown without saying which search produced it (#685 review).
<p className="ctv-collections-picker-note">
Results for &ldquo;{submittedQuery}&rdquo;
</p>
)}
{totalMatches > results.length && (
<p aria-live="polite" className="ctv-collections-picker-note">
Showing {results.length} of {totalMatches} matches — narrow your search.
</p>
)}
<div className="ctv-collections-picker-results">
{results.length === 0 && query.trim().length < LIBRARY_PICKER_MIN_QUERY ? (
// Keyed to results.length, not just the live input: without it, backspacing the query
// back below the min-query length after a successful search wiped the rendered rows AND
// their checkmarks while `selected` (and the Add button's count) still held them
// (#685 review finding 1).
{results.length === 0 && submittedQuery === '' ? (
// Keyed to submittedQuery, not the live input: without it, backspacing the query back
// below the min-query length after a successful search wiped the rendered rows AND their
// checkmarks while `selected` (and the Add button's count) still held them (#685 review
// finding 1) — and, separately, submitting a blank/cleared query after a real selection
// must still say the selection persists rather than rendering as if nothing was ever
// searched (#685 second review).
<div className="ctv-collections-picker-empty">
Type at least {LIBRARY_PICKER_MIN_QUERY} characters to search.
</div>