Second cold cross-family (Codex, BLOCKED) re-review of b90f8a3b found the
regex/bracket-tracking guard scanner still defeated in five ways, and two new
High-severity races introduced by the F3/F4 fixes. Addressed as a further
follow-up (b90f8a3b left untouched).
GUARD REWRITE (per the review's explicit direction — stop patching the regex,
use the compiler):
- New `web/src/api/pageSizeScan.ts`: `scanPageSizeSites` parses each file with
`ts.createSourceFile` and walks the real AST for `pageSize`
PropertyAssignment/ShorthandPropertyAssignment nodes inside an
ObjectLiteralExpression. This eliminates categorically (not case-by-case):
- M-3: comments and string/template CONTENTS are never revisited as code,
so a `'https://...'` string can't be misread as an unterminated string
that swallows the rest of the file.
- M-4: an object literal nested in a ternary, `??`, or JSX expression
container is still found — the walk visits every descendant node
regardless of the syntactic context above the ObjectLiteralExpression.
- M-5: template-literal interpolations are real AST children, not opaque
text.
- L-7: a type literal (`type P = { pageSize: 100 }`), an interface
PropertySignature, and a destructuring ObjectBindingPattern (parameter
or nested) are structurally different node kinds from
ObjectLiteralExpression — excluded by kind, not by a
preceding-character heuristic a stray `{`/`(`/`,` could fool.
`getLineAndCharacterOfPosition` gives exact line+column (fixes M-6 identity
granularity) instead of the prior line-only identity.
- `pageSizeCallSites.guard.test.ts` now imports the shared scanner; identity
is `file:line:column:kind:value`, compared as a MULTISET (count, not
membership) in both directions.
- Both directions (unregistered / stale) are computed and folded into ONE
thrown Error so a failure always shows the complete picture in one run,
addressing the line-churn "second direction never renders" concern.
- New `pageSizeScan.test.ts`: a FIXTURE test (inline source strings, no repo
scan) pinning the exact discovered set for every case the review named —
comment-in-string, string containing the literal text `pageSize: 100`,
template interpolation, ternary, `??`, JSX container, same-line duplicates,
parameter/nested destructuring, a type literal, an interface property, a
forwarded call expression, a React dependency array. This is what actually
protects the scanner going forward — the guard test alone only ever proved
today's snapshot of real call sites, never the scanner's handling of input
classes it hadn't happened to encounter yet.
- Re-verified both original plants (a duplicate at-cap call in an
already-registered file, and a new file with both a literal and a
shorthand site) against the rewritten scanner; both still fail with the
new combined-direction message. Also verified a run with BOTH directions
simultaneously non-empty renders both in one report.
HIGH-1 (ChannelBuilder.tsx useLibraryBrowse, now web/src/builder/libraryBrowse.ts):
`reqId` identifies a query GENERATION, not an individual fetch — a page-0
refresh and a "Load more" append can be outstanding simultaneously under the
same reqId (query changes while an append is in flight for the new
generation). Whichever settled first used to clear `loadingMore`, letting a
second click fire an out-of-order/duplicate page fetch. Fixed with a
per-fetch `fetchId` plus a `loadingFetchIdRef`/`loadingFetchReqIdRef` pair:
only the fetch that OWNS the currently-displayed spinner can clear it; a
same-generation page-0 refresh leaves a same-generation append's spinner
alone, while a page-0 refresh for a NEW generation still retires an
abandoned OLDER-generation append's spinner (preserving the original #650 F3
fix). Reproduced the exact interleaving from the review in a new test
(gate B's page-0 and page-1 fetches independently, click "Load more" while
B's page-0 is still in flight) and confirmed it fails without the fix
(button re-enables while the append is still pending).
HIGH-2 (same file): the append-failure rollback mutated whatever
`pageRef.current` currently held, rather than the specific page THIS fetch
requested — under an overlapping-append race, a later page's success
followed by an earlier page's failure could roll the cursor back past
already-appended progress, corrupting a retry into refetching a duplicate.
Fixed with a compare-and-set guard (`if (pageRef.current === pageNum)`) so
the rollback only fires when nothing has advanced the cursor since. Since
this overlap is UI-unreachable once HIGH-1's single-flight disabling is
wired up (verified empirically: two synchronous fireEvent.click calls in RTL
only produce one request, since act() flushes the disabling render between
them), the regression test drives `useLibraryBrowse` directly via
`renderHook` (now exported) to force the exact interleaving and confirms it
fails without the fix (page 2 gets duplicated, page 3 never requested).
Extracted `useLibraryBrowse` (plus `loadCollections`/`loadLibraryItems`/
`BrowseState`/the media-type const arrays) into a new non-JSX module
`web/src/builder/libraryBrowse.ts` — exporting a hook from a .tsx file
tripped `react-refresh/only-export-components`; this also makes the hook
importable by `renderHook` without pulling in the whole screen component.
No server-side/C# change. Full local gate: lint clean, tsc clean, full
vitest run 110 files / 1051 tests passed (one LibrariesScreen.test.tsx
flake reproduced under full-suite parallel load, confirmed pre-existing and
unrelated — passes in isolation, never touched that file).
231 lines
12 KiB
TypeScript
231 lines
12 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
import { getLibraryBrowseItems, messageFromError, type LibraryBrowseItem, type LibraryBrowseMediaType } from '../api';
|
|
|
|
// Extracted from ChannelBuilder.tsx into its own non-JSX module (#650 follow-up) so
|
|
// `useLibraryBrowse` — a plain hook, no component — can be exported without tripping
|
|
// `react-refresh/only-export-components` (that lint rule wants a file that exports React
|
|
// Fast-Refresh components to export ONLY components). It also lets `ChannelBuilder.test.tsx`
|
|
// unit-test the hook's fetch-ownership/rollback guards directly via `renderHook` — the HIGH-2
|
|
// interleaving (two same-generation appends genuinely overlapping) is not reachable through the
|
|
// rendered "Load more" button once HIGH-1's single-flight disabling is wired up, so the
|
|
// regression test drives the hook directly rather than asserting something the UI can no longer
|
|
// produce.
|
|
|
|
export const COLLECTION_MEDIA_TYPES: LibraryBrowseMediaType[] = [
|
|
'Collection',
|
|
'SmartCollection',
|
|
'MultiCollection',
|
|
'RerunCollection',
|
|
'Playlist'
|
|
];
|
|
|
|
// Browsing a library shows the "pickable" top-level kinds only, not every
|
|
// episode/song/etc. nested underneath them. Kept explicit here since
|
|
// `GET /api/v1/library/browse` now spans all 10 media kinds when `mediaType` is
|
|
// omitted. TelevisionSeason is intentionally excluded so a multi-season show
|
|
// renders as a single tile instead of flooding the grid with per-season tiles
|
|
// (issue #180); seasons are reachable via the show tile's Seasons drill-in.
|
|
export const LIBRARY_MEDIA_TYPES: LibraryBrowseMediaType[] = ['Movie', 'TelevisionShow', 'Artist'];
|
|
|
|
// ---- Library browse data hook ---------------------------------------------
|
|
export interface BrowseState {
|
|
status: 'loading' | 'error' | 'success';
|
|
items: LibraryBrowseItem[];
|
|
totalCount: number;
|
|
error: string | null;
|
|
}
|
|
|
|
// Fan out across the "pickable" collection-ish kinds (Collection, SmartCollection,
|
|
// MultiCollection, RerunCollection, Playlist). Reports the REAL summed per-kind `totalCount`
|
|
// (not `merged.length`, i.e. the truncated page) — #650: returning the page length as the total
|
|
// made `canLoadMore`'s `items.length < totalCount` comparison permanently `merged.length >=
|
|
// merged.length`, so "load more" could never fire once any one kind hit the 100-row server cap.
|
|
// Mirrors loadLibraryItems's per-kind pageNum/totalCount pattern below.
|
|
async function loadCollections(
|
|
query: string,
|
|
pageNum: number,
|
|
pageSize: number
|
|
): Promise<{ page: LibraryBrowseItem[]; totalCount: number }> {
|
|
const results = await Promise.all(
|
|
COLLECTION_MEDIA_TYPES.map((mediaType) => getLibraryBrowseItems({ query, mediaType, pageNum, pageSize }))
|
|
);
|
|
const merged = results
|
|
.flatMap((result) => result.page)
|
|
.sort((left, right) => left.title.localeCompare(right.title, undefined, { sensitivity: 'base' }));
|
|
const totalCount = results.reduce((sum, result) => sum + result.totalCount, 0);
|
|
return { page: merged, totalCount };
|
|
}
|
|
|
|
// Fan out across the pickable top-level library kinds (movies/shows/artists)
|
|
// instead of the unscoped browse, which now also returns episodes/songs/etc.
|
|
// Mirrors loadCollections's per-kind Promise.all pattern, but preserves real
|
|
// paging (each kind keeps its own pageNum/totalCount, summed across kinds) so
|
|
// canLoadMore stays meaningful for large libraries.
|
|
async function loadLibraryItems(
|
|
query: string,
|
|
libraryId: number | null,
|
|
pageNum: number,
|
|
pageSize: number
|
|
): Promise<{ page: LibraryBrowseItem[]; totalCount: number }> {
|
|
const results = await Promise.all(
|
|
LIBRARY_MEDIA_TYPES.map((mediaType) =>
|
|
getLibraryBrowseItems({
|
|
query: query || undefined,
|
|
libraryId: libraryId ?? undefined,
|
|
mediaType,
|
|
pageNum,
|
|
pageSize
|
|
})
|
|
)
|
|
);
|
|
const merged = results
|
|
.flatMap((result) => result.page)
|
|
.sort((left, right) => left.title.localeCompare(right.title, undefined, { sensitivity: 'base' }));
|
|
const totalCount = results.reduce((sum, result) => sum + result.totalCount, 0);
|
|
return { page: merged, totalCount };
|
|
}
|
|
|
|
export function useLibraryBrowse(source: 'library' | 'collections', query: string, libraryId: number | null) {
|
|
const [state, setState] = useState<BrowseState>({ status: 'loading', items: [], totalCount: 0, error: null });
|
|
const [loadingMore, setLoadingMore] = useState(false);
|
|
// Append-only error, kept separate from `state.error` (#650 follow-up F4): a rejected "load
|
|
// more" must NOT flip `state.status` to 'error' — that branch renders instead of the item grid
|
|
// and would destroy every already-loaded row with no way back. This renders inline next to the
|
|
// (still-present) Load more button so the fetch can simply be retried.
|
|
const [loadMoreError, setLoadMoreError] = useState<string | null>(null);
|
|
// Query GENERATION (bumped on query/library/source change) — invalidates every fetch from an
|
|
// earlier generation, whether it was a page-0 refresh or an append.
|
|
const reqRef = useRef(0);
|
|
const pageRef = useRef(0);
|
|
// #650 follow-up HIGH-1: `reqRef` alone identifies a query GENERATION, not an individual
|
|
// in-flight request — a page-0 refresh and a "Load more" append can be outstanding
|
|
// SIMULTANEOUSLY under the same `reqId` (e.g. the user clicks "Load more" while a query change's
|
|
// fresh page-0 fetch is still resolving). Comparing only `reqRef.current === reqId` in
|
|
// `finally` cannot tell those two fetches apart, so whichever settles FIRST clears
|
|
// `loadingMore` — even if it isn't the append the spinner represents, re-enabling the button
|
|
// while the real append is still in flight and letting a second click fire an out-of-order or
|
|
// duplicate page fetch. Each individual fetch now gets its own monotonic `fetchId`; only the
|
|
// fetch that started the CURRENTLY-DISPLAYED spinner (`loadingFetchIdRef`) may clear it, and
|
|
// `loadingFetchReqIdRef` records which GENERATION that owning fetch belongs to, so a fresh
|
|
// page-0 fetch can tell "this is a same-generation append I must not touch" (HIGH-1) apart from
|
|
// "this is an abandoned append from a query the user already left" (the original #650 F3 —
|
|
// still needs cleaning up once its generation is truly gone, or the spinner strands forever).
|
|
const fetchSeqRef = useRef(0);
|
|
const loadingFetchIdRef = useRef<number | null>(null);
|
|
const loadingFetchReqIdRef = useRef<number | null>(null);
|
|
|
|
const runFetch = useCallback(
|
|
(pageNum: number, reqId: number, append: boolean) => {
|
|
const fetchId = ++fetchSeqRef.current;
|
|
if (append) {
|
|
loadingFetchIdRef.current = fetchId;
|
|
loadingFetchReqIdRef.current = reqId;
|
|
}
|
|
|
|
const promise =
|
|
source === 'collections'
|
|
? loadCollections(query, pageNum, 100)
|
|
: loadLibraryItems(query, libraryId, pageNum, 100);
|
|
|
|
promise
|
|
.then((result) => {
|
|
if (reqRef.current !== reqId) {
|
|
return;
|
|
}
|
|
// Clear unconditionally (not just when THIS request was itself an append): a fresh
|
|
// (non-append) fetch that supersedes an in-flight append must also clear any stale
|
|
// append error left over from a previous failed "Load more" (#650 follow-up F3/F4).
|
|
setLoadMoreError(null);
|
|
setState((prev) => ({
|
|
status: 'success',
|
|
error: null,
|
|
items: append ? [...prev.items, ...result.page] : result.page,
|
|
totalCount: result.totalCount
|
|
}));
|
|
})
|
|
.catch((error: unknown) => {
|
|
if (reqRef.current !== reqId) {
|
|
return;
|
|
}
|
|
if (append) {
|
|
// Preserve already-rendered items/totalCount — only surface the failure inline so
|
|
// "Load more" can be retried, rather than wiping a page's worth of loaded rows on one
|
|
// rejected per-kind request (#650 follow-up F4). Roll the page cursor back so the
|
|
// retry re-requests the SAME failed page — but ONLY if nothing has advanced the
|
|
// cursor since this specific fetch started (#650 follow-up HIGH-2): tying the
|
|
// rollback to whatever `pageRef.current` currently holds, rather than to the `pageNum`
|
|
// THIS fetch actually requested, can under an overlapping-append race decrement a
|
|
// cursor a LATER, already-succeeded page already advanced past — silently losing that
|
|
// later page and refetching it as a duplicate. A compare-and-set guard (only roll
|
|
// back when the cursor is still exactly where this fetch left it) makes the rollback
|
|
// a no-op instead of a corruption when that overlap happens.
|
|
if (pageRef.current === pageNum) {
|
|
pageRef.current = pageNum - 1;
|
|
}
|
|
setLoadMoreError(messageFromError(error));
|
|
} else {
|
|
setState({ status: 'error', items: [], totalCount: 0, error: messageFromError(error) });
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (append) {
|
|
// Only the fetch that OWNS the currently-displayed spinner may clear it (#650
|
|
// follow-up HIGH-1) — evaluated purely on fetch identity, independent of whether this
|
|
// fetch's generation is still current, so an abandoned append still retires its own
|
|
// spinner if nothing else already did (the branch below, from the SUPERSEDING
|
|
// generation's own page-0 fetch, normally beats it to this).
|
|
if (loadingFetchIdRef.current === fetchId) {
|
|
setLoadingMore(false);
|
|
loadingFetchIdRef.current = null;
|
|
loadingFetchReqIdRef.current = null;
|
|
}
|
|
return;
|
|
}
|
|
|
|
// This settling fetch is a page-0 refresh. If it belongs to the CURRENT generation and
|
|
// there is a tracked append spinner from an OLDER, now-abandoned generation, retire it
|
|
// here — that append can never again be "what the user is waiting on" (#650 follow-up
|
|
// F3). A SAME-generation append is left untouched; only its own completion (above) may
|
|
// clear it (#650 follow-up HIGH-1) — that's what stops the button re-enabling while a
|
|
// same-generation append is still genuinely in flight.
|
|
if (
|
|
reqRef.current === reqId &&
|
|
loadingFetchIdRef.current !== null &&
|
|
loadingFetchReqIdRef.current !== null &&
|
|
loadingFetchReqIdRef.current !== reqId
|
|
) {
|
|
setLoadingMore(false);
|
|
loadingFetchIdRef.current = null;
|
|
loadingFetchReqIdRef.current = null;
|
|
}
|
|
});
|
|
},
|
|
[source, query, libraryId]
|
|
);
|
|
|
|
// Refetch when inputs change. Following the guide-hook pattern, setState only
|
|
// runs inside runFetch's async callbacks - the previous results stay visible
|
|
// until the new page resolves (initial 'loading' shows the first-load spinner).
|
|
useEffect(() => {
|
|
const reqId = reqRef.current + 1;
|
|
reqRef.current = reqId;
|
|
pageRef.current = 0;
|
|
runFetch(0, reqId, false);
|
|
}, [runFetch]);
|
|
|
|
const loadMore = useCallback(() => {
|
|
const nextPage = pageRef.current + 1;
|
|
pageRef.current = nextPage;
|
|
setLoadingMore(true);
|
|
setLoadMoreError(null);
|
|
runFetch(nextPage, reqRef.current, true);
|
|
}, [runFetch]);
|
|
|
|
// #650: `totalCount` is now the real summed per-kind total for both sources (loadCollections
|
|
// no longer reports the truncated page length as the total), so this comparison is meaningful
|
|
// for 'collections' too — no need to gate it to 'library' only.
|
|
const canLoadMore = state.status === 'success' && state.items.length < state.totalCount;
|
|
|
|
return { state, loadingMore, loadMore, canLoadMore, loadMoreError };
|
|
}
|