fix(650): close two test-adjacency gaps — hook-level single-flight pin, predicate-level glob pin

Fourth cold cross-family review: no runtime correctness finding this round
(single-flight held against synchronous throws, generation overlap,
StrictMode, unmount, and separate hook instances). Two test-gap findings
remained, both the same shape as prior rounds' review feedback: asserting on
something ADJACENT to the mechanism rather than the mechanism itself.

1. ChannelBuilder.test.tsx's page-0 single-flight test asserted on the
   disabled BUTTON — during a page-0 refresh, `loadingMore` disables the
   native button, so `fireEvent.click` never reaches `loadMore` at all.
   Deleting `busyRef.current = true` at libraryBrowse.ts's generation-change
   effect would leave that test green while direct hook calls could still
   overlap page 0 and page 1. Added a hook-level test that calls
   `result.current.loadMore()` directly (via `renderHook`, bypassing the
   button/DOM layer) while a gated page-0 fetch is in flight, and asserts no
   page-1 request is ever issued. Verified: removing `busyRef.current = true`
   at that line makes the new test fail with
   `expected [ +0, 1 ] to deeply equal [ +0 ]` (a page-1 request was issued
   when the guard should have ignored the direct call); restored, green
   again.

2. pageSizeScan.test.ts's `.mts`/`.cts` tests exercised the SCANNER'S
   PARSING, not the guard's file-discovery glob — reverting the glob back to
   `.ts`/`.tsx` left both those tests green (the scanner still parses a
   `.mts`/`.cts` filename as plain TS regardless of extension) AND the
   real-source guard green (this repo has no committed `.mts`/`.cts` file
   for the reverted glob to miss). A prior verification planted a real
   `.mts` file and watched the guard notice it, which proved the behavior
   exists today but pinned nothing going forward. Extracted the inline glob
   condition into a standalone, exported `isScannableSourceFileName`
   predicate and added 14 parametrized cases asserting it BY FILENAME (no
   filesystem involved) — `.ts`/`.tsx`/`.mts`/`.cts` accepted, their
   `.test.*` and `.guard.test.ts` variants excluded, non-TS extensions
   rejected. Verified: reverting the predicate's regex back to `.ts`/`.tsx`
   only makes 2 of the 14 cases fail (`isScannableSourceFileName('*.mts')`
   and `'*.cts'` both wrongly return `false`); restored, green again.

Nothing else changed — the reviewer confirmed no further findings (loader
async/throw handling, generation sequencing, the unconditional rollback,
StrictMode/unmount behavior, the disabled-during-refresh UX, type-only node
exclusion, computed-name exactness, wrapped-forwarded-call rejection, and
all existing test labelling were all confirmed correct as-is).

Full local gate: lint clean, tsc clean, full vitest run 110 files / 1078
tests passed, re-run twice for stability (no flakes).
This commit is contained in:
2026-07-27 01:29:15 +02:00
parent 1c86a1c1fc
commit 937ee92a3f
2 changed files with 125 additions and 8 deletions
+47 -8
View File
@@ -268,6 +268,23 @@ const REGISTRY: RegistryEntry[] = [
// This file lives in `src/api/`; the scan root is `src/`.
const SRC_DIR = join(dirname(fileURLToPath(import.meta.url)), '..');
// Extracted from `listSourceFiles`'s inline condition so it's independently testable (#650
// follow-up round 4): a plant that adds a real `.mts` FILE and observes the guard notice it
// proves the behavior exists today, but pins nothing — revert the glob back to `.ts`/`.tsx` and
// both the real-source guard AND `pageSizeScan.test.ts`'s `.mts`/`.cts` PARSING tests stay green,
// because this repo has no committed `.mts`/`.cts` source and `scanPageSizeSites` parses any
// non-`.tsx` filename as plain TS regardless of extension. Testing this predicate directly, by
// filename, is what actually regression-pins the file-discovery fix rather than depending on the
// repo happening to contain (or not contain) a matching file.
export function isScannableSourceFileName(name: string): boolean {
// `.mts`/`.cts` are legal TS extensions `tsconfig.app.json`'s `include` covers alongside
// `.ts`/`.tsx` — none exist in this repo today, but the glob must not silently skip one if it
// ever does (#650 follow-up round 3 MEDIUM finding).
return (
/\.(ts|tsx|mts|cts)$/.test(name) && !/\.test\.(tsx?|mts|cts)$/.test(name) && !name.endsWith('.guard.test.ts')
);
}
function listSourceFiles(dir: string): string[] {
const out: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
@@ -279,14 +296,7 @@ function listSourceFiles(dir: string): string[] {
out.push(...listSourceFiles(full));
continue;
}
// `.mts`/`.cts` are legal TS extensions `tsconfig.app.json`'s `include` covers alongside
// `.ts`/`.tsx` — none exist in this repo today, but the glob must not silently skip one if it
// ever does (#650 follow-up round 3 MEDIUM finding).
if (
/\.(ts|tsx|mts|cts)$/.test(entry.name) &&
!/\.test\.(tsx?|mts|cts)$/.test(entry.name) &&
!entry.name.endsWith('.guard.test.ts')
) {
if (isScannableSourceFileName(entry.name)) {
out.push(full);
}
}
@@ -353,6 +363,35 @@ function multisetExcess(left: Map<string, number>, right: Map<string, number>):
// class, verified against the prior scanner where the review asked for it) — these 4 just confirm
// the guard, wired to whichever scanner it currently uses, still holds over real source.
describe('pageSize call-site guard (#650)', () => {
it.each([
['screens/TraktListsScreen.ts', true],
['builder/ChannelBuilder.tsx', true],
['builder/libraryBrowse.mts', true],
['api/pageSizeScan.cts', true],
['screens/TraktListsScreen.test.ts', false],
['builder/ChannelBuilder.test.tsx', false],
['builder/libraryBrowse.test.mts', false],
['api/pageSizeScan.test.cts', false],
['api/pageSizeCallSites.guard.test.ts', false],
['api/generated/v1.ts', true], // the predicate itself is filename-only; the 'generated' DIRECTORY exclusion lives in listSourceFiles, tested separately below.
['components.js', false],
['data.json', false],
['README.md', false],
['noextension', false]
])(
'isScannableSourceFileName(%s) === %s — the file-discovery predicate itself, independent of ' +
'whether the repo happens to contain a matching file (#650 follow-up round 4)',
(name, expected) => {
// A prior verification planted a REAL .mts file and observed the guard notice it — that
// proved the .mts/.cts fix works today, but pinned nothing: reverting the glob back to
// `.ts`/`.tsx` leaves both the real-source guard AND pageSizeScan.test.ts's .mts/.cts
// PARSING tests green, since this repo has no committed .mts/.cts source and the scanner
// parses any non-.tsx filename as plain TS regardless of extension. Asserting on the
// predicate BY FILENAME, with no filesystem involved, is what actually regression-pins it.
expect(isScannableSourceFileName(name)).toBe(expected);
}
);
it('scans a healthy number of source files (anti-vacuity: a broken glob must not pass on zero input)', () => {
const files = listSourceFiles(SRC_DIR);
expect(files.length).toBeGreaterThan(50);
+78
View File
@@ -1252,6 +1252,84 @@ describe('Channel Builder (#89)', () => {
}
);
it(
'single-flight: calling loadMore() directly while a page-0 refresh is still in flight is ' +
'IGNORED — no page-1 request is ever issued (#650 follow-up round 4)',
async () => {
// ChannelBuilder.test.tsx's component-level single-flight test asserts on the DISABLED
// BUTTON — during a page-0 refresh, `loadingMore` disables the native button, so
// `fireEvent.click` never even reaches `loadMore`. That test would stay green if the
// generation-change effect's `busyRef.current = true` (libraryBrowse.ts) were deleted,
// because the presentation layer's own disabling would still mask the missing guard. This
// test drives `loadMore()` directly via `renderHook`, bypassing the button entirely, so it
// exercises the HOOK's own guard rather than something adjacent to it.
const pageA0 = [browseItem({ id: 1, mediaItemId: 1, mediaType: 'TelevisionShow', title: 'Item A' })];
const pageB0 = [browseItem({ id: 2, mediaItemId: 2, mediaType: 'TelevisionShow', title: 'Item B0' })];
const pageB1 = [browseItem({ id: 3, mediaItemId: 3, mediaType: 'TelevisionShow', title: 'Item B1' })];
let releaseB0: (() => void) | null = null;
const gateB0 = new Promise<void>((resolve) => {
releaseB0 = resolve;
});
const televisionShowPageNumsForB: number[] = [];
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
const url = new URL(input.toString(), 'http://localhost');
if (url.pathname !== '/api/v1/library/browse') {
return Promise.resolve(new Response(null, { status: 204 }));
}
const mediaType = url.searchParams.get('mediaType');
if (mediaType !== 'TelevisionShow') {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
const query = url.searchParams.get('query') ?? '';
const pageNum = Number(url.searchParams.get('pageNum') ?? '0');
if (query === '') {
return Promise.resolve(jsonResponse({ page: pageA0, totalCount: 4 }));
}
televisionShowPageNumsForB.push(pageNum);
if (pageNum === 0) {
return gateB0.then(() => jsonResponse({ page: pageB0, totalCount: 4 }));
}
return Promise.resolve(jsonResponse({ page: pageB1, totalCount: 4 }));
});
const { result, rerender } = renderHook(({ query }) => useLibraryBrowse('library', query, null), {
initialProps: { query: '' }
});
await waitFor(() => expect(result.current.state.status).toBe('success'));
expect(result.current.state.items.map((item) => item.title)).toEqual(['Item A']);
// Change the query — the generation-change effect fires immediately (no debounce at the
// hook level; that's a ChannelBuilderScreen-only concern) and issues B/page-0, held open by
// gateB0.
rerender({ query: 'B' });
await waitFor(() => expect(televisionShowPageNumsForB).toEqual([0]));
// Call loadMore() DIRECTLY while B/page-0 is still in flight — single-flight must ignore
// this outright, not queue a page-1 request behind it.
act(() => {
result.current.loadMore();
});
expect(televisionShowPageNumsForB).toEqual([0]);
// Let B/page-0 resolve; still no page-1 request should have appeared (the ignored call
// above must not have been queued for later, either).
releaseB0?.();
await waitFor(() => expect(result.current.state.items.map((item) => item.title)).toContain('Item B0'));
expect(televisionShowPageNumsForB).toEqual([0]);
// Now that the single-flight slot is free, a genuine call correctly fetches page 1.
act(() => {
result.current.loadMore();
});
await waitFor(() => expect(result.current.state.items.map((item) => item.title)).toContain('Item B1'));
expect(televisionShowPageNumsForB).toEqual([0, 1]);
}
);
it(
'a failed "Load more" page is retried as the SAME page number, not skipped or duplicated ' +
'(#650 follow-up round 3)',