vomebook commited on
Commit
551ecc9
·
1 Parent(s): 685b545

Enforce frontend unused checks and streamline chapter navigation

Browse files
Files changed (43) hide show
  1. config/types/jsconfig.chapter-worker-strict.json +2 -0
  2. config/types/jsconfig.service-worker-strict.json +2 -0
  3. config/types/jsconfig.strict.json +3 -0
  4. scripts/check_strict_inventory.py +11 -6
  5. static/app.js +10 -66
  6. static/reader/core/reader-security.js +0 -1
  7. static/reader/core/reader-source.mjs +2 -2
  8. static/reader/formats/reader-chapter-format.mjs +35 -8
  9. static/reader/pdf/reader-pdf-engine.mjs +6 -7
  10. static/reader/pdf/reader-pdf-range-hints.mjs +3 -3
  11. static/reader/pdf/reader-pdf-renderer.mjs +3 -4
  12. static/reader/search/reader-dom-search.mjs +3 -3
  13. static/reader/search/reader-pdf-book-validate.mjs +2 -1
  14. static/reader/search/reader-pdf-hit-projection.mjs +2 -1
  15. static/reader/ui/reader-speech.mjs +3 -4
  16. static/search/results/virtual/application/controller.js +0 -1
  17. static/search/results/window/domain/page.js +1 -4
  18. tests/gates/test_quality_inventory.py +26 -14
  19. tests/gates/test_static_checks.py +13 -0
  20. tests/gates/test_static_contract.py +3 -2
  21. tests/reader/browser/test_reader_host_history_races.py +8 -3
  22. tests/reader/browser/test_reader_navigation_host.py +6 -6
  23. tests/reader/browser/test_reader_pdf_first_page.py +2 -2
  24. tests/reader/browser/test_reader_refactor.py +1 -1
  25. tests/reader/chapters/test_chapter_format_validation.mjs +92 -0
  26. tests/reader/core/test_reader_warming.js +14 -14
  27. tests/search/baselines/test_sidebar_markup_baseline.mjs +13 -17
  28. tests/search/browser/test_browser.py +8 -8
  29. tests/search/browser/test_download_lifecycle.py +8 -8
  30. tests/search/browser/test_initial_intent_reader_routes.py +10 -10
  31. tests/search/browser/test_paging_recovery.py +9 -9
  32. tests/search/browser/test_position_window.py +1 -1
  33. tests/search/browser/test_prefetch_pipeline.py +5 -4
  34. tests/search/browser/test_scroll_stability.py +7 -3
  35. tests/search/browser/test_search_accessibility_browser.py +14 -13
  36. tests/search/browser/test_search_positions.py +6 -6
  37. tests/search/browser/test_sidebar_keyboard.py +13 -13
  38. tests/search/reader-navigation/test_search_history_races.mjs +6 -5
  39. tests/search/ui/history_quotation_contracts.mjs +12 -12
  40. tests/search/ui/shell_contracts.mjs +3 -3
  41. tests/search/ui/virtual_results_contracts.mjs +2 -1
  42. typings/reader-chapter-format-strict.d.ts +1 -1
  43. typings/reader-pdf-engine-strict.d.ts +2 -2
config/types/jsconfig.chapter-worker-strict.json CHANGED
@@ -9,6 +9,8 @@
9
  "noImplicitOverride": true,
10
  "noImplicitReturns": true,
11
  "noFallthroughCasesInSwitch": true,
 
 
12
  "target": "esnext",
13
  "lib": [
14
  "esnext",
 
9
  "noImplicitOverride": true,
10
  "noImplicitReturns": true,
11
  "noFallthroughCasesInSwitch": true,
12
+ "noUnusedLocals": true,
13
+ "noUnusedParameters": true,
14
  "target": "esnext",
15
  "lib": [
16
  "esnext",
config/types/jsconfig.service-worker-strict.json CHANGED
@@ -7,6 +7,8 @@
7
  "noImplicitOverride": true,
8
  "noImplicitReturns": true,
9
  "noFallthroughCasesInSwitch": true,
 
 
10
  "noUncheckedIndexedAccess": true,
11
  "exactOptionalPropertyTypes": true,
12
  "skipLibCheck": true,
 
7
  "noImplicitOverride": true,
8
  "noImplicitReturns": true,
9
  "noFallthroughCasesInSwitch": true,
10
+ "noUnusedLocals": true,
11
+ "noUnusedParameters": true,
12
  "noUncheckedIndexedAccess": true,
13
  "exactOptionalPropertyTypes": true,
14
  "skipLibCheck": true,
config/types/jsconfig.strict.json CHANGED
@@ -8,10 +8,13 @@
8
  "noImplicitOverride": true,
9
  "noImplicitReturns": true,
10
  "noFallthroughCasesInSwitch": true,
 
 
11
  "exactOptionalPropertyTypes": true,
12
  "target": "esnext",
13
  "module": "esnext",
14
  "moduleResolution": "bundler",
 
15
  "paths": {
16
  "/static/*": ["../../static/*"],
17
  "/search/static/*": ["../../static/*"]
 
8
  "noImplicitOverride": true,
9
  "noImplicitReturns": true,
10
  "noFallthroughCasesInSwitch": true,
11
+ "noUnusedLocals": true,
12
+ "noUnusedParameters": true,
13
  "exactOptionalPropertyTypes": true,
14
  "target": "esnext",
15
  "module": "esnext",
16
  "moduleResolution": "bundler",
17
+ "moduleDetection": "force",
18
  "paths": {
19
  "/static/*": ["../../static/*"],
20
  "/search/static/*": ["../../static/*"]
scripts/check_strict_inventory.py CHANGED
@@ -22,7 +22,7 @@ STRICT_FRONTEND_PROJECTS = (
22
  )
23
  REQUIRED_FRONTEND_FLAGS = (
24
  "noUncheckedIndexedAccess", "exactOptionalPropertyTypes", "noImplicitOverride",
25
- "noImplicitReturns", "noFallthroughCasesInSwitch",
26
  )
27
 
28
 
@@ -72,9 +72,8 @@ def inventory_errors(root: Path, js_strict: set[str], js_basic: set[str],
72
 
73
 
74
  def compiler_files(root: Path, config: str, *, strict: bool = False) -> set[str]:
75
- if config not in ("config/types/jsconfig.check.json", "config/types/jsconfig.service-worker.json",
76
- "config/types/jsconfig.service-worker-strict.json", "config/types/jsconfig.chapter-worker-strict.json",
77
- "config/types/jsconfig.strict.json"):
78
  raise ValueError("unknown TypeScript configuration")
79
  node = shutil.which("node")
80
  if node is None:
@@ -88,12 +87,18 @@ def compiler_files(root: Path, config: str, *, strict: bool = False) -> set[str]
88
  if resolved.returncode:
89
  raise RuntimeError(f"{config}: {resolved.stdout}")
90
  options = json.loads(resolved.stdout).get("compilerOptions", {})
 
 
 
91
  for option in ("strictNullChecks", "noImplicitAny"):
92
  if options.get(option, options.get("strict", False)) is not True:
93
  raise RuntimeError(f"{config}: effective {option} must be enabled")
94
  for flag in REQUIRED_FRONTEND_FLAGS:
95
  if options.get(flag) is not True:
96
  raise RuntimeError(f"{config}: effective {flag} must be enabled")
 
 
 
97
  result = subprocess.run([node, str(compiler), "--project", config, "--listFilesOnly"], # noqa: S603
98
  cwd=root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)
99
  if result.returncode:
@@ -129,14 +134,14 @@ def main() -> int:
129
  browser = browser_sources(ROOT)
130
  errors = inventory_errors(ROOT, strict, basic, py_strict, debt, previous)
131
  for path in sorted((browser - strict) & set(debt.get("browser_js", []))):
132
- errors.append(f"browser source must be checked with all five frontend flags: {path}")
133
  if errors:
134
  print("\n".join(errors), file=sys.stderr)
135
  return 1
136
  python_sources = backend_sources(ROOT) | {"app.py"}
137
  print(f"Strict inventory: JS {len(browser & strict)}/{len(browser)}; "
138
  f"backend and entry {len(python_sources & py_strict)}/{len(python_sources)}; "
139
- "no new ungated files; all five frontend flags enforced")
140
  return 0
141
 
142
 
 
22
  )
23
  REQUIRED_FRONTEND_FLAGS = (
24
  "noUncheckedIndexedAccess", "exactOptionalPropertyTypes", "noImplicitOverride",
25
+ "noImplicitReturns", "noFallthroughCasesInSwitch", "noUnusedLocals", "noUnusedParameters",
26
  )
27
 
28
 
 
72
 
73
 
74
  def compiler_files(root: Path, config: str, *, strict: bool = False) -> set[str]:
75
+ if config not in (*STRICT_FRONTEND_PROJECTS, "config/types/jsconfig.check.json",
76
+ "config/types/jsconfig.service-worker.json"):
 
77
  raise ValueError("unknown TypeScript configuration")
78
  node = shutil.which("node")
79
  if node is None:
 
87
  if resolved.returncode:
88
  raise RuntimeError(f"{config}: {resolved.stdout}")
89
  options = json.loads(resolved.stdout).get("compilerOptions", {})
90
+ if (not all(options.get(key) is True for key in ("allowJs", "checkJs", "noEmit"))
91
+ or options.get("noCheck", False) is not False):
92
+ raise RuntimeError(f"{config}: strict JavaScript checking must remain enabled")
93
  for option in ("strictNullChecks", "noImplicitAny"):
94
  if options.get(option, options.get("strict", False)) is not True:
95
  raise RuntimeError(f"{config}: effective {option} must be enabled")
96
  for flag in REQUIRED_FRONTEND_FLAGS:
97
  if options.get(flag) is not True:
98
  raise RuntimeError(f"{config}: effective {flag} must be enabled")
99
+ # Check top-level bindings even in browser classic scripts; this graph never emits.
100
+ if options.get("moduleDetection") != "force":
101
+ raise RuntimeError(f"{config}: effective moduleDetection must be force for top-level unused checking")
102
  result = subprocess.run([node, str(compiler), "--project", config, "--listFilesOnly"], # noqa: S603
103
  cwd=root, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=60)
104
  if result.returncode:
 
134
  browser = browser_sources(ROOT)
135
  errors = inventory_errors(ROOT, strict, basic, py_strict, debt, previous)
136
  for path in sorted((browser - strict) & set(debt.get("browser_js", []))):
137
+ errors.append(f"browser source must be checked with all seven frontend flags: {path}")
138
  if errors:
139
  print("\n".join(errors), file=sys.stderr)
140
  return 1
141
  python_sources = backend_sources(ROOT) | {"app.py"}
142
  print(f"Strict inventory: JS {len(browser & strict)}/{len(browser)}; "
143
  f"backend and entry {len(python_sources & py_strict)}/{len(python_sources)}; "
144
+ "no new ungated files; all seven frontend flags enforced")
145
  return 0
146
 
147
 
static/app.js CHANGED
@@ -97,11 +97,7 @@ const STATE = {
97
  _deferredAppendWhileDragging: false,
98
  };
99
 
100
- const {
101
- openSearchSessionDB,
102
- persistSearchSession,
103
- restoreSearchSession,
104
- } = VoiceOfMLSearchSession.createSearchSession({
105
  canPersist: () => !location.pathname.startsWith("/static/reader.html"),
106
  canRestore: target => {
107
  if (initialSearchDraft) return false;
@@ -111,6 +107,7 @@ const {
111
  && target.pathname !== "/static/reader.html";
112
  },
113
  });
 
114
  /** @type {AbortController | null} */
115
  let searchAbortController = null;
116
  /** @type {VoiceOfMLSearchPrefetchGroup | null} */
@@ -131,9 +128,8 @@ let routeRenderId = 0;
131
  let scrollLoadTimer = null;
132
  /** @type {ReturnType<typeof setTimeout> | null} */
133
  let scrollRecoveryTimer = null;
134
- // Readable host compatibility bridge; only the input controller writes these.
135
  let searchComposing = false;
136
- let searchInputReady = false;
137
  let initialSearchDraft = false;
138
  /** @type {VoiceOfMLInputController} */
139
  let searchInputController;
@@ -149,8 +145,6 @@ const searchResponseStore = VoiceOfMLSearchResponseStore.create({
149
  getSearchViewKey: () => getSearchViewKey(),
150
  rememberSearchPageMetadata: data => rememberSearchPageMetadata(data),
151
  });
152
- // Retain direct cache diagnostics for browser checks.
153
- const searchResponseCache = searchResponseStore.cache;
154
  /** @type {BoundedResponseCache<{data: SearchInitialPayload, time: number}>} */
155
  const initialPayloadCache = new BoundedResponseCache(16, SEARCH_CACHE_TTL);
156
  const embeddedInitialAcquiredAt = Date.now();
@@ -170,7 +164,6 @@ function getSidebarScroll() {
170
  }
171
  const SEARCH_REQUEST_TIMEOUT = 25000;
172
  const APPEND_REQUEST_TIMEOUT = 5000;
173
- const pendingSearchPages = getSearchTransport().pending;
174
  // Detached compatibility projection for browser diagnostics; the controller owns recovery.
175
  let pagingFailures = 0;
176
  const DOWNLOAD_CHECK_TIMEOUT = 8000;
@@ -196,7 +189,6 @@ function getSearchHistoryController() {
196
  submitSearchQuery: (query, options) => submitSearchQuery(query, options)
197
  }));
198
  }
199
- function getHistory() { return searchHistoryStore.get(); }
200
  /** @param {string[]} list */
201
  function saveHistory(list) { searchHistoryStore.save(list); }
202
 
@@ -232,7 +224,6 @@ function stableSearchStringify(value) {
232
  }
233
 
234
  const SEARCH_VIEW_SNAPSHOT_VERSION = VoiceOfMLSnapshotPolicy.VERSION;
235
- const SEARCH_VIEW_SNAPSHOT_BYTES_MAX = VoiceOfMLSnapshotPolicy.BYTES_MAX;
236
  const resultSnapshots = VoiceOfMLResultSnapshots.create({
237
  cloneResult: record => cloneSearchResult(record),
238
  measurementKey: () => getHeightMeasurementKey(),
@@ -870,9 +861,6 @@ async function fetchPositionPage(query, page, signal, anchorId) {
870
  return fetchSearchPage(url + "|" + stableSearchStringify(body), url, body, signal, SEARCH_REQUEST_TIMEOUT);
871
  }
872
 
873
- function trimSearchViewSnapshots() {
874
- resultSnapshots.trim();
875
- }
876
  /** @type {VoiceOfMLSearchViewMemo | null} */
877
  let searchViewKeyMemo = null;
878
 
@@ -1177,11 +1165,6 @@ function getSearchTransport() {
1177
  });
1178
  }
1179
 
1180
- /** @param {string} cacheKey @param {string} url @param {VoiceOfMLSearchRequestBody} body @param {number} timeoutMs */
1181
- function createSearchPageRequest(cacheKey, url, body, timeoutMs) {
1182
- return getSearchTransport().createRequest(cacheKey, url, body, timeoutMs);
1183
- }
1184
-
1185
  /** @param {string} cacheKey @param {string} url @param {VoiceOfMLSearchRequestBody} body @param {AbortSignal | null | undefined} signal @param {number} timeoutMs */
1186
  function fetchSearchPage(cacheKey, url, body, signal, timeoutMs) {
1187
  return getSearchTransport().fetchPage(cacheKey, url, body, signal, timeoutMs);
@@ -1342,8 +1325,6 @@ function addHistoryItem(q) { getSearchHistoryController().addHistoryItem(q); }
1342
  function renderDropdown() { getSearchHistoryController().renderDropdown(); }
1343
  function hideSearchHistory(restoreFocus = false) { getSearchHistoryController().hideSearchHistory(restoreFocus); }
1344
  function setupSearchHistory() { getSearchHistoryController().setupSearchHistory(); }
1345
- /** @param {string} q */
1346
- function removeHistoryItem(q) { getSearchHistoryController().removeHistoryItem(q); }
1347
  /** @type {Record<number, boolean>} */
1348
  var selectedIndices = {};
1349
  var lastSelectedIndex = -1;
@@ -1545,23 +1526,12 @@ const downloadController = VoiceOfMLDownloadController.createDownloadController(
1545
  isBatchActive: downloadBatches.isActive,
1546
  timeout: DOWNLOAD_CHECK_TIMEOUT,
1547
  });
1548
- const {
1549
- downloadChecks,
1550
- downloadCheckQueue,
1551
- pendingDownloads,
1552
- checkDownload,
1553
- runDownloadCheck,
1554
- pumpDownloadChecks,
1555
- scheduleDownloadLaunch,
1556
- downloadFile,
1557
- } = downloadController;
1558
  Object.defineProperty(globalThis, "activeDownloadChecks", {
1559
  configurable: true,
1560
  get: () => downloadController.activeDownloadChecks,
1561
  });
1562
 
1563
- function renderDownloadBatch() { downloadBatches.render(); }
1564
-
1565
  function getSelectedFiles() {
1566
  const files = Object.keys(selectedIndices).map(Number).flatMap(index => {
1567
  if (resultSnapshots.cloneTask) materializeSnapshotRange(resultSnapshots.cloneTask, index, index + 1, true);
@@ -1767,7 +1737,6 @@ const readerHost = VoiceOfMLReaderHost.create({
1767
  closeOverlay: (focus, scroll) => closeReaderOverlay(focus, scroll), reconcile: () => reconcileSearchDestination()
1768
  });
1769
  const readerNavigation = readerHost.navigation;
1770
- const READER_RETURN_SEARCH_KEYS = readerHost.keys;
1771
  // Read-only compatibility projections for existing browser diagnostics.
1772
  Object.defineProperties(window, {
1773
  readerOverlay: { get: () => readerHost.overlay },
@@ -1868,7 +1837,6 @@ const warmedReaderSources = new Map();
1868
  // Match reader-resolve's metadata freshness without imposing a lifetime quota.
1869
  const READER_WARMUP_TTL = 5 * 60 * 1000;
1870
  const READER_WARMUP_MAX = 8;
1871
- let readerWarmupInFlight = 0;
1872
  /** @type {{key: string, cancel(superseded?: boolean): void} | null} */
1873
  let readerWarmupPending = null;
1874
  /** @type {Map<string, number>} */
@@ -1915,7 +1883,6 @@ function startReaderSourceWarmup(base, readerId, sourceUrl, urgent = false) {
1915
  if (readerWarmupPending !== task) return;
1916
  clearTimeout(timer);
1917
  readerWarmupPending = null;
1918
- readerWarmupInFlight = 0;
1919
  if (success) {
1920
  let metadataStored = false;
1921
  if (readerId) {
@@ -1942,7 +1909,6 @@ function startReaderSourceWarmup(base, readerId, sourceUrl, urgent = false) {
1942
  }
1943
  };
1944
  readerWarmupPending = task;
1945
- readerWarmupInFlight = 1;
1946
  const timer = setTimeout(() => task.cancel(), 8000);
1947
  (async () => {
1948
  try {
@@ -2055,7 +2021,6 @@ const catalog = VoiceOfMLCatalogClient.create({
2055
  fetchJSON: (url, timeout) => fetchJsonWithTimeout(url, timeout),
2056
  getBootstrap: () => API.getBootstrap(),
2057
  });
2058
- const { sidebarInitialCache, sidebarInitialPending } = catalog;
2059
 
2060
  /** @type {VoiceOfMLSearchAppApi} */
2061
  const API = {
@@ -2382,14 +2347,17 @@ function getSidebarDirectory() {
2382
  renderRepos: repos => renderRepoListItems(repos), updateHeader: () => {},
2383
  initial: repo => loadSidebarInitial(repo), fetchRepos: () => API.getRepos(),
2384
  fetchContents: (repo, path) => API.getContents(repo, path).then(data => data ?? null),
2385
- localContents: (repo, path) => Promise.resolve(null), ensureLocal: (force, silent) => Promise.resolve(false),
2386
  cachedContents: key => API._browserCache?.get(key), publishRepos: repos => { STATE.repoList = repos || []; },
2387
  refreshAssets: refreshSidebarReaderAssets,
2388
  }));
2389
  }
2390
 
2391
- /** @param {HTMLElement} list @param {string} currentRepo @param {string} path @param {number | undefined} routeId @param {() => VoiceOfMLSidebarEntries | null} readDisplayed @param {() => boolean} isCurrent */
2392
- function refreshSidebarReaderAssets(list, currentRepo, path, routeId, readDisplayed, isCurrent) {
 
 
 
2393
  // Directory navigation remains usable while optional converted assets load.
2394
  const initialAssets = readerAssetController.state.assets;
2395
  loadReaderAssets().then(() => {
@@ -2417,11 +2385,6 @@ function renderRepoListItems(repos) {
2417
  return getSidebarDirectoryView().repos(repos);
2418
  }
2419
 
2420
- /** @param {number} [routeId] */
2421
- function renderRepoList(routeId) {
2422
- return getSidebarDirectory().repos(routeId);
2423
- }
2424
-
2425
  /** @param {VoiceOfMLSidebarFile & {link?: string}} f @param {string} currentRepo @param {string} path */
2426
  function getBrowserFileReadUrl(f, currentRepo, path) {
2427
  const displayName = getBrowserFileName(f);
@@ -2433,21 +2396,11 @@ function getBrowserFileReadUrl(f, currentRepo, path) {
2433
  return isReadableRecord(record) ? VoiceOfMLReader.readerUrl(record, "/static/reader.html") : "";
2434
  }
2435
 
2436
- /** @param {HTMLElement} list @param {VoiceOfMLSidebarEntries} data @param {string} currentRepo @param {string} path */
2437
- function renderBrowserListItems(list, data, currentRepo, path) {
2438
- return getSidebarDirectoryView().items(list, data, currentRepo, path);
2439
- }
2440
-
2441
  /** @param {string} path @param {number} [routeId] */
2442
  function renderBrowser(path, routeId) {
2443
  return getSidebarDirectory().browse(path, routeId);
2444
  }
2445
 
2446
- /** @param {string} path */
2447
- function createSidebarBreadcrumb(path) {
2448
- return getSidebarDirectoryView().breadcrumb(path);
2449
- }
2450
-
2451
  /** @param {string} query @param {{restore?: boolean, record?: boolean, refreshHistory?: boolean, clearResults?: boolean, blur?: boolean, updateInput?: boolean}} [options] */
2452
  function submitSearchQuery(query, { restore = false, record = false, refreshHistory = false, clearResults = false, blur = false, updateInput = restore } = {}) {
2453
  if (Array.from(query).length > 256) {
@@ -2506,7 +2459,6 @@ function setupSearchInput() {
2506
  onState: state => {
2507
  searchTimer = state.timer;
2508
  searchComposing = state.composing;
2509
- searchInputReady = state.ready;
2510
  initialSearchDraft = state.dirty;
2511
  }
2512
  });
@@ -2609,8 +2561,6 @@ function getResultRows() {
2609
  });
2610
  return resultRows;
2611
  }
2612
- /** @param {VoiceOfMLResultRecord} rec @param {number} idx */
2613
- function buildResultHTML(rec, idx) { return getResultRows().buildHTML(rec, idx); }
2614
 
2615
  /** @type {ReaderAssetMap | null} */
2616
  let refreshedReaderAssets = null;
@@ -2773,7 +2723,6 @@ function resetVirtualScrollState() { return getVirtualResults().resetVirtualScro
2773
  function ensureVirtualHeights(len) { return getVirtualResults().ensureVirtualHeights(len); }
2774
  function refreshVirtualAfterAppend(updateView = true) { return getVirtualResults().refreshVirtualAfterAppend(updateView); }
2775
  function ensureVirtualViewportCovered() { return getVirtualResults().ensureVirtualViewportCovered(); }
2776
- function measureHeights(start = VSCROLL.renderStart, end = VSCROLL.renderEnd, anchor = null) { return getVirtualResults().measureHeights(start, end, anchor); }
2777
 
2778
  function prepareRouteTransitionResults() {
2779
  saveSearchViewSnapshot();
@@ -3222,15 +3171,12 @@ function renderFilters(routeId) { return getSidebarFilters().render(routeId); }
3222
  /** @param {number} routeId */
3223
  function retainFilterRenderingForRoute(routeId) { return getSidebarFilters().retain(routeId); }
3224
  /** @param {number} [routeId] */
3225
- function renderRepoFilter(routeId) { return getSidebarFilters().renderRepos(routeId); }
3226
- /** @param {number} [routeId] */
3227
  function renderExtensionFilter(routeId) { return getSidebarFilters().renderExtensions(routeId); }
3228
  function getSidebarFolderTree() {
3229
  getSidebarFilters();
3230
  if (!sidebarFolderTree) throw new Error("Sidebar folder tree was not initialized");
3231
  return sidebarFolderTree;
3232
  }
3233
- function renderFilterFolderTree() { getSidebarFolderTree().render(); }
3234
  function refreshFilterFolderSelectionState() { getSidebarFolderTree().refresh(); }
3235
  /** @param {boolean} collapsed */
3236
  function setAllFoldersCollapsed(collapsed) { getSidebarFolderTree().setAllCollapsed(collapsed); }
@@ -3592,8 +3538,6 @@ function applyTheme() { getShell().applyTheme(); }
3592
  function toggleMobile() { getShell().toggleMobile(); }
3593
  function applyMobileMode() { getShell().applyMobileMode(); }
3594
  function autoDetectMobile() { return window.innerWidth <= 768; }
3595
- /** @param {HTMLElement} sidebar */
3596
- function focusSearchSidebar(sidebar) { VoiceOfMLShellView.focusSearchSidebar(sidebar); }
3597
  /** @param {VoiceOfMLShellEvent} [event] */
3598
  function toggleLeftSidebar(event) { getShell().toggleLeftSidebar(event); }
3599
  /** @param {VoiceOfMLShellEvent} [event] */
 
97
  _deferredAppendWhileDragging: false,
98
  };
99
 
100
+ const searchSession = VoiceOfMLSearchSession.createSearchSession({
 
 
 
 
101
  canPersist: () => !location.pathname.startsWith("/static/reader.html"),
102
  canRestore: target => {
103
  if (initialSearchDraft) return false;
 
107
  && target.pathname !== "/static/reader.html";
108
  },
109
  });
110
+ const { persistSearchSession, restoreSearchSession } = searchSession;
111
  /** @type {AbortController | null} */
112
  let searchAbortController = null;
113
  /** @type {VoiceOfMLSearchPrefetchGroup | null} */
 
128
  let scrollLoadTimer = null;
129
  /** @type {ReturnType<typeof setTimeout> | null} */
130
  let scrollRecoveryTimer = null;
131
+ // Only the input controller writes these.
132
  let searchComposing = false;
 
133
  let initialSearchDraft = false;
134
  /** @type {VoiceOfMLInputController} */
135
  let searchInputController;
 
145
  getSearchViewKey: () => getSearchViewKey(),
146
  rememberSearchPageMetadata: data => rememberSearchPageMetadata(data),
147
  });
 
 
148
  /** @type {BoundedResponseCache<{data: SearchInitialPayload, time: number}>} */
149
  const initialPayloadCache = new BoundedResponseCache(16, SEARCH_CACHE_TTL);
150
  const embeddedInitialAcquiredAt = Date.now();
 
164
  }
165
  const SEARCH_REQUEST_TIMEOUT = 25000;
166
  const APPEND_REQUEST_TIMEOUT = 5000;
 
167
  // Detached compatibility projection for browser diagnostics; the controller owns recovery.
168
  let pagingFailures = 0;
169
  const DOWNLOAD_CHECK_TIMEOUT = 8000;
 
189
  submitSearchQuery: (query, options) => submitSearchQuery(query, options)
190
  }));
191
  }
 
192
  /** @param {string[]} list */
193
  function saveHistory(list) { searchHistoryStore.save(list); }
194
 
 
224
  }
225
 
226
  const SEARCH_VIEW_SNAPSHOT_VERSION = VoiceOfMLSnapshotPolicy.VERSION;
 
227
  const resultSnapshots = VoiceOfMLResultSnapshots.create({
228
  cloneResult: record => cloneSearchResult(record),
229
  measurementKey: () => getHeightMeasurementKey(),
 
861
  return fetchSearchPage(url + "|" + stableSearchStringify(body), url, body, signal, SEARCH_REQUEST_TIMEOUT);
862
  }
863
 
 
 
 
864
  /** @type {VoiceOfMLSearchViewMemo | null} */
865
  let searchViewKeyMemo = null;
866
 
 
1165
  });
1166
  }
1167
 
 
 
 
 
 
1168
  /** @param {string} cacheKey @param {string} url @param {VoiceOfMLSearchRequestBody} body @param {AbortSignal | null | undefined} signal @param {number} timeoutMs */
1169
  function fetchSearchPage(cacheKey, url, body, signal, timeoutMs) {
1170
  return getSearchTransport().fetchPage(cacheKey, url, body, signal, timeoutMs);
 
1325
  function renderDropdown() { getSearchHistoryController().renderDropdown(); }
1326
  function hideSearchHistory(restoreFocus = false) { getSearchHistoryController().hideSearchHistory(restoreFocus); }
1327
  function setupSearchHistory() { getSearchHistoryController().setupSearchHistory(); }
 
 
1328
  /** @type {Record<number, boolean>} */
1329
  var selectedIndices = {};
1330
  var lastSelectedIndex = -1;
 
1526
  isBatchActive: downloadBatches.isActive,
1527
  timeout: DOWNLOAD_CHECK_TIMEOUT,
1528
  });
1529
+ const { checkDownload, downloadFile } = downloadController;
 
 
 
 
 
 
 
 
 
1530
  Object.defineProperty(globalThis, "activeDownloadChecks", {
1531
  configurable: true,
1532
  get: () => downloadController.activeDownloadChecks,
1533
  });
1534
 
 
 
1535
  function getSelectedFiles() {
1536
  const files = Object.keys(selectedIndices).map(Number).flatMap(index => {
1537
  if (resultSnapshots.cloneTask) materializeSnapshotRange(resultSnapshots.cloneTask, index, index + 1, true);
 
1737
  closeOverlay: (focus, scroll) => closeReaderOverlay(focus, scroll), reconcile: () => reconcileSearchDestination()
1738
  });
1739
  const readerNavigation = readerHost.navigation;
 
1740
  // Read-only compatibility projections for existing browser diagnostics.
1741
  Object.defineProperties(window, {
1742
  readerOverlay: { get: () => readerHost.overlay },
 
1837
  // Match reader-resolve's metadata freshness without imposing a lifetime quota.
1838
  const READER_WARMUP_TTL = 5 * 60 * 1000;
1839
  const READER_WARMUP_MAX = 8;
 
1840
  /** @type {{key: string, cancel(superseded?: boolean): void} | null} */
1841
  let readerWarmupPending = null;
1842
  /** @type {Map<string, number>} */
 
1883
  if (readerWarmupPending !== task) return;
1884
  clearTimeout(timer);
1885
  readerWarmupPending = null;
 
1886
  if (success) {
1887
  let metadataStored = false;
1888
  if (readerId) {
 
1909
  }
1910
  };
1911
  readerWarmupPending = task;
 
1912
  const timer = setTimeout(() => task.cancel(), 8000);
1913
  (async () => {
1914
  try {
 
2021
  fetchJSON: (url, timeout) => fetchJsonWithTimeout(url, timeout),
2022
  getBootstrap: () => API.getBootstrap(),
2023
  });
 
2024
 
2025
  /** @type {VoiceOfMLSearchAppApi} */
2026
  const API = {
 
2347
  renderRepos: repos => renderRepoListItems(repos), updateHeader: () => {},
2348
  initial: repo => loadSidebarInitial(repo), fetchRepos: () => API.getRepos(),
2349
  fetchContents: (repo, path) => API.getContents(repo, path).then(data => data ?? null),
2350
+ localContents: () => Promise.resolve(null), ensureLocal: () => Promise.resolve(false),
2351
  cachedContents: key => API._browserCache?.get(key), publishRepos: repos => { STATE.repoList = repos || []; },
2352
  refreshAssets: refreshSidebarReaderAssets,
2353
  }));
2354
  }
2355
 
2356
+ /**
2357
+ * @param {[list: HTMLElement, repo: string, path: string, routeId: number | undefined,
2358
+ * readDisplayed: () => VoiceOfMLSidebarEntries | null, isCurrent: () => boolean]} args
2359
+ */
2360
+ function refreshSidebarReaderAssets(...[list, currentRepo, path, , readDisplayed, isCurrent]) {
2361
  // Directory navigation remains usable while optional converted assets load.
2362
  const initialAssets = readerAssetController.state.assets;
2363
  loadReaderAssets().then(() => {
 
2385
  return getSidebarDirectoryView().repos(repos);
2386
  }
2387
 
 
 
 
 
 
2388
  /** @param {VoiceOfMLSidebarFile & {link?: string}} f @param {string} currentRepo @param {string} path */
2389
  function getBrowserFileReadUrl(f, currentRepo, path) {
2390
  const displayName = getBrowserFileName(f);
 
2396
  return isReadableRecord(record) ? VoiceOfMLReader.readerUrl(record, "/static/reader.html") : "";
2397
  }
2398
 
 
 
 
 
 
2399
  /** @param {string} path @param {number} [routeId] */
2400
  function renderBrowser(path, routeId) {
2401
  return getSidebarDirectory().browse(path, routeId);
2402
  }
2403
 
 
 
 
 
 
2404
  /** @param {string} query @param {{restore?: boolean, record?: boolean, refreshHistory?: boolean, clearResults?: boolean, blur?: boolean, updateInput?: boolean}} [options] */
2405
  function submitSearchQuery(query, { restore = false, record = false, refreshHistory = false, clearResults = false, blur = false, updateInput = restore } = {}) {
2406
  if (Array.from(query).length > 256) {
 
2459
  onState: state => {
2460
  searchTimer = state.timer;
2461
  searchComposing = state.composing;
 
2462
  initialSearchDraft = state.dirty;
2463
  }
2464
  });
 
2561
  });
2562
  return resultRows;
2563
  }
 
 
2564
 
2565
  /** @type {ReaderAssetMap | null} */
2566
  let refreshedReaderAssets = null;
 
2723
  function ensureVirtualHeights(len) { return getVirtualResults().ensureVirtualHeights(len); }
2724
  function refreshVirtualAfterAppend(updateView = true) { return getVirtualResults().refreshVirtualAfterAppend(updateView); }
2725
  function ensureVirtualViewportCovered() { return getVirtualResults().ensureVirtualViewportCovered(); }
 
2726
 
2727
  function prepareRouteTransitionResults() {
2728
  saveSearchViewSnapshot();
 
3171
  /** @param {number} routeId */
3172
  function retainFilterRenderingForRoute(routeId) { return getSidebarFilters().retain(routeId); }
3173
  /** @param {number} [routeId] */
 
 
3174
  function renderExtensionFilter(routeId) { return getSidebarFilters().renderExtensions(routeId); }
3175
  function getSidebarFolderTree() {
3176
  getSidebarFilters();
3177
  if (!sidebarFolderTree) throw new Error("Sidebar folder tree was not initialized");
3178
  return sidebarFolderTree;
3179
  }
 
3180
  function refreshFilterFolderSelectionState() { getSidebarFolderTree().refresh(); }
3181
  /** @param {boolean} collapsed */
3182
  function setAllFoldersCollapsed(collapsed) { getSidebarFolderTree().setAllCollapsed(collapsed); }
 
3538
  function toggleMobile() { getShell().toggleMobile(); }
3539
  function applyMobileMode() { getShell().applyMobileMode(); }
3540
  function autoDetectMobile() { return window.innerWidth <= 768; }
 
 
3541
  /** @param {VoiceOfMLShellEvent} [event] */
3542
  function toggleLeftSidebar(event) { getShell().toggleLeftSidebar(event); }
3543
  /** @param {VoiceOfMLShellEvent} [event] */
static/reader/core/reader-security.js CHANGED
@@ -210,7 +210,6 @@ function (root) {
210
  return /** @type {import('../../../typings/reader-security-strict').ValidatedPdfPageManifest} */ (/** @type {unknown} */ (manifest));
211
  }
212
  const PDF_OCR_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr\/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)$/;
213
- const PDF_OCR_MANIFEST_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr-manifest\.json$/;
214
  const PDF_OCR_PAGE_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?pages\/page-[0-9]{6}\.(?:webp|jxl|png)$/;
215
  const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;
216
  /** @param {unknown} path */
 
210
  return /** @type {import('../../../typings/reader-security-strict').ValidatedPdfPageManifest} */ (/** @type {unknown} */ (manifest));
211
  }
212
  const PDF_OCR_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?ocr\/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)$/;
 
213
  const PDF_OCR_PAGE_PATH = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/(?:[0-9a-f]{16}\/)?pages\/page-[0-9]{6}\.(?:webp|jxl|png)$/;
214
  const PDF_OCR_ROOT = /^(objects\/[0-9a-f]{2}\/[0-9a-f]{64}(?:\/[0-9a-f]{16})?)/;
215
  /** @param {unknown} path */
static/reader/core/reader-source.mjs CHANGED
@@ -342,8 +342,8 @@ export function createReaderSource(readerContext) {
342
  }
343
  }
344
 
345
- /** @param {string} raw @param {string} base @param {string} attribute @param {string} manifestBase */
346
- function trustedChapterResourceUrl(raw, base, attribute, manifestBase) {
347
  const value = String(raw || "").trim();
348
  if (!value || /^(?:data:|mailto:|tel:|javascript:)/i.test(value)) return null;
349
  // Chapters and resources can be siblings within the manifest's asset directory.
 
342
  }
343
  }
344
 
345
+ /** @param {string} raw @param {string} base @param {string} manifestBase */
346
+ function trustedChapterResourceUrl(raw, base, manifestBase) {
347
  const value = String(raw || "").trim();
348
  if (!value || /^(?:data:|mailto:|tel:|javascript:)/i.test(value)) return null;
349
  // Chapters and resources can be siblings within the manifest's asset directory.
static/reader/formats/reader-chapter-format.mjs CHANGED
@@ -192,8 +192,37 @@ export function createReaderChapterFormat(readerContext) {
192
  }
193
  }
194
  : null;
 
 
195
  /** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter */
196
- const chapterUrl = (chapter) => readerContext.trustedChapterUrl(chapter.path, manifestBase);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  /** @param {number} index */
198
  const chapterAt = (index) => chapterByIndex.get(index) || null;
199
  /** @param {number} index @param {string} selector */
@@ -202,11 +231,11 @@ export function createReaderChapterFormat(readerContext) {
202
  if (Number(/** @type {HTMLElement} */ (node).dataset.chapter) > index) return node;
203
  return null;
204
  };
205
- /** @param {string} raw @param {string} base @param {string} attribute */
206
- const resourceUrl = (raw, base, attribute) => {
207
  const value = String(raw || "").trim();
208
  if (!value || value.startsWith("#")) return null;
209
- return readerContext.trustedChapterResourceUrl(value, base, attribute, manifestBase);
210
  };
211
  /** @param {HTMLElement} article */
212
  const insertChapter = (article) => {
@@ -368,7 +397,7 @@ export function createReaderChapterFormat(readerContext) {
368
  const value = element.getAttribute(name) || "";
369
  if (name === "href" && element.localName === "a" &&
370
  readerContext.trustedChapterReferenceUrl(value, url, manifestBase)) continue;
371
- const resolved = resourceUrl(value, url, name === "href" ? "href" : "resource");
372
  if (resolved) element.setAttribute(name, resolved);
373
  else if (!(name === "href" && value.startsWith("#"))) element.removeAttribute(name);
374
  }
@@ -511,9 +540,8 @@ export function createReaderChapterFormat(readerContext) {
511
  return;
512
  const current = chapterAt(Number(article.dataset.chapter));
513
  const destination = readerContext.trustedChapterReferenceUrl(link.getAttribute("href"), chapterUrl(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (current)), manifestBase);
514
- const target = destination ? new URL(destination.url) : null;
515
  const fragment = destination?.fragment || "";
516
- const chapter = target && manifest.chapters.find((item) => chapterUrl(item) === target.href);
517
  if (!chapter) {
518
  // A stale or missing book document must not navigate out to an asset 404.
519
  if (/\.(?:xhtml?|html?)(?:$|#)/i.test(link.getAttribute("href") || "")) {
@@ -744,7 +772,6 @@ export function createReaderChapterFormat(readerContext) {
744
  chapterWindowReady = true;
745
  if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate();
746
  for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(article);
747
- frame.style.overflowAnchor = "none";
748
  scheduleChapterWindow();
749
  readerContext.assertReaderActive();
750
  readerContext.markReaderContentReady();
 
192
  }
193
  }
194
  : null;
195
+ /** @type {Map<string, string | null>} */
196
+ const resolvedChapterUrls = new Map();
197
  /** @param {import("../../../typings/reader-chapter-format-strict").Chapter} chapter */
198
+ const chapterUrl = (chapter) => {
199
+ let url = resolvedChapterUrls.get(chapter.path);
200
+ if (url === undefined) {
201
+ url = readerContext.trustedChapterUrl(chapter.path, manifestBase);
202
+ resolvedChapterUrls.set(chapter.path, url);
203
+ }
204
+ return url;
205
+ };
206
+ /** @type {Map<string, import("../../../typings/reader-chapter-format-strict").Chapter> | null} */
207
+ let chaptersByUrl = null;
208
+ let indexedChapterCount = 0;
209
+ /** @param {string} href */
210
+ const chapterAtUrl = (href) => {
211
+ const byUrl = chaptersByUrl ??= new Map();
212
+ const indexed = byUrl.get(href);
213
+ if (indexed) return indexed;
214
+ // Extend only on demand, in manifest order (not chapter load order),
215
+ // so duplicate URLs still resolve to the first chapter.
216
+ while (indexedChapterCount < manifest.chapters.length) {
217
+ const chapter = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[indexedChapterCount]);
218
+ const url = chapterUrl(chapter);
219
+ indexedChapterCount++;
220
+ if (url === null || byUrl.has(url)) continue;
221
+ byUrl.set(url, chapter);
222
+ if (url === href) return chapter;
223
+ }
224
+ return null;
225
+ };
226
  /** @param {number} index */
227
  const chapterAt = (index) => chapterByIndex.get(index) || null;
228
  /** @param {number} index @param {string} selector */
 
231
  if (Number(/** @type {HTMLElement} */ (node).dataset.chapter) > index) return node;
232
  return null;
233
  };
234
+ /** @param {string} raw @param {string} base */
235
+ const resourceUrl = (raw, base) => {
236
  const value = String(raw || "").trim();
237
  if (!value || value.startsWith("#")) return null;
238
+ return readerContext.trustedChapterResourceUrl(value, base, manifestBase);
239
  };
240
  /** @param {HTMLElement} article */
241
  const insertChapter = (article) => {
 
397
  const value = element.getAttribute(name) || "";
398
  if (name === "href" && element.localName === "a" &&
399
  readerContext.trustedChapterReferenceUrl(value, url, manifestBase)) continue;
400
+ const resolved = resourceUrl(value, url);
401
  if (resolved) element.setAttribute(name, resolved);
402
  else if (!(name === "href" && value.startsWith("#"))) element.removeAttribute(name);
403
  }
 
540
  return;
541
  const current = chapterAt(Number(article.dataset.chapter));
542
  const destination = readerContext.trustedChapterReferenceUrl(link.getAttribute("href"), chapterUrl(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (current)), manifestBase);
 
543
  const fragment = destination?.fragment || "";
544
+ const chapter = destination && chapterAtUrl(new URL(destination.url).href);
545
  if (!chapter) {
546
  // A stale or missing book document must not navigate out to an asset 404.
547
  if (/\.(?:xhtml?|html?)(?:$|#)/i.test(link.getAttribute("href") || "")) {
 
772
  chapterWindowReady = true;
773
  if (readerContext.isReaderGenerationCurrent("navigation", openingGeneration)) readerContext.chapterScrollAnchors.invalidate();
774
  for (const article of frame.querySelectorAll(".reader-epub-chapter")) readerContext.chapterScrollAnchors.observe(article);
 
775
  scheduleChapterWindow();
776
  readerContext.assertReaderActive();
777
  readerContext.markReaderContentReady();
static/reader/pdf/reader-pdf-engine.mjs CHANGED
@@ -48,7 +48,7 @@ export function createReaderPdfEngine(readerContext) {
48
  canPrefetchFirstPage: () => readerContext.capability?.mode === "pdf" &&
49
  readerContext.readerRestorationLoaded && !readerContext.restorationFailed &&
50
  (!readerContext.readerRestorationEntry || Number(readerContext.readerRestorationEntry.page) === 1),
51
- onError(error) {
52
  if (!documentReady || readerContext.readerAbortController.signal.aborted) return;
53
  if (readerContext.capability.mode !== "pdf") return;
54
  // Page retries cannot revive a destroyed PDF.js document. Capture an
@@ -83,10 +83,9 @@ export function createReaderPdfEngine(readerContext) {
83
  }));
84
  }
85
 
86
- /** @param {PdfModule} pdfjs @param {(url: string) => PdfOptions} options @param {string} originalUrl @param {string} proxyUrl @param {(url: string) => Initial} takeInitial */
87
- function loadPdfWithTimeout(pdfjs, options, originalUrl = readerContext.sourceUrl, proxyUrl = readerContext.contentUrl, takeInitial = (_url) => null) {
88
- // Keep a failed proxy on the proxied URL. Falling through to originalUrl
89
- // opens huggingface.co directly, which does not connect on this network.
90
  return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl)));
91
  }
92
 
@@ -390,7 +389,7 @@ export function createReaderPdfEngine(readerContext) {
390
  standardFontDataUrl: readerContext.PDFJS_STANDARD_FONT_URL,
391
  withCredentials: false
392
  });
393
- return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document")
394
  .catch(async error => {
395
  readerContext.assertReaderActive();
396
  if (!stagedWorker || (/** @type {{name?: string} | null | undefined} */ (error))?.name === "AbortError" || readerContext.retryableReaderProxyError(error) ||
@@ -400,7 +399,7 @@ export function createReaderPdfEngine(readerContext) {
400
  // original worker, not silently accept provisional page identities.
401
  readerContext.releasePdfWorker?.();
402
  await readerContext.preparePdfWorker(pdfjs);
403
- return readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial);
404
  });
405
  }).finally(() => {
406
  initial = null;
 
48
  canPrefetchFirstPage: () => readerContext.capability?.mode === "pdf" &&
49
  readerContext.readerRestorationLoaded && !readerContext.restorationFailed &&
50
  (!readerContext.readerRestorationEntry || Number(readerContext.readerRestorationEntry.page) === 1),
51
+ onError() {
52
  if (!documentReady || readerContext.readerAbortController.signal.aborted) return;
53
  if (readerContext.capability.mode !== "pdf") return;
54
  // Page retries cannot revive a destroyed PDF.js document. Capture an
 
83
  }));
84
  }
85
 
86
+ /** @param {PdfModule} pdfjs @param {(url: string) => PdfOptions} options @param {string} proxyUrl @param {(url: string) => Initial} [takeInitial] */
87
+ function loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial = () => null) {
88
+ // Retry the proxy URL only; never fall back to the original source URL.
 
89
  return readerContext.retryReaderProxy(() => readerContext.loadPdfTaskWithTimeout(pdfjs, options, proxyUrl, takeInitial(proxyUrl)));
90
  }
91
 
 
389
  standardFontDataUrl: readerContext.PDFJS_STANDARD_FONT_URL,
390
  withCredentials: false
391
  });
392
+ return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial), "document")
393
  .catch(async error => {
394
  readerContext.assertReaderActive();
395
  if (!stagedWorker || (/** @type {{name?: string} | null | undefined} */ (error))?.name === "AbortError" || readerContext.retryableReaderProxyError(error) ||
 
399
  // original worker, not silently accept provisional page identities.
400
  readerContext.releasePdfWorker?.();
401
  await readerContext.preparePdfWorker(pdfjs);
402
+ return readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial);
403
  });
404
  }).finally(() => {
405
  initial = null;
static/reader/pdf/reader-pdf-range-hints.mjs CHANGED
@@ -162,11 +162,11 @@ export function choosePdfRangeChunkSize(bytes, total, fallback = PDF_DEFAULT_CHU
162
  // some edge cases rather than penalizing ordinary books.
163
  if (/** @type {number} */ (numbers[numbers.length - 1]) - /** @type {number} */ (numbers[0]) >= refs.length * 2) return PDF_ADAPTIVE_CHUNK_BYTES;
164
  }
165
- return chooseLargeFlatTreeChunkSize(bytes, total, fallback);
166
  }
167
 
168
- /** @param {Uint8Array} bytes @param {number} total @param {number} fallback */
169
- function chooseLargeFlatTreeChunkSize(bytes, total, fallback) {
170
  const head = new TextDecoder('latin1').decode(bytes.subarray(0, Math.min(bytes.length, PDF_LARGE_FLAT_HEADER_BYTES)));
171
  if (!head.startsWith('%PDF-') || /\/Linearized\b/.test(head.slice(0, 1024))) return fallback;
172
  // Walk only complete direct-length objects. Skip stream bytes exactly; this
 
162
  // some edge cases rather than penalizing ordinary books.
163
  if (/** @type {number} */ (numbers[numbers.length - 1]) - /** @type {number} */ (numbers[0]) >= refs.length * 2) return PDF_ADAPTIVE_CHUNK_BYTES;
164
  }
165
+ return chooseLargeFlatTreeChunkSize(bytes, fallback);
166
  }
167
 
168
+ /** @param {Uint8Array} bytes @param {number} fallback */
169
+ function chooseLargeFlatTreeChunkSize(bytes, fallback) {
170
  const head = new TextDecoder('latin1').decode(bytes.subarray(0, Math.min(bytes.length, PDF_LARGE_FLAT_HEADER_BYTES)));
171
  if (!head.startsWith('%PDF-') || /\/Linearized\b/.test(head.slice(0, 1024))) return fallback;
172
  // Walk only complete direct-length objects. Skip stream bytes exactly; this
static/reader/pdf/reader-pdf-renderer.mjs CHANGED
@@ -198,8 +198,8 @@ export function createReaderPdfRenderer(readerContext) {
198
  }
199
 
200
  // Reveal ordinary image pages only after decoding; respect reduced motion.
201
- /** @param {import('../../../typings/reader-pdf-renderer-strict').PdfShell} shell @param {HTMLElement} surface @param {boolean} fade */
202
- function revealPdfSurface(shell, surface, fade) {
203
  surface.classList.add("ready");
204
  if (fade && readerContext.capability?.mode === "image-pages")
205
  surface.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: 120, easing: "ease" });
@@ -290,7 +290,7 @@ export function createReaderPdfRenderer(readerContext) {
290
  readerContext.applyPdfShellGeometry(() => {
291
  shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;
292
  shell.dataset.pageGeometry = "1";
293
- revealPdfSurface(shell, image, fade);
294
  readerContext.seedPdfPageGeometry?.(image.naturalWidth, image.naturalHeight);
295
  });
296
  // A speculative page may become visible while its image is loading.
@@ -468,7 +468,6 @@ export function createReaderPdfRenderer(readerContext) {
468
  renderPdfImageShell,
469
  renderPdfShell,
470
  applyPdfShellGeometry,
471
- revealPdfSurface,
472
  pdfSurfaceFades
473
  };
474
  }
 
198
  }
199
 
200
  // Reveal ordinary image pages only after decoding; respect reduced motion.
201
+ /** @param {HTMLElement} surface @param {boolean} fade */
202
+ function revealPdfSurface(surface, fade) {
203
  surface.classList.add("ready");
204
  if (fade && readerContext.capability?.mode === "image-pages")
205
  surface.animate?.([{ opacity: 0 }, { opacity: 1 }], { duration: 120, easing: "ease" });
 
290
  readerContext.applyPdfShellGeometry(() => {
291
  shell.style.aspectRatio = `${image.naturalWidth || 1} / ${image.naturalHeight || 1}`;
292
  shell.dataset.pageGeometry = "1";
293
+ revealPdfSurface(image, fade);
294
  readerContext.seedPdfPageGeometry?.(image.naturalWidth, image.naturalHeight);
295
  });
296
  // A speculative page may become visible while its image is loading.
 
468
  renderPdfImageShell,
469
  renderPdfShell,
470
  applyPdfShellGeometry,
 
471
  pdfSurfaceFades
472
  };
473
  }
static/reader/search/reader-dom-search.mjs CHANGED
@@ -346,8 +346,8 @@ export function createReaderDomSearch({
346
  return { label: boundaries[low - 1]?.label };
347
  };
348
  }
349
- /** @param {Node} node @param {string} fallback @param {number} offset @param {number} total @param {DomSearch.HeadingLookup | null} [headingLookup] @param {HTMLElement | null} [parent] */
350
- function fullSearchLocation(node, fallback, offset, total, headingLookup = null, parent = node.parentElement) {
351
  const page = parent && parent.closest("[data-page]");
352
  if (page) return `第 ${/** @type {HTMLElement} */ (page).dataset.page} 页`;
353
  const indexed = headingLookup?.(offset);
@@ -460,7 +460,7 @@ export function createReaderDomSearch({
460
  const resultFor = (match) => {
461
  const part = offsets[locateIndex(match.index)];
462
  return {
463
- location: part ? fullSearchLocation(part.node || part.parent, fallback, match.index, text.length, headingLookup, part.parent) : fallback,
464
  snippet: fullSearchSnippet(text, match.index, match.value.length),
465
  async activate(navigationGeneration = runtime.currentGeneration("navigation")) {
466
  if (!isCurrent("navigation", navigationGeneration)) return false;
 
346
  return { label: boundaries[low - 1]?.label };
347
  };
348
  }
349
+ /** @param {Node} node @param {number} offset @param {number} total @param {DomSearch.HeadingLookup | null} [headingLookup] @param {HTMLElement | null} [parent] */
350
+ function fullSearchLocation(node, offset, total, headingLookup = null, parent = node.parentElement) {
351
  const page = parent && parent.closest("[data-page]");
352
  if (page) return `第 ${/** @type {HTMLElement} */ (page).dataset.page} 页`;
353
  const indexed = headingLookup?.(offset);
 
460
  const resultFor = (match) => {
461
  const part = offsets[locateIndex(match.index)];
462
  return {
463
+ location: part ? fullSearchLocation(part.node || part.parent, match.index, text.length, headingLookup, part.parent) : fallback,
464
  snippet: fullSearchSnippet(text, match.index, match.value.length),
465
  async activate(navigationGeneration = runtime.currentGeneration("navigation")) {
466
  if (!isCurrent("navigation", navigationGeneration)) return false;
static/reader/search/reader-pdf-book-validate.mjs CHANGED
@@ -21,7 +21,8 @@ function validPage(page, index) {
21
  /** @param {string} text */
22
  function codePointLength(text) {
23
  let length = 0;
24
- for (const point of text) length++;
 
25
  return length;
26
  }
27
  /** @param {unknown} value @returns {value is number[]} */
 
21
  /** @param {string} text */
22
  function codePointLength(text) {
23
  let length = 0;
24
+ const points = text[Symbol.iterator]();
25
+ while (!points.next().done) length++;
26
  return length;
27
  }
28
  /** @param {unknown} value @returns {value is number[]} */
static/reader/search/reader-pdf-hit-projection.mjs CHANGED
@@ -4,7 +4,8 @@
4
  /** @param {string} text */
5
  export function codePointLength(text) {
6
  let length = 0;
7
- for (const point of text) length++;
 
8
  return length;
9
  }
10
 
 
4
  /** @param {string} text */
5
  export function codePointLength(text) {
6
  let length = 0;
7
+ const points = text[Symbol.iterator]();
8
+ while (!points.next().done) length++;
9
  return length;
10
  }
11
 
static/reader/ui/reader-speech.mjs CHANGED
@@ -46,7 +46,7 @@ function rootText(root) { return textNodes(root).map((node) => node.data).join("
46
  // every offset) identical: a break not after sentence punctuation becomes a space.
47
  /** @param {string} text */
48
  function spokenPageText(text) {
49
- return text.replace(/\n(?!\n)/g, (/** @type {string} */ match, /** @type {number} */ offset) => /[。!?!?;;::…”」』))\n]\s*$/u.test(text.slice(Math.max(0, offset - 2), offset)) ? "\n" : " ");
50
  }
51
 
52
  /** @param {Document} doc @param {number} x @param {number} y @param {ShadowRoot[]} roots */
@@ -556,8 +556,7 @@ export function createReaderSpeech(readerContext, loadPlayer) {
556
  } };
557
  }
558
 
559
- /** @param {import('../../../typings/reader-speech-strict').SpeechSource} info */
560
- function needsProbe(info) {
561
  const current = mode();
562
  if (current === "epub-chapters") return false;
563
  if (current === "pdf-pages" && (readerContext.ocrManifestUrl || readerContext.pdfOcrManifest)) return false;
@@ -623,7 +622,7 @@ export function createReaderSpeech(readerContext, loadPlayer) {
623
  if (!hasText()) return;
624
  const info = source();
625
  if (!info || info.units <= info.first) return;
626
- if (needsProbe(info)) { offerSource = info; offer(info); }
627
  else publish(createAdapter(info, info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first));
628
  /** @param {EventTarget | null | undefined} target @param {string} type @param {EventListener} handler @param {AddEventListenerOptions} [options] */
629
  const listen = (target, type, handler, options) => {
 
46
  // every offset) identical: a break not after sentence punctuation becomes a space.
47
  /** @param {string} text */
48
  function spokenPageText(text) {
49
+ return text.replace(/\n(?!\n)/g, (/** @type {string} */ _match, /** @type {number} */ offset) => /[。!?!?;;::…”」』))\n]\s*$/u.test(text.slice(Math.max(0, offset - 2), offset)) ? "\n" : " ");
50
  }
51
 
52
  /** @param {Document} doc @param {number} x @param {number} y @param {ShadowRoot[]} roots */
 
556
  } };
557
  }
558
 
559
+ function needsProbe() {
 
560
  const current = mode();
561
  if (current === "epub-chapters") return false;
562
  if (current === "pdf-pages" && (readerContext.ocrManifestUrl || readerContext.pdfOcrManifest)) return false;
 
622
  if (!hasText()) return;
623
  const info = source();
624
  if (!info || info.units <= info.first) return;
625
+ if (needsProbe()) { offerSource = info; offer(info); }
626
  else publish(createAdapter(info, info.units > 1 ? Math.max(info.first, (topPosition()?.unit ?? info.first) - 1) : info.first));
627
  /** @param {EventTarget | null | undefined} target @param {string} type @param {EventListener} handler @param {AddEventListenerOptions} [options] */
628
  const listen = (target, type, handler, options) => {
static/search/results/virtual/application/controller.js CHANGED
@@ -210,7 +210,6 @@ function ensureVirtualViewportCovered() {
210
  /** @param {number} [start] @param {number} [end] @param {{index: number, offset: number} | null} [anchor] */
211
  function measureHeights(start = VSCROLL.renderStart, end = VSCROLL.renderEnd, anchor = null) {
212
  if (VSCROLL.isDraggingThumb || start !== VSCROLL.renderStart || end !== VSCROLL.renderEnd) return false;
213
- const container = DOM.resultsContainer;
214
  const anchorIndex = anchor ? anchor.index : findVirtualIndex(getResultScrollTop());
215
  const anchorOffset = anchor ? anchor.offset : getResultScrollTop() - getVirtualOffset(anchorIndex);
216
  const rowMeasureKey = getHeightMeasurementKey();
 
210
  /** @param {number} [start] @param {number} [end] @param {{index: number, offset: number} | null} [anchor] */
211
  function measureHeights(start = VSCROLL.renderStart, end = VSCROLL.renderEnd, anchor = null) {
212
  if (VSCROLL.isDraggingThumb || start !== VSCROLL.renderStart || end !== VSCROLL.renderEnd) return false;
 
213
  const anchorIndex = anchor ? anchor.index : findVirtualIndex(getResultScrollTop());
214
  const anchorOffset = anchor ? anchor.offset : getResultScrollTop() - getVirtualOffset(anchorIndex);
215
  const rowMeasureKey = getHeightMeasurementKey();
static/search/results/window/domain/page.js CHANGED
@@ -1,10 +1,7 @@
1
  // Validation of a page against the search window's pinned generation.
2
  // Fetching, cancellation and committing results belong to the host.
3
  (function () {
4
- /**
5
- * @typedef {{results: unknown[], page: number, page_size: number, total: number, generation?: string | undefined}} Page
6
- * @typedef {{total: number, generation?: string | undefined}} Expected
7
- */
8
 
9
  /** @param {SearchResponsePage} data @param {number} page @param {number} pageSize */
10
  function invalidContents(data, page, pageSize) {
 
1
  // Validation of a page against the search window's pinned generation.
2
  // Fetching, cancellation and committing results belong to the host.
3
  (function () {
4
+ /** @typedef {{total: number, generation?: string | undefined}} Expected */
 
 
 
5
 
6
  /** @param {SearchResponsePage} data @param {number} page @param {number} pageSize */
7
  function invalidContents(data, page, pageSize) {
tests/gates/test_quality_inventory.py CHANGED
@@ -523,12 +523,14 @@ assert upstream.upstream_redirect_cache is replacement
523
  (self.root / "node_modules/typescript").symlink_to(compiler, target_is_directory=True)
524
  config_dir = self.root / "config/types"
525
  config_dir.mkdir(parents=True)
526
- (config_dir / "input.ts").write_text("const value = 1;\n")
527
  base = config_dir / "base.json"
528
  config = config_dir / "jsconfig.strict.json"
529
- config.write_text(json.dumps({"extends": "./base.json", "files": ["input.ts"]}))
 
530
  name = "config/types/jsconfig.strict.json"
531
- required = dict.fromkeys(REQUIRED_FRONTEND_FLAGS, True)
 
532
  for options, accepted in (({"strict": True}, True),
533
  ({"strictNullChecks": True, "noImplicitAny": True}, True),
534
  ({"strict": True, "strictNullChecks": False}, False),
@@ -537,22 +539,32 @@ assert upstream.upstream_redirect_cache is replacement
537
  with self.subTest(options=options):
538
  base.write_text(json.dumps({"compilerOptions": {**required, **options}}))
539
  if accepted:
540
- self.assertIn("config/types/input.ts", compiler_files(self.root, name, strict=True))
541
  else:
542
  with self.assertRaisesRegex(RuntimeError, "effective (strictNullChecks|noImplicitAny) must be enabled"):
543
  compiler_files(self.root, name, strict=True)
544
  # An inherited strict setting can also be overridden in the child.
545
- base.write_text(json.dumps({"compilerOptions": {"strict": True, **required}}))
546
- config.write_text(json.dumps({"extends": "./base.json", "files": ["input.ts"],
547
- "compilerOptions": {"noImplicitAny": False}}))
548
- with self.assertRaisesRegex(RuntimeError, "effective noImplicitAny must be enabled"):
549
- compiler_files(self.root, name, strict=True)
550
- for flag in REQUIRED_FRONTEND_FLAGS:
551
- with self.subTest(flag=flag):
552
- config.write_text(json.dumps({"extends": "./base.json", "files": ["input.ts"],
553
- "compilerOptions": {flag: False}}))
554
- with self.assertRaisesRegex(RuntimeError, f"effective {flag} must be enabled"):
 
555
  compiler_files(self.root, name, strict=True)
 
 
 
 
 
 
 
 
 
556
 
557
  def test_promoting_a_file_requires_removing_its_old_debt_entry(self):
558
  self.py_strict.add("backend/old.py")
 
523
  (self.root / "node_modules/typescript").symlink_to(compiler, target_is_directory=True)
524
  config_dir = self.root / "config/types"
525
  config_dir.mkdir(parents=True)
526
+ (config_dir / "input.js").write_text("const value = 1;\nconsole.log(value);\n")
527
  base = config_dir / "base.json"
528
  config = config_dir / "jsconfig.strict.json"
529
+ fixture = {"extends": "./base.json", "files": ["input.js"]}
530
+ config.write_text(json.dumps(fixture))
531
  name = "config/types/jsconfig.strict.json"
532
+ required = {**dict.fromkeys(REQUIRED_FRONTEND_FLAGS, True), "allowJs": True, "checkJs": True,
533
+ "noEmit": True, "moduleDetection": "force"}
534
  for options, accepted in (({"strict": True}, True),
535
  ({"strictNullChecks": True, "noImplicitAny": True}, True),
536
  ({"strict": True, "strictNullChecks": False}, False),
 
539
  with self.subTest(options=options):
540
  base.write_text(json.dumps({"compilerOptions": {**required, **options}}))
541
  if accepted:
542
+ self.assertIn("config/types/input.js", compiler_files(self.root, name, strict=True))
543
  else:
544
  with self.assertRaisesRegex(RuntimeError, "effective (strictNullChecks|noImplicitAny) must be enabled"):
545
  compiler_files(self.root, name, strict=True)
546
  # An inherited strict setting can also be overridden in the child.
547
+ strict_options = {"strict": True, **required}
548
+ base.write_text(json.dumps({"compilerOptions": strict_options}))
549
+ for option, value, message in (
550
+ ("noImplicitAny", False, "effective noImplicitAny must be enabled"),
551
+ ("moduleDetection", "legacy", "effective moduleDetection must be force"),
552
+ ("noCheck", True, "strict JavaScript checking must remain enabled"),
553
+ ("checkJs", False, "strict JavaScript checking must remain enabled"),
554
+ ):
555
+ with self.subTest(option=option):
556
+ config.write_text(json.dumps({**fixture, "compilerOptions": {option: value}}))
557
+ with self.assertRaisesRegex(RuntimeError, message):
558
  compiler_files(self.root, name, strict=True)
559
+ for flag in REQUIRED_FRONTEND_FLAGS:
560
+ without_flag = strict_options.copy()
561
+ del without_flag[flag]
562
+ for base_options, overrides in ((strict_options, {flag: False}), (without_flag, {})):
563
+ with self.subTest(flag=flag, overrides=overrides):
564
+ base.write_text(json.dumps({"compilerOptions": base_options}))
565
+ config.write_text(json.dumps({**fixture, "compilerOptions": overrides}))
566
+ with self.assertRaisesRegex(RuntimeError, f"effective {flag} must be enabled"):
567
+ compiler_files(self.root, name, strict=True)
568
 
569
  def test_promoting_a_file_requires_removing_its_old_debt_entry(self):
570
  self.py_strict.add("backend/old.py")
tests/gates/test_static_checks.py CHANGED
@@ -221,22 +221,35 @@ class StaticGateTests(unittest.TestCase):
221
  ("noImplicitReturns", "TS7030", """
222
  /** @param {boolean} active */
223
  function readCount(active) { if (active) return 1; }
 
224
  """),
225
  ("noImplicitOverride", "TS4119", """
226
  class BaseProbe { clear() {} }
227
  class CacheProbe extends BaseProbe { clear() {} }
 
228
  """),
229
  ("noFallthroughCasesInSwitch", "TS7029", """
230
  /** @param {number} value */
231
  function update(value) { switch (value) { case 0: value++; case 1: break; } }
 
232
  """),
233
  ("noUncheckedIndexedAccess", "TS2322", """
234
  /** @param {string[]} values @returns {string} */
235
  function firstValue(values) { return values[0]; }
 
236
  """),
237
  ("exactOptionalPropertyTypes", "TS2375", """
238
  /** @type {{signal?: AbortSignal}} */
239
  const options = {signal: undefined};
 
 
 
 
 
 
 
 
 
240
  """),
241
  )
242
  source = self.root / "static/strict-options-probe.js"
 
221
  ("noImplicitReturns", "TS7030", """
222
  /** @param {boolean} active */
223
  function readCount(active) { if (active) return 1; }
224
+ readCount(true);
225
  """),
226
  ("noImplicitOverride", "TS4119", """
227
  class BaseProbe { clear() {} }
228
  class CacheProbe extends BaseProbe { clear() {} }
229
+ new CacheProbe().clear();
230
  """),
231
  ("noFallthroughCasesInSwitch", "TS7029", """
232
  /** @param {number} value */
233
  function update(value) { switch (value) { case 0: value++; case 1: break; } }
234
+ update(0);
235
  """),
236
  ("noUncheckedIndexedAccess", "TS2322", """
237
  /** @param {string[]} values @returns {string} */
238
  function firstValue(values) { return values[0]; }
239
+ firstValue(["ok"]);
240
  """),
241
  ("exactOptionalPropertyTypes", "TS2375", """
242
  /** @type {{signal?: AbortSignal}} */
243
  const options = {signal: undefined};
244
+ console.log(options);
245
+ """),
246
+ ("noUnusedLocals", "TS6133: 'unusedBinding'", """
247
+ const unusedBinding = 1;
248
+ """),
249
+ ("noUnusedParameters", "TS6133: 'unusedParameter'", """
250
+ /** @param {number} value @param {number} unusedParameter */
251
+ function keepValue(value, unusedParameter) { return value; }
252
+ keepValue(1, 2);
253
  """),
254
  )
255
  source = self.root / "static/strict-options-probe.js"
tests/gates/test_static_contract.py CHANGED
@@ -662,7 +662,8 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
662
  chapter = (ROOT / "static/reader/formats/reader-chapter-format.mjs").read_text(encoding="utf-8")
663
  reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")
664
  assert_source_contains(self, 'readerContext.trustedChapterReferenceUrl(value, url, manifestBase)', chapter)
665
- assert_source_contains(self, 'const resolved = resourceUrl(value, url, name === "href" ? "href" : "resource")', chapter)
 
666
  assert_source_contains(self, 'element.removeAttribute(name)', chapter)
667
  self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:")
668
 
@@ -945,7 +946,7 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
945
 
946
  def test_result_rows_use_three_line_desktop_layout_and_equal_action_heights(self):
947
  self.assertRegex(self.result_rows, r'class="result-title"[\s\S]*class="result-path"[\s\S]*class="result-meta"')
948
- self.assertIn('function buildResultHTML(rec, idx) { return getResultRows().buildHTML(rec, idx); }', self.js)
949
  self.assertIn("body:not(.mobile) .result-title { grid-column: 3; grid-row: 1;", self.css)
950
  self.assertIn("body:not(.mobile) .result-path { grid-column: 3 / 5; grid-row: 2;", self.css)
951
  self.assertIn("body:not(.mobile) .result-meta { grid-column: 3 / 5; grid-row: 3;", self.css)
 
662
  chapter = (ROOT / "static/reader/formats/reader-chapter-format.mjs").read_text(encoding="utf-8")
663
  reader_html = (ROOT / "static/reader.html").read_text(encoding="utf-8")
664
  assert_source_contains(self, 'readerContext.trustedChapterReferenceUrl(value, url, manifestBase)', chapter)
665
+ assert_source_contains(self, 'const resolved = resourceUrl(value, url)', chapter)
666
+ assert_source_contains(self, 'trustedChapterResourceUrl(value, base, manifestBase)', chapter)
667
  assert_source_contains(self, 'element.removeAttribute(name)', chapter)
668
  self.assertRegex(reader_html, r"connect-src[^\"]*\bblob:")
669
 
 
946
 
947
  def test_result_rows_use_three_line_desktop_layout_and_equal_action_heights(self):
948
  self.assertRegex(self.result_rows, r'class="result-title"[\s\S]*class="result-path"[\s\S]*class="result-meta"')
949
+ self.assertIn('function createResultRow(rec, idx) { return getResultRows().createRow(rec, idx); }', self.js)
950
  self.assertIn("body:not(.mobile) .result-title { grid-column: 3; grid-row: 1;", self.css)
951
  self.assertIn("body:not(.mobile) .result-path { grid-column: 3 / 5; grid-row: 2;", self.css)
952
  self.assertIn("body:not(.mobile) .result-meta { grid-column: 3 / 5; grid-row: 3;", self.css)
tests/reader/browser/test_reader_host_history_races.py CHANGED
@@ -223,7 +223,7 @@ class ReaderHostHistoryRaceTests(unittest.TestCase):
223
  self.page.evaluate('''async url => {
224
  history.replaceState(null, '', url);
225
  await persistSearchSession();
226
- const db = await openSearchSessionDB();
227
  const saved = await new Promise((resolve, reject) => {
228
  const request = db.transaction('session', 'readonly').objectStore('session').get('last-search');
229
  request.onsuccess = () => resolve(request.result);
@@ -296,9 +296,14 @@ class ReaderHostHistoryRaceTests(unittest.TestCase):
296
  self.page.wait_for_timeout(10)
297
  self.assertEqual(len(held), 1)
298
  route = held.pop()
299
- route.fulfill(response=route.fetch())
 
 
 
 
 
300
  self.page.unroute(pattern, hold_app)
301
- self.page.wait_for_function('typeof searchInputReady !== "undefined" && searchInputReady')
302
  self.assertFalse(field.evaluate('input => "_earlySearchInput" in input'))
303
  self.assertEqual(self.page.evaluate('searchComposing'), mode == 'spanning')
304
  current_query = 'paging-before-bind-B' if navigate else 'paging-before-bind'
 
223
  self.page.evaluate('''async url => {
224
  history.replaceState(null, '', url);
225
  await persistSearchSession();
226
+ const db = await searchSession.openSearchSessionDB();
227
  const saved = await new Promise((resolve, reject) => {
228
  const request = db.transaction('session', 'readonly').objectStore('session').get('last-search');
229
  request.onsuccess = () => resolve(request.result);
 
296
  self.page.wait_for_timeout(10)
297
  self.assertEqual(len(held), 1)
298
  route = held.pop()
299
+ response = route.fetch()
300
+ source = response.text()
301
+ startup = 'finishInitialSearchInput(initialDraftCurrent);'
302
+ self.assertEqual(source.count(startup), 1)
303
+ route.fulfill(response=response, body=source.replace(
304
+ startup, startup + ' window.__testSearchInputReady = true;'))
305
  self.page.unroute(pattern, hold_app)
306
+ self.page.wait_for_function('window.__testSearchInputReady === true')
307
  self.assertFalse(field.evaluate('input => "_earlySearchInput" in input'))
308
  self.assertEqual(self.page.evaluate('searchComposing'), mode == 'spanning')
309
  current_query = 'paging-before-bind-B' if navigate else 'paging-before-bind'
tests/reader/browser/test_reader_navigation_host.py CHANGED
@@ -110,7 +110,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
110
  self.assertEqual(current.evaluate('''() => [formatSize(0), formatSize(1023), formatSize(1024),
111
  formatSize(1048576), formatSize(1073741824)]'''), ['', '1023 B', '1.0 KB', '1.0 MB', '1.00 GB'])
112
  row = current.evaluate('''() => {
113
- const html = buildResultHTML({Repo:'VoiceOfML/Test', File:'size', Extension:'txt', Folder:[], Size:1536}, 0);
114
  const node = document.createElement('div'); node.innerHTML = html;
115
  return node.textContent.includes('1.5 KB');
116
  }''')
@@ -527,7 +527,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
527
  {name:'poster.jpg',ext:'jpg',size:1}, {name:'normal',ext:'jpg',size:1},
528
  {name:'book.PDF',ext:'pdf',size:1}, {name:'README',ext:'',size:1}];
529
  const list=document.createElement('div');list.className='browser-list';DOM.sidebarContent.append(list);
530
- renderBrowserListItems(list,{folders:[],files},repo,folder);
531
  return [...list.querySelectorAll('.browser-item')].map(row=>({filename:row.dataset.filename,
532
  link:decodeURIComponent(new URL(row.dataset.link).pathname),
533
  reader:row.dataset.readUrl ? new URL(row.dataset.readUrl,location.href).searchParams.get('id') : null}));
@@ -763,7 +763,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
763
  releaseBody({url:'https://source.test/stale'});
764
  await new Promise(resolve=>setTimeout(resolve,0));
765
  const stale=sessionStorage.getItem('reader-resolve:warm-hover');
766
- const slot=readerWarmupInFlight;
767
  calls[1].resolve({ok:true,json:async()=>({url:'https://source.test/click'})});
768
  await new Promise(resolve=>setTimeout(resolve,0));
769
  const cached=JSON.parse(sessionStorage.getItem('reader-resolve:warm-click') || 'null');
@@ -775,7 +775,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
775
  await new Promise(resolve=>setTimeout(resolve,0));
776
  return {before,replaced,stale,slot,cached:cached?.url,keyboardReplaced,
777
  keyboard:JSON.parse(sessionStorage.getItem('reader-resolve:warm-keyboard') || 'null')?.url,
778
- active:readerWarmupInFlight,errors};
779
  } finally {
780
  cancelReaderWarmup();window.fetch=originalFetch;window.removeEventListener('unhandledrejection',handler);
781
  hover.remove();click.remove();keyboard.remove();history.replaceState(null,'',savedUrl);
@@ -876,7 +876,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
876
  self.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())
877
  self.assertEqual(len(lookups),1)
878
  self.page.evaluate('''url=>__lateCalls[1].resolve({ok:true,json:async()=>({url,extension:'txt'})})''', source)
879
- self.page.wait_for_function('readerWarmupInFlight === 0')
880
  self.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())
881
  self.assertEqual(len(lookups),1)
882
  finally:
@@ -1044,7 +1044,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8'
1044
  STATE.useMirrorLinks=false; DOM.sortSelect.value='size';
1045
  let target=new URL('/Test?folder_self=docs', location.origin);
1046
  target=readerNavigation.mergeSearchParams(target, buildSearchURLParams(), {
1047
- keys: READER_RETURN_SEARCH_KEYS
1048
  });
1049
  return Object.fromEntries(target.searchParams);
1050
  }''')
 
110
  self.assertEqual(current.evaluate('''() => [formatSize(0), formatSize(1023), formatSize(1024),
111
  formatSize(1048576), formatSize(1073741824)]'''), ['', '1023 B', '1.0 KB', '1.0 MB', '1.00 GB'])
112
  row = current.evaluate('''() => {
113
+ const html = getResultRows().buildHTML({Repo:'VoiceOfML/Test', File:'size', Extension:'txt', Folder:[], Size:1536}, 0);
114
  const node = document.createElement('div'); node.innerHTML = html;
115
  return node.textContent.includes('1.5 KB');
116
  }''')
 
527
  {name:'poster.jpg',ext:'jpg',size:1}, {name:'normal',ext:'jpg',size:1},
528
  {name:'book.PDF',ext:'pdf',size:1}, {name:'README',ext:'',size:1}];
529
  const list=document.createElement('div');list.className='browser-list';DOM.sidebarContent.append(list);
530
+ getSidebarDirectoryView().items(list,{folders:[],files},repo,folder);
531
  return [...list.querySelectorAll('.browser-item')].map(row=>({filename:row.dataset.filename,
532
  link:decodeURIComponent(new URL(row.dataset.link).pathname),
533
  reader:row.dataset.readUrl ? new URL(row.dataset.readUrl,location.href).searchParams.get('id') : null}));
 
763
  releaseBody({url:'https://source.test/stale'});
764
  await new Promise(resolve=>setTimeout(resolve,0));
765
  const stale=sessionStorage.getItem('reader-resolve:warm-hover');
766
+ const slot=Number(!!readerWarmupPending);
767
  calls[1].resolve({ok:true,json:async()=>({url:'https://source.test/click'})});
768
  await new Promise(resolve=>setTimeout(resolve,0));
769
  const cached=JSON.parse(sessionStorage.getItem('reader-resolve:warm-click') || 'null');
 
775
  await new Promise(resolve=>setTimeout(resolve,0));
776
  return {before,replaced,stale,slot,cached:cached?.url,keyboardReplaced,
777
  keyboard:JSON.parse(sessionStorage.getItem('reader-resolve:warm-keyboard') || 'null')?.url,
778
+ active:Number(!!readerWarmupPending),errors};
779
  } finally {
780
  cancelReaderWarmup();window.fetch=originalFetch;window.removeEventListener('unhandledrejection',handler);
781
  hover.remove();click.remove();keyboard.remove();history.replaceState(null,'',savedUrl);
 
876
  self.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())
877
  self.assertEqual(len(lookups),1)
878
  self.page.evaluate('''url=>__lateCalls[1].resolve({ok:true,json:async()=>({url,extension:'txt'})})''', source)
879
+ self.page.wait_for_function('!readerWarmupPending')
880
  self.assertIn('Reader independent of delayed warmup',frame.locator('.reader-text').inner_text())
881
  self.assertEqual(len(lookups),1)
882
  finally:
 
1044
  STATE.useMirrorLinks=false; DOM.sortSelect.value='size';
1045
  let target=new URL('/Test?folder_self=docs', location.origin);
1046
  target=readerNavigation.mergeSearchParams(target, buildSearchURLParams(), {
1047
+ keys: readerHost.keys
1048
  });
1049
  return Object.fromEntries(target.searchParams);
1050
  }''')
tests/reader/browser/test_reader_pdf_first_page.py CHANGED
@@ -709,11 +709,11 @@ class PdfFirstPageTests(unittest.TestCase):
709
  page=context.new_page();attempts=[]
710
  def fail_once(route):
711
  response=route.fetch();script=response.text()
712
- needle='return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document")'
713
  self.assertIn(needle,script)
714
  script=script.replace(needle,'''return readerContext.measurePdf(stagedWorker
715
  ? Promise.reject(new Error("injected staged parser failure"))
716
- : readerContext.loadPdfWithTimeout(pdfjs, options, target, proxyUrl, takeInitial), "document")''')
717
  route.fulfill(response=response,body=script)
718
  page.route('**/static/reader/pdf/reader-pdf-engine.mjs*',fail_once)
719
  page.on('request',lambda req:attempts.append(req.url) if 'pdf-worker-wrapper.mjs' in req.url else None)
 
709
  page=context.new_page();attempts=[]
710
  def fail_once(route):
711
  response=route.fetch();script=response.text()
712
+ needle='return readerContext.measurePdf(readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial), "document")'
713
  self.assertIn(needle,script)
714
  script=script.replace(needle,'''return readerContext.measurePdf(stagedWorker
715
  ? Promise.reject(new Error("injected staged parser failure"))
716
+ : readerContext.loadPdfWithTimeout(pdfjs, options, proxyUrl, takeInitial), "document")''')
717
  route.fulfill(response=response,body=script)
718
  page.route('**/static/reader/pdf/reader-pdf-engine.mjs*',fail_once)
719
  page.on('request',lambda req:attempts.append(req.url) if 'pdf-worker-wrapper.mjs' in req.url else None)
tests/reader/browser/test_reader_refactor.py CHANGED
@@ -2648,7 +2648,7 @@ class ReaderRefactorTest(unittest.TestCase):
2648
  const page = part.node.parentElement.closest('[data-page]');
2649
  const expected = page ? '第 ' + page.dataset.page + ' 页' :
2650
  heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';
2651
- return [window.__domSearchTools.location(part.node, '', part.start, length, lookup), expected];
2652
  });
2653
  const pairs = compare();
2654
  setToc([...navigationState.tocEntries].reverse());
 
2648
  const page = part.node.parentElement.closest('[data-page]');
2649
  const expected = page ? '第 ' + page.dataset.page + ' 页' :
2650
  heading ? heading.label : '正文 ' + Math.min(100, Math.floor(part.start / Math.max(1,length) * 100)) + '%';
2651
+ return [window.__domSearchTools.location(part.node, part.start, length, lookup), expected];
2652
  });
2653
  const pairs = compare();
2654
  setToc([...navigationState.tocEntries].reverse());
tests/reader/chapters/test_chapter_format_validation.mjs CHANGED
@@ -1,6 +1,7 @@
1
  import assert from 'node:assert/strict';
2
  import { readFileSync } from 'node:fs';
3
  import vm from 'node:vm';
 
4
  import { createChapterProgress, createReaderChapterFormat, chapterPrefetchSize, isChapterSearchIndex } from '../../../static/reader/formats/reader-chapter-format.mjs';
5
 
6
  const sandbox = {};
@@ -57,4 +58,95 @@ const context = {
57
  const chapters = [{index:1,path:'1.html',title:{html:'<img onerror=alert(1)>'},source_path:{toString(){throw Error('coercion');}}}, {index:2,path:'2.html',title:'正常'}];
58
  await assert.rejects(createReaderChapterFormat(context).renderChapterManifest(new Response(JSON.stringify({version:1,kind:'epub-chapters',chapters}))), /stop/);
59
  assert.deepEqual(toc.map(item=>item.label), ['章节 1','正常']);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  console.log('chapter metadata validation and prefetch sizes passed');
 
1
  import assert from 'node:assert/strict';
2
  import { readFileSync } from 'node:fs';
3
  import vm from 'node:vm';
4
+ import { createReaderSource } from '../../../static/reader/core/reader-source.mjs';
5
  import { createChapterProgress, createReaderChapterFormat, chapterPrefetchSize, isChapterSearchIndex } from '../../../static/reader/formats/reader-chapter-format.mjs';
6
 
7
  const sandbox = {};
 
58
  const chapters = [{index:1,path:'1.html',title:{html:'<img onerror=alert(1)>'},source_path:{toString(){throw Error('coercion');}}}, {index:2,path:'2.html',title:'正常'}];
59
  await assert.rejects(createReaderChapterFormat(context).renderChapterManifest(new Response(JSON.stringify({version:1,kind:'epub-chapters',chapters}))), /stop/);
60
  assert.deepEqual(toc.map(item=>item.label), ['章节 1','正常']);
61
+ // Drive the actual click handler and trusted URL resolvers. Stub layout and
62
+ // speculative loading so the resolution counts don't depend on timing.
63
+ vm.runInNewContext(readFileSync(new URL('../../../static/reader/core/reader-contract.js', import.meta.url), 'utf8'), sandbox);
64
+ globalThis.VoiceOfMLReader = sandbox.VoiceOfMLReader;
65
+ const source = {};
66
+ Object.assign(source, createReaderSource(source));
67
+ const resolved = [], landings = [], articles = new Map();
68
+ let click;
69
+ globalThis.document.createElement = (tag) => {
70
+ const node = {style:{}, dataset:{}, appendChild(){}, addEventListener(){}, setAttribute(){}, querySelectorAll:()=>[]};
71
+ if (tag === 'article') node.querySelector = function (selector) { return [Number(this.dataset.chapter), selector]; };
72
+ if (tag === 'div') Object.assign(node, {
73
+ addEventListener(type, listener) { assert.equal(type, 'click'); click = listener; },
74
+ querySelector: selector => articles.get(selector) || null,
75
+ insertBefore(article) {
76
+ if (article.className === 'reader-markdown reader-epub-chapter')
77
+ articles.set(`.reader-epub-chapter[data-chapter="${article.dataset.chapter}"]`, article);
78
+ }
79
+ });
80
+ return node;
81
+ };
82
+ globalThis.document.removeEventListener = globalThis.window.removeEventListener = () => {};
83
+ globalThis.IntersectionObserver.prototype.disconnect = () => {};
84
+ globalThis.requestAnimationFrame = () => 1;
85
+ globalThis.cancelAnimationFrame = () => {};
86
+ globalThis.CSS = {escape: value => value};
87
+ globalThis.VoiceOfMLReaderChapters.createChapterScheduler = ({create}) => ({
88
+ load: index => create(index, new AbortController().signal, 'high'), prefetch(){}, dispose(){}
89
+ });
90
+ globalThis.VoiceOfMLReaderVirtual.createSectionVirtualizer = () => ({dispose(){}});
91
+ const linkContext = {
92
+ ...context, ...source, status:{}, readerAbortController:new AbortController(),
93
+ viewport:{addEventListener(){}, removeEventListener(){}}, readerRestorationEntry:{chapterIndex:4},
94
+ trustedChapterUrl(path, base) { resolved.push(path); return source.trustedChapterUrl(path, base); },
95
+ fetchReaderUrl: async () => new Response(''), parseChapterDocument: () => ({querySelectorAll:()=>[]}),
96
+ chapterScrollAnchors:{preserve: change => change(), observe(){}, invalidate(){}, remember(){}, whenIdle(){}},
97
+ getInitialReaderRestoration: async () => {}, awaitReader: promise => promise, setToc: () => [],
98
+ beginReaderNavigation: () => 1, isReaderGenerationCurrent: () => true,
99
+ alignReaderDestination: anchor => landings.push(anchor), holdReaderDestination(){},
100
+ syncHeadingLocation(){}, updateProgressTools(){}, scheduleSave(){}, markReaderContentReady(){},
101
+ reportNavigationError(error) { throw error; }
102
+ };
103
+ const format = createReaderChapterFormat(linkContext);
104
+ const chapterPath = index => `chapters/chapter-${String(index).padStart(4, '0')}.xhtml`;
105
+ const linkChapters = Array.from({length:64}, (_, i) => ({index:i + 1, path:chapterPath(i + 1)}));
106
+ linkChapters[1].path = 'chapters/invalid.xhtml'; // Valid manifest metadata, but not a trusted chapter URL.
107
+ linkChapters[2].path = 'chapters/chapter-000%34.xhtml'; // Same resolved URL as the restored chapter 4.
108
+ const paths = linkChapters.map(chapter => chapter.path);
109
+ async function openBook(identity) {
110
+ const prefix = `chapters/ebook/epub/${identity.repeat(64)}/${'a'.repeat(16)}/`;
111
+ linkContext.chapterManifestUrl = `https://voiceofml-search.hf.space/api/reader-bucket-resource?path=${encodeURIComponent(prefix + 'chapter-manifest.json')}`;
112
+ resolved.length = 0;
113
+ articles.clear();
114
+ await format.renderChapterManifest(new Response(JSON.stringify({version:1, kind:'epub-chapters', chapters:linkChapters})));
115
+ assert.deepEqual(resolved, [chapterPath(4)], 'opening only resolves the loaded chapter path');
116
+ }
117
+ async function follow(href, chapterIndex, fragment) {
118
+ const article = articles.get('.reader-epub-chapter[data-chapter="4"]');
119
+ let prevented = false, error;
120
+ const link = {closest:()=>article, getAttribute:()=>href, after: node => { error = node; }};
121
+ landings.length = 0;
122
+ await click({button:0, target:{closest:()=>link}, preventDefault(){ prevented = true; }});
123
+ assert.equal(prevented, true);
124
+ assert.equal(error?.className, chapterIndex ? undefined : 'reader-chapter-link-error');
125
+ assert.deepEqual(landings, chapterIndex ? [[chapterIndex, `[id="${fragment}"], [name="${fragment}"]`]] : []);
126
+ }
127
+
128
+ await openBook('b');
129
+ try {
130
+ await follow('https://example.test/chapter-0004.xhtml#external');
131
+ assert.equal(resolved.length, 1, 'a rejected reference does not start the scan');
132
+ await follow('./chapter-0004.xhtml#%E7%9B%AE%E6%A0%87', 3, '目标');
133
+ assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3)], 'stop at the first canonical match');
134
+ await follow('chapter-0004.xhtml#again', 3, 'again');
135
+ assert.equal(resolved.length, 4, 'repeated hit does not parse chapter paths again');
136
+ await follow('chapter-0050.xhtml#late', 50, 'late');
137
+ assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3), ...paths.slice(4, 50)], 'resume the prefix and reuse the fetch URL');
138
+ await follow('chapter-0004.xhtml#first', 3, 'first');
139
+ assert.equal(resolved.length, 50, 'the later duplicate did not replace the first match');
140
+ await follow('chapter-0002.xhtml#missing');
141
+ assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3), ...paths.slice(4)], 'a miss scans only the remaining suffix');
142
+ await follow('chapter-0002.xhtml#missing');
143
+ await follow('chapter-0099.xhtml#another-miss');
144
+ assert.equal(resolved.length, paths.length, 'after exhaustion no miss parses another chapter path');
145
+ } finally { linkContext.chapterManifestCleanup(); }
146
+
147
+ await openBook('c');
148
+ try {
149
+ await follow('chapter-0004.xhtml#new-book', 3, 'new-book');
150
+ assert.deepEqual(resolved, [paths[3], ...paths.slice(0, 3)], 'a new manifest starts with a fresh cache and cursor');
151
+ } finally { linkContext.chapterManifestCleanup(); }
152
  console.log('chapter metadata validation and prefetch sizes passed');
tests/reader/core/test_reader_warming.js CHANGED
@@ -100,14 +100,14 @@ function fixture(simd = true) {
100
  assert.strictEqual(first.url,'/api/reader-resolve?id=one');
101
  first.resolve({ok:true,json:()=>new Promise(()=>{})});await tick();
102
  for(const timer of [...f.timers.values()])timer();await tick();
103
- assert.strictEqual(f.run('readerWarmupInFlight'),0,'stalled JSON must release the warming slot');
104
  assert.ok(first.options.signal.aborted);
105
  assert.strictEqual(f.run('warmedReaderSources.size'),0);
106
  f.run('warmReaderIntent("/reader?id=one&ext=txt")');
107
  assert.strictEqual(f.calls.filter(call=>call.url.includes('reader-resolve')).length,1,'failure must back off');
108
  f.advance();f.run('warmReaderIntent("/reader?id=one&ext=txt")');
109
  f.calls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/book'})});await tick();
110
- assert.strictEqual(f.run('readerWarmupInFlight'),0);
111
  assert.ok(f.stored.has('reader-resolve:one'));
112
  assert.strictEqual(f.run('warmedReaderSources.size'),1);
113
  console.log('reader warming: whole-body deadline, coalescing, backoff and successful retry passed');
@@ -115,7 +115,7 @@ function fixture(simd = true) {
115
  for(const response of [{ok:false},{ok:true,json:async()=>({error:'bad'})}]) {
116
  const t=fixture();t.run('warmReaderIntent("/reader?id=bad&ext=txt")');
117
  t.calls.find(call=>call.url.includes('reader-resolve')).resolve(response);await tick();
118
- assert.strictEqual(t.run('warmedReaderSources.size'),0);assert.strictEqual(t.run('readerWarmupInFlight'),0);
119
  }
120
  for(const event of ['pagehide','offline','visibilitychange']) {
121
  const t=fixture();t.run('warmReaderIntent("/reader?id=old&ext=txt")');
@@ -124,7 +124,7 @@ function fixture(simd = true) {
124
  if(event==='visibilitychange')t.context.document.hidden=true;
125
  t.events[event]();await tick();assert.ok(pending.options.signal.aborted);
126
  resolveBody({url:'https://source.test/stale'});await tick();assert.strictEqual(t.stored.size,0);
127
- assert.strictEqual(t.run('readerWarmupInFlight'),0);
128
  }
129
  const t=fixture();t.context.document.hidden=true;t.run('warmReaderIntent("/reader?id=x")');
130
  t.context.document.hidden=false;t.context.navigator.onLine=false;t.run('warmReaderIntent("/reader?id=x")');
@@ -164,11 +164,11 @@ function fixture(simd = true) {
164
  const next=resolverCalls(priority)[1];
165
  assert.ok(old.options.signal.aborted,'active intent must abort the previous speculative request');
166
  assert.ok(next.url.endsWith('id=new'));
167
- assert.strictEqual(priority.run('readerWarmupInFlight'),1);
168
  assert.strictEqual(priority.run('readerWarmupRetryAt.size'),0,'superseded work is not a failure');
169
  finishOld({url:'https://source.test/stale'});await tick();
170
  assert.strictEqual(priority.stored.has('reader-resolve:old'),false,'late old JSON cannot enter cache');
171
- assert.strictEqual(priority.run('readerWarmupInFlight'),1,'late completion cannot release new task');
172
  next.resolve({ok:true,json:async()=>({url:'https://source.test/new'})});await tick();
173
  assert.ok(priority.stored.has('reader-resolve:new'));
174
  emitIntent(priority,'pointerover','old');
@@ -180,7 +180,7 @@ function fixture(simd = true) {
180
  emitIntent(priority,'pointerdown','download',true);
181
  assert.strictEqual(resolverCalls(priority).length,4,'download actions never preempt');
182
  priority.events.offline();await tick();
183
- assert.strictEqual(priority.run('readerWarmupInFlight'),0);
184
  assert.ok(priority.run('readerWarmupRetryAt.has("id:keyboard")'),'offline cancellation retains backoff');
185
 
186
  const reentrant=fixture();
@@ -195,7 +195,7 @@ function fixture(simd = true) {
195
  assert.ok(owner.options.signal.aborted && reentrantCalls[1].url.endsWith('id=reentrant'));
196
  assert.strictEqual(reentrant.run('readerWarmupPending.key'),'id:reentrant');
197
  reentrantCalls[1].resolve({ok:true,json:async()=>({url:'https://source.test/reentrant'})});await tick();
198
- assert.strictEqual(reentrant.run('readerWarmupInFlight'),0);
199
 
200
  const rapid=fixture();
201
  emitIntent(rapid,'pointerover','rapid0');
@@ -204,12 +204,12 @@ function fixture(simd = true) {
204
  assert.strictEqual(rapidCalls.length,21);
205
  assert.ok(rapidCalls.slice(0,-1).every(call=>call.options.signal.aborted));
206
  assert.ok(!rapidCalls.at(-1).options.signal.aborted);
207
- assert.strictEqual(rapid.run('readerWarmupInFlight'),1);
208
  assert.strictEqual(rapid.run('readerWarmupRetryAt.size'),0);
209
  rapidCalls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/final'})});
210
  await tick();
211
  assert.ok(rapid.stored.has('reader-resolve:rapid20'));
212
- assert.strictEqual(rapid.run('readerWarmupInFlight'),0);
213
 
214
  const sources=fixture();
215
  sources.run(`warmReaderIntent('/reader?url=https://source.test/hover');
@@ -219,7 +219,7 @@ function fixture(simd = true) {
219
  assert.ok(heads[0].options.signal.aborted);
220
  assert.ok(heads[1].url.includes(encodeURIComponent('https://source.test/activate')));
221
  heads[1].resolve({ok:true});await tick();
222
- assert.strictEqual(sources.run('readerWarmupInFlight'),0);
223
  assert.strictEqual(sources.run('warmedReaderSources.size'),1);
224
 
225
  const capacity=fixture();
@@ -235,7 +235,7 @@ function fixture(simd = true) {
235
  await tick();
236
  assert.strictEqual(capacity.run('readerWarmupPending.key'),'id:limit','old rejection cannot release the urgent owner');
237
  resolverCalls(capacity).at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/limit'})});await tick();
238
- assert.strictEqual(capacity.run('readerWarmupInFlight'),0);
239
  assert.strictEqual(capacity.run('warmedReaderSources.size'),8);
240
 
241
  const timeout=fixture();
@@ -244,7 +244,7 @@ function fixture(simd = true) {
244
  // Such a callback argument must not accidentally mark a timeout superseded.
245
  for (const timer of [...timeout.timers.values()]) timer({simulatedTimer:true});
246
  await tick();
247
- assert.strictEqual(timeout.run('readerWarmupInFlight'),0);
248
  assert.ok(timeout.run('readerWarmupRetryAt.has("id:timed-out")'));
249
 
250
  const previous=fixture();
@@ -255,7 +255,7 @@ function fixture(simd = true) {
255
  emitIntent(previous,'pointerdown','failed');
256
  assert.ok(busy.options.signal.aborted,'even a backed-off target should cancel unrelated speculation');
257
  assert.strictEqual(resolverCalls(previous).length,2,'priority does not bypass retry backoff');
258
- assert.strictEqual(previous.run('readerWarmupInFlight'),0);
259
  previous.advance();emitIntent(previous,'focusin','failed');
260
  assert.strictEqual(resolverCalls(previous).length,3);
261
  resolverCalls(previous)[2].resolve({ok:true,json:async()=>({url:'https://source.test/failed'})});await tick();
 
100
  assert.strictEqual(first.url,'/api/reader-resolve?id=one');
101
  first.resolve({ok:true,json:()=>new Promise(()=>{})});await tick();
102
  for(const timer of [...f.timers.values()])timer();await tick();
103
+ assert.strictEqual(f.run('Number(!!readerWarmupPending)'),0,'stalled JSON must release the warming slot');
104
  assert.ok(first.options.signal.aborted);
105
  assert.strictEqual(f.run('warmedReaderSources.size'),0);
106
  f.run('warmReaderIntent("/reader?id=one&ext=txt")');
107
  assert.strictEqual(f.calls.filter(call=>call.url.includes('reader-resolve')).length,1,'failure must back off');
108
  f.advance();f.run('warmReaderIntent("/reader?id=one&ext=txt")');
109
  f.calls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/book'})});await tick();
110
+ assert.strictEqual(f.run('Number(!!readerWarmupPending)'),0);
111
  assert.ok(f.stored.has('reader-resolve:one'));
112
  assert.strictEqual(f.run('warmedReaderSources.size'),1);
113
  console.log('reader warming: whole-body deadline, coalescing, backoff and successful retry passed');
 
115
  for(const response of [{ok:false},{ok:true,json:async()=>({error:'bad'})}]) {
116
  const t=fixture();t.run('warmReaderIntent("/reader?id=bad&ext=txt")');
117
  t.calls.find(call=>call.url.includes('reader-resolve')).resolve(response);await tick();
118
+ assert.strictEqual(t.run('warmedReaderSources.size'),0);assert.strictEqual(t.run('Number(!!readerWarmupPending)'),0);
119
  }
120
  for(const event of ['pagehide','offline','visibilitychange']) {
121
  const t=fixture();t.run('warmReaderIntent("/reader?id=old&ext=txt")');
 
124
  if(event==='visibilitychange')t.context.document.hidden=true;
125
  t.events[event]();await tick();assert.ok(pending.options.signal.aborted);
126
  resolveBody({url:'https://source.test/stale'});await tick();assert.strictEqual(t.stored.size,0);
127
+ assert.strictEqual(t.run('Number(!!readerWarmupPending)'),0);
128
  }
129
  const t=fixture();t.context.document.hidden=true;t.run('warmReaderIntent("/reader?id=x")');
130
  t.context.document.hidden=false;t.context.navigator.onLine=false;t.run('warmReaderIntent("/reader?id=x")');
 
164
  const next=resolverCalls(priority)[1];
165
  assert.ok(old.options.signal.aborted,'active intent must abort the previous speculative request');
166
  assert.ok(next.url.endsWith('id=new'));
167
+ assert.strictEqual(priority.run('Number(!!readerWarmupPending)'),1);
168
  assert.strictEqual(priority.run('readerWarmupRetryAt.size'),0,'superseded work is not a failure');
169
  finishOld({url:'https://source.test/stale'});await tick();
170
  assert.strictEqual(priority.stored.has('reader-resolve:old'),false,'late old JSON cannot enter cache');
171
+ assert.strictEqual(priority.run('Number(!!readerWarmupPending)'),1,'late completion cannot release new task');
172
  next.resolve({ok:true,json:async()=>({url:'https://source.test/new'})});await tick();
173
  assert.ok(priority.stored.has('reader-resolve:new'));
174
  emitIntent(priority,'pointerover','old');
 
180
  emitIntent(priority,'pointerdown','download',true);
181
  assert.strictEqual(resolverCalls(priority).length,4,'download actions never preempt');
182
  priority.events.offline();await tick();
183
+ assert.strictEqual(priority.run('Number(!!readerWarmupPending)'),0);
184
  assert.ok(priority.run('readerWarmupRetryAt.has("id:keyboard")'),'offline cancellation retains backoff');
185
 
186
  const reentrant=fixture();
 
195
  assert.ok(owner.options.signal.aborted && reentrantCalls[1].url.endsWith('id=reentrant'));
196
  assert.strictEqual(reentrant.run('readerWarmupPending.key'),'id:reentrant');
197
  reentrantCalls[1].resolve({ok:true,json:async()=>({url:'https://source.test/reentrant'})});await tick();
198
+ assert.strictEqual(reentrant.run('Number(!!readerWarmupPending)'),0);
199
 
200
  const rapid=fixture();
201
  emitIntent(rapid,'pointerover','rapid0');
 
204
  assert.strictEqual(rapidCalls.length,21);
205
  assert.ok(rapidCalls.slice(0,-1).every(call=>call.options.signal.aborted));
206
  assert.ok(!rapidCalls.at(-1).options.signal.aborted);
207
+ assert.strictEqual(rapid.run('Number(!!readerWarmupPending)'),1);
208
  assert.strictEqual(rapid.run('readerWarmupRetryAt.size'),0);
209
  rapidCalls.at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/final'})});
210
  await tick();
211
  assert.ok(rapid.stored.has('reader-resolve:rapid20'));
212
+ assert.strictEqual(rapid.run('Number(!!readerWarmupPending)'),0);
213
 
214
  const sources=fixture();
215
  sources.run(`warmReaderIntent('/reader?url=https://source.test/hover');
 
219
  assert.ok(heads[0].options.signal.aborted);
220
  assert.ok(heads[1].url.includes(encodeURIComponent('https://source.test/activate')));
221
  heads[1].resolve({ok:true});await tick();
222
+ assert.strictEqual(sources.run('Number(!!readerWarmupPending)'),0);
223
  assert.strictEqual(sources.run('warmedReaderSources.size'),1);
224
 
225
  const capacity=fixture();
 
235
  await tick();
236
  assert.strictEqual(capacity.run('readerWarmupPending.key'),'id:limit','old rejection cannot release the urgent owner');
237
  resolverCalls(capacity).at(-1).resolve({ok:true,json:async()=>({url:'https://source.test/limit'})});await tick();
238
+ assert.strictEqual(capacity.run('Number(!!readerWarmupPending)'),0);
239
  assert.strictEqual(capacity.run('warmedReaderSources.size'),8);
240
 
241
  const timeout=fixture();
 
244
  // Such a callback argument must not accidentally mark a timeout superseded.
245
  for (const timer of [...timeout.timers.values()]) timer({simulatedTimer:true});
246
  await tick();
247
+ assert.strictEqual(timeout.run('Number(!!readerWarmupPending)'),0);
248
  assert.ok(timeout.run('readerWarmupRetryAt.has("id:timed-out")'));
249
 
250
  const previous=fixture();
 
255
  emitIntent(previous,'pointerdown','failed');
256
  assert.ok(busy.options.signal.aborted,'even a backed-off target should cancel unrelated speculation');
257
  assert.strictEqual(resolverCalls(previous).length,2,'priority does not bypass retry backoff');
258
+ assert.strictEqual(previous.run('Number(!!readerWarmupPending)'),0);
259
  previous.advance();emitIntent(previous,'focusin','failed');
260
  assert.strictEqual(resolverCalls(previous).length,3);
261
  resolverCalls(previous)[2].resolve({ok:true,json:async()=>({url:'https://source.test/failed'})});await tick();
tests/search/baselines/test_sidebar_markup_baseline.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // Capture the existing host renderer before replacing its HTML assembly.
2
  import assert from 'node:assert/strict';
3
  import fs from 'node:fs';
4
  import path from 'node:path';
@@ -6,9 +6,6 @@ import test from 'node:test';
6
  import vm from 'node:vm';
7
 
8
  const root = process.cwd();
9
- const source = fs.readFileSync(path.join(root,'static/app.js'),'utf8');
10
- const match = source.match(/^function renderBrowserListItems\([^]*?^}/m);
11
- assert.ok(match, 'host sidebar renderer must exist');
12
  const space = fs.existsSync(path.join(root,'pyrightconfig.json'));
13
 
14
  function fixture() {
@@ -28,28 +25,27 @@ function fixture() {
28
  vm.runInContext(fs.readFileSync(modulePath,'utf8'),c,{filename:modulePath});
29
  const directoryPath=path.join(root,'static/search/sidebar/presentation/directory.js');
30
  vm.runInContext(fs.readFileSync(directoryPath,'utf8'),c,{filename:directoryPath});
31
- c.getSidebarDirectoryView=()=>c.VoiceOfMLSidebarDirectoryView.create({
32
  surface:space?'space':'pages',scroll:{restore:()=>c.restoreSidebarScroll()},
33
  markup:{icon:key=>c.sidebarIconMarkup(key),escape:value=>c.escapeHTML(value),
34
  iconType:value=>c.getFileIconType(value),formatSize:value=>c.formatSize(value),
35
  name:file=>c.getBrowserFileName(file),link:(...args)=>c.getBrowserFileLink(...args),
36
  reader:(...args)=>space?c.getBrowserFileReadUrl(...args):c.getBrowserReaderUrl(...args)}
37
  });
38
- vm.runInContext(match[0],c,{filename:'sidebar-host.js'});
39
- return {c,calls};
40
  }
41
 
42
  test('empty sidebar preserves original output and scroll restore timing',()=>{
43
- const {c,calls}=fixture();const list={innerHTML:'old'};
44
- c.renderBrowserListItems(list,{},'Repo','');
45
  assert.equal(list.innerHTML,'');assert.deepEqual(calls,[['icon','folder'],['restore']]);
46
  });
47
 
48
  test('folder and file markup preserve site-specific attributes, escaping and order',()=>{
49
- const {c,calls}=fixture();const list={innerHTML:''};
50
  const data={folders:[{name:'<目录&',path:'a"/b',count:3}],files:[
51
  {name:'a<b',ext:'pdf',size:12},{name:'raw&',ext:'zip',size:0}]};
52
- c.renderBrowserListItems(list,data,'Repo','folder');
53
  const html=list.innerHTML;
54
  assert.match(html,/aria-label="打开文件夹:&lt;目录&amp;"/);
55
  assert.match(html,/data-path="a&quot;\/b"/);
@@ -64,20 +60,20 @@ test('folder and file markup preserve site-specific attributes, escaping and ord
64
  });
65
 
66
  test('missing folder paths keep each site original serialization',()=>{
67
- const {c}=fixture();const list={innerHTML:''};
68
- c.renderBrowserListItems(list,{folders:[{name:'missing'}]},'R','');
69
  assert.match(list.innerHTML,space?/data-path="undefined"/:/data-path=""/);
70
  });
71
 
72
  test('exceptions before final assignment do not restore scroll or partially replace DOM',()=>{
73
- const {c,calls}=fixture();const list={innerHTML:'old'};
74
  c.getBrowserFileName=()=>{throw new Error('name failure');};
75
- assert.throws(()=>c.renderBrowserListItems(list,{folders:[],files:[{name:'x',ext:'pdf'}]},'R',''),/name failure/);
76
  assert.equal(list.innerHTML,'old');assert.equal(calls.some(x=>x[0]==='restore'),false);
77
  });
78
 
79
  test('DOM assignment exceptions prevent scroll restoration',()=>{
80
- const {c,calls}=fixture();const list={set innerHTML(_value){throw new Error('assignment failure');}};
81
- assert.throws(()=>c.renderBrowserListItems(list,{folders:[],files:[]},'R',''),/assignment failure/);
82
  assert.equal(calls.some(x=>x[0]==='restore'),false);
83
  });
 
1
+ // Keep the original sidebar behavior pinned against the directory view.
2
  import assert from 'node:assert/strict';
3
  import fs from 'node:fs';
4
  import path from 'node:path';
 
6
  import vm from 'node:vm';
7
 
8
  const root = process.cwd();
 
 
 
9
  const space = fs.existsSync(path.join(root,'pyrightconfig.json'));
10
 
11
  function fixture() {
 
25
  vm.runInContext(fs.readFileSync(modulePath,'utf8'),c,{filename:modulePath});
26
  const directoryPath=path.join(root,'static/search/sidebar/presentation/directory.js');
27
  vm.runInContext(fs.readFileSync(directoryPath,'utf8'),c,{filename:directoryPath});
28
+ const directory=c.VoiceOfMLSidebarDirectoryView.create({
29
  surface:space?'space':'pages',scroll:{restore:()=>c.restoreSidebarScroll()},
30
  markup:{icon:key=>c.sidebarIconMarkup(key),escape:value=>c.escapeHTML(value),
31
  iconType:value=>c.getFileIconType(value),formatSize:value=>c.formatSize(value),
32
  name:file=>c.getBrowserFileName(file),link:(...args)=>c.getBrowserFileLink(...args),
33
  reader:(...args)=>space?c.getBrowserFileReadUrl(...args):c.getBrowserReaderUrl(...args)}
34
  });
35
+ return {c,calls,directory};
 
36
  }
37
 
38
  test('empty sidebar preserves original output and scroll restore timing',()=>{
39
+ const {directory,calls}=fixture();const list={innerHTML:'old'};
40
+ directory.items(list,{},'Repo','');
41
  assert.equal(list.innerHTML,'');assert.deepEqual(calls,[['icon','folder'],['restore']]);
42
  });
43
 
44
  test('folder and file markup preserve site-specific attributes, escaping and order',()=>{
45
+ const {directory,calls}=fixture();const list={innerHTML:''};
46
  const data={folders:[{name:'<目录&',path:'a"/b',count:3}],files:[
47
  {name:'a<b',ext:'pdf',size:12},{name:'raw&',ext:'zip',size:0}]};
48
+ directory.items(list,data,'Repo','folder');
49
  const html=list.innerHTML;
50
  assert.match(html,/aria-label="打开文件夹:&lt;目录&amp;"/);
51
  assert.match(html,/data-path="a&quot;\/b"/);
 
60
  });
61
 
62
  test('missing folder paths keep each site original serialization',()=>{
63
+ const {directory}=fixture();const list={innerHTML:''};
64
+ directory.items(list,{folders:[{name:'missing'}]},'R','');
65
  assert.match(list.innerHTML,space?/data-path="undefined"/:/data-path=""/);
66
  });
67
 
68
  test('exceptions before final assignment do not restore scroll or partially replace DOM',()=>{
69
+ const {c,calls,directory}=fixture();const list={innerHTML:'old'};
70
  c.getBrowserFileName=()=>{throw new Error('name failure');};
71
+ assert.throws(()=>directory.items(list,{folders:[],files:[{name:'x',ext:'pdf'}]},'R',''),/name failure/);
72
  assert.equal(list.innerHTML,'old');assert.equal(calls.some(x=>x[0]==='restore'),false);
73
  });
74
 
75
  test('DOM assignment exceptions prevent scroll restoration',()=>{
76
+ const {directory,calls}=fixture();const list={set innerHTML(_value){throw new Error('assignment failure');}};
77
+ assert.throws(()=>directory.items(list,{folders:[],files:[]},'R',''),/assignment failure/);
78
  assert.equal(calls.some(x=>x[0]==='restore'),false);
79
  });
tests/search/browser/test_browser.py CHANGED
@@ -150,7 +150,7 @@ class BrowserInteractionTests(unittest.TestCase):
150
  }
151
  initialPayloadCache.clear();
152
  // The first-page response cache is independent of the initial payload cache.
153
- searchResponseCache.clear();
154
  STATE.query = ""; STATE.page = 1;
155
  const pending = searchWithInitialFallbackFresh();
156
  await new Promise(resolve => setTimeout(resolve, 50));
@@ -366,7 +366,7 @@ class BrowserInteractionTests(unittest.TestCase):
366
  }];
367
  STATE.folderTreeCollapsed = {};
368
  getSidebarFolderTree().initialize(STATE.folderTree);
369
- renderFilterFolderTree();
370
  }""")
371
  checkbox = page.locator("#filter-folder-tree .filter-folder-item input").last
372
  with page.expect_request(lambda request: request.url.split('?', 1)[0].endswith('/api/search/MLMRL-Hub') and
@@ -482,7 +482,7 @@ class BrowserInteractionTests(unittest.TestCase):
482
  name: `folder-${i}`, path: `folder-${i}`, count: 1,
483
  hasDirectFiles: true, hasChildren: false, children: []
484
  }));
485
- renderFilterFolderTree();
486
  window.__originalFilterRow = DOM.filterFolderTree.firstElementChild;
487
  window.__filterRuns = 0;
488
  window.__searchRuns = 0;
@@ -519,7 +519,7 @@ class BrowserInteractionTests(unittest.TestCase):
519
  showSelfToggle:true, hasDirectFiles:true, hasChildren:true,
520
  children:[{name:'docs', path:'docs', count:1, hasDirectFiles:true, hasChildren:false, children:[]}]}];
521
  STATE.folderTreeCollapsed = {};
522
- renderFilterFolderTree();
523
  }""")
524
  button = page.locator("#filter-folder-tree .folder-self-toggle")
525
  button.click()
@@ -739,7 +739,7 @@ class BrowserInteractionTests(unittest.TestCase):
739
  try:
740
  # The visible input precedes asynchronous startup search/prefetch.
741
  # Observe composition only after those initial requests settle.
742
- page.wait_for_function("STATE._loadedPage >= 1 && !STATE.isLoading && pendingSearchPages.size === 0")
743
  requests.clear()
744
  page.locator("#search-input").dispatch_event("compositionstart")
745
  page.locator("#search-input").fill("手")
@@ -843,12 +843,12 @@ class BrowserInteractionTests(unittest.TestCase):
843
  const originalRect = measuredRow.getBoundingClientRect.bind(measuredRow);
844
  measuredRow.getBoundingClientRect = () => { repeatedReads++; return originalRect(); };
845
  VSCROLL.measuredWindowKey = "";
846
- measureHeights(VSCROLL.renderStart, VSCROLL.renderEnd);
847
  const readsAtSameWidth = repeatedReads;
848
  const originalWidth = DOM.resultsContainer.style.width;
849
  DOM.resultsContainer.style.width = Math.max(200, container.clientWidth - 1) + "px";
850
  VSCROLL.measuredWindowKey = "";
851
- measureHeights(VSCROLL.renderStart, VSCROLL.renderEnd);
852
  DOM.resultsContainer.style.width = originalWidth;
853
  const preservedAfterAppend = preservedRow === DOM.resultsList.querySelector(`.result-item[data-index="${preservedIndex}"]`);
854
  const treeExtendedInPlace = heightTreeBeforeAppend === VSCROLL.heightTree;
@@ -1270,7 +1270,7 @@ class BrowserInteractionTests(unittest.TestCase):
1270
  page.locator("#search-input").wait_for(state="visible")
1271
  page.wait_for_function("() => STATE.query === '持久搜索' && STATE.filterExtensions.includes('pdf')")
1272
  page.wait_for_function("""async () => {
1273
- const db = await openSearchSessionDB();
1274
  const tx = db.transaction('session', 'readonly');
1275
  const request = tx.objectStore('session').get('last-search');
1276
  const saved = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = reject; });
 
150
  }
151
  initialPayloadCache.clear();
152
  // The first-page response cache is independent of the initial payload cache.
153
+ searchResponseStore.cache.clear();
154
  STATE.query = ""; STATE.page = 1;
155
  const pending = searchWithInitialFallbackFresh();
156
  await new Promise(resolve => setTimeout(resolve, 50));
 
366
  }];
367
  STATE.folderTreeCollapsed = {};
368
  getSidebarFolderTree().initialize(STATE.folderTree);
369
+ getSidebarFolderTree().render();
370
  }""")
371
  checkbox = page.locator("#filter-folder-tree .filter-folder-item input").last
372
  with page.expect_request(lambda request: request.url.split('?', 1)[0].endswith('/api/search/MLMRL-Hub') and
 
482
  name: `folder-${i}`, path: `folder-${i}`, count: 1,
483
  hasDirectFiles: true, hasChildren: false, children: []
484
  }));
485
+ getSidebarFolderTree().render();
486
  window.__originalFilterRow = DOM.filterFolderTree.firstElementChild;
487
  window.__filterRuns = 0;
488
  window.__searchRuns = 0;
 
519
  showSelfToggle:true, hasDirectFiles:true, hasChildren:true,
520
  children:[{name:'docs', path:'docs', count:1, hasDirectFiles:true, hasChildren:false, children:[]}]}];
521
  STATE.folderTreeCollapsed = {};
522
+ getSidebarFolderTree().render();
523
  }""")
524
  button = page.locator("#filter-folder-tree .folder-self-toggle")
525
  button.click()
 
739
  try:
740
  # The visible input precedes asynchronous startup search/prefetch.
741
  # Observe composition only after those initial requests settle.
742
+ page.wait_for_function("STATE._loadedPage >= 1 && !STATE.isLoading && getSearchTransport().pending.size === 0")
743
  requests.clear()
744
  page.locator("#search-input").dispatch_event("compositionstart")
745
  page.locator("#search-input").fill("手")
 
843
  const originalRect = measuredRow.getBoundingClientRect.bind(measuredRow);
844
  measuredRow.getBoundingClientRect = () => { repeatedReads++; return originalRect(); };
845
  VSCROLL.measuredWindowKey = "";
846
+ getVirtualResults().measureHeights();
847
  const readsAtSameWidth = repeatedReads;
848
  const originalWidth = DOM.resultsContainer.style.width;
849
  DOM.resultsContainer.style.width = Math.max(200, container.clientWidth - 1) + "px";
850
  VSCROLL.measuredWindowKey = "";
851
+ getVirtualResults().measureHeights();
852
  DOM.resultsContainer.style.width = originalWidth;
853
  const preservedAfterAppend = preservedRow === DOM.resultsList.querySelector(`.result-item[data-index="${preservedIndex}"]`);
854
  const treeExtendedInPlace = heightTreeBeforeAppend === VSCROLL.heightTree;
 
1270
  page.locator("#search-input").wait_for(state="visible")
1271
  page.wait_for_function("() => STATE.query === '持久搜索' && STATE.filterExtensions.includes('pdf')")
1272
  page.wait_for_function("""async () => {
1273
+ const db = await searchSession.openSearchSessionDB();
1274
  const tx = db.transaction('session', 'readonly');
1275
  const request = tx.objectStore('session').get('last-search');
1276
  const saved = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = reject; });
tests/search/browser/test_download_lifecycle.py CHANGED
@@ -48,7 +48,7 @@ class DownloadLifecycleTests(unittest.TestCase):
48
  self.assertEqual(self.page.locator('[data-action="download"]').first.text_content(), '准备中…')
49
  self.assertEqual(self.page.evaluate('launches.length'), 0)
50
  self.page.evaluate('finishCheck()')
51
- self.page.wait_for_function('launches.length === 1 && pendingDownloads.size === 0')
52
  self.page.locator('[data-action="download"]').first.click()
53
  self.page.wait_for_function('launches.length === 2')
54
  self.assertEqual(self.page.evaluate('checkCalls'), 1)
@@ -117,7 +117,7 @@ class DownloadLifecycleTests(unittest.TestCase):
117
  if (handedOff !== link) return;
118
  const cancel=()=>{
119
  downloadBatches.cancel();
120
- handoffRetained=pendingDownloads.has(link);
121
  };
122
  if (timing==='sync') cancel(); else queueMicrotask(cancel);
123
  };
@@ -130,7 +130,7 @@ class DownloadLifecycleTests(unittest.TestCase):
130
  self.assertEqual(self.page.evaluate('''[
131
  downloadBatches.batch.cancelled,downloadBatches.batch.started,downloadBatches.batch.next,
132
  downloadBatches.batch.failed.map(item=>item.link),handoffLaunches,
133
- handoffIndependent,handoffRetained,pendingDownloads.size
134
  ]'''), [True, 1, 2, [link+'-queued', link+'-unclaimed'], [link], True, True, 0])
135
  self.assertIn('已发起 1/3', self.page.locator('#download-queue [role="status"]').text_content())
136
  self.page.locator('#download-queue [data-queue="retry"]').click()
@@ -167,8 +167,8 @@ class DownloadLifecycleTests(unittest.TestCase):
167
  {status:link==='bad' && calls[link]===1 ? 503 : 200}));
168
  };
169
  for(let i=0;i<70;i++) await checkDownload('cache'+i);
170
- const size=downloadChecks.size;
171
- downloadChecks.get('cache69').expires=Date.now()-1;
172
  await checkDownload('cache69');
173
  const first=await downloadFile('bad.txt','bad');
174
  const second=await downloadFile('bad.txt','bad');
@@ -225,7 +225,7 @@ class DownloadLifecycleTests(unittest.TestCase):
225
  const real=checkDownload('real');
226
  const busy=await checkDownload('speculative',true);
227
  finishCheck(); await real;
228
- return {hidden,offline,busy,calls:checkCalls,queued:downloadCheckQueue.length};
229
  }''')
230
  self.assertEqual(result, dict(hidden=False,offline=False,busy=False,calls=1,queued=0))
231
 
@@ -290,7 +290,7 @@ class DownloadLifecycleTests(unittest.TestCase):
290
  self.page.locator('[data-queue="cancel"]').click()
291
  self.page.evaluate('releases.forEach(release=>release())')
292
  self.page.wait_for_function('downloadBatches.batch.done')
293
- self.assertEqual(self.page.evaluate('[releases.length,launches.length,pendingDownloads.size]'), [2,0,0])
294
  self.page.locator('[data-queue="close"]').click()
295
  self.assertEqual(self.page.locator('#download-queue').count(), 0)
296
 
@@ -306,7 +306,7 @@ class DownloadLifecycleTests(unittest.TestCase):
306
  }''')
307
  self.page.clock.fast_forward(8001)
308
  self.page.wait_for_function('window.downloadResult === false')
309
- self.assertEqual(self.page.evaluate('[activeDownloadChecks,downloadChecks.size,pendingDownloads.size]'), [0,0,0])
310
  self.assertIn('超时', self.page.locator('#toast').text_content())
311
 
312
  def test_attachment_handoff_keeps_search_page_and_filename(self):
 
48
  self.assertEqual(self.page.locator('[data-action="download"]').first.text_content(), '准备中…')
49
  self.assertEqual(self.page.evaluate('launches.length'), 0)
50
  self.page.evaluate('finishCheck()')
51
+ self.page.wait_for_function('launches.length === 1 && downloadController.pendingDownloads.size === 0')
52
  self.page.locator('[data-action="download"]').first.click()
53
  self.page.wait_for_function('launches.length === 2')
54
  self.assertEqual(self.page.evaluate('checkCalls'), 1)
 
117
  if (handedOff !== link) return;
118
  const cancel=()=>{
119
  downloadBatches.cancel();
120
+ handoffRetained=downloadController.pendingDownloads.has(link);
121
  };
122
  if (timing==='sync') cancel(); else queueMicrotask(cancel);
123
  };
 
130
  self.assertEqual(self.page.evaluate('''[
131
  downloadBatches.batch.cancelled,downloadBatches.batch.started,downloadBatches.batch.next,
132
  downloadBatches.batch.failed.map(item=>item.link),handoffLaunches,
133
+ handoffIndependent,handoffRetained,downloadController.pendingDownloads.size
134
  ]'''), [True, 1, 2, [link+'-queued', link+'-unclaimed'], [link], True, True, 0])
135
  self.assertIn('已发起 1/3', self.page.locator('#download-queue [role="status"]').text_content())
136
  self.page.locator('#download-queue [data-queue="retry"]').click()
 
167
  {status:link==='bad' && calls[link]===1 ? 503 : 200}));
168
  };
169
  for(let i=0;i<70;i++) await checkDownload('cache'+i);
170
+ const size=downloadController.downloadChecks.size;
171
+ downloadController.downloadChecks.get('cache69').expires=Date.now()-1;
172
  await checkDownload('cache69');
173
  const first=await downloadFile('bad.txt','bad');
174
  const second=await downloadFile('bad.txt','bad');
 
225
  const real=checkDownload('real');
226
  const busy=await checkDownload('speculative',true);
227
  finishCheck(); await real;
228
+ return {hidden,offline,busy,calls:checkCalls,queued:downloadController.downloadCheckQueue.length};
229
  }''')
230
  self.assertEqual(result, dict(hidden=False,offline=False,busy=False,calls=1,queued=0))
231
 
 
290
  self.page.locator('[data-queue="cancel"]').click()
291
  self.page.evaluate('releases.forEach(release=>release())')
292
  self.page.wait_for_function('downloadBatches.batch.done')
293
+ self.assertEqual(self.page.evaluate('[releases.length,launches.length,downloadController.pendingDownloads.size]'), [2,0,0])
294
  self.page.locator('[data-queue="close"]').click()
295
  self.assertEqual(self.page.locator('#download-queue').count(), 0)
296
 
 
306
  }''')
307
  self.page.clock.fast_forward(8001)
308
  self.page.wait_for_function('window.downloadResult === false')
309
+ self.assertEqual(self.page.evaluate('[activeDownloadChecks,downloadController.downloadChecks.size,downloadController.pendingDownloads.size]'), [0,0,0])
310
  self.assertIn('超时', self.page.locator('#toast').text_content())
311
 
312
  def test_attachment_handoff_keeps_search_page_and_filename(self):
tests/search/browser/test_initial_intent_reader_routes.py CHANGED
@@ -131,7 +131,7 @@ class InitialIntentReaderRouteTests(unittest.TestCase):
131
  el.textContent = JSON.stringify(changed);
132
  }''')
133
  for age in (240000, 479999):
134
- self.page.evaluate('age => { initialNow = 1000000 + age; searchResponseCache.clear(); }', age)
135
  self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')
136
  self.assert_initial_generation('G1')
137
  self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 0))
@@ -152,7 +152,7 @@ class InitialIntentReaderRouteTests(unittest.TestCase):
152
  def test_initial_payload_cannot_overwrite_newer_response(self):
153
  self.load_initial_clock_fixture()
154
  self.page.evaluate('''() => {
155
- initialNow += 1000; searchResponseCache.clear(); doSearch();
156
  }''')
157
  self.assert_initial_generation('G2')
158
  self.assertEqual(len(self.api_requests), 1)
@@ -161,17 +161,17 @@ class InitialIntentReaderRouteTests(unittest.TestCase):
161
  self.assertEqual(self.page.evaluate('getCachedSearchResponse(getCurrentSearchCacheKey(1)).generation'), 'G2')
162
  self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 1))
163
  self.initial_generation = 'G3'
164
- self.page.evaluate('searchResponseCache.clear()')
165
  self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')
166
  self.assert_initial_generation('G3')
167
  self.assertEqual((len(self.initial_requests), len(self.api_requests)), (1, 1))
168
 
169
  def test_newer_response_eviction_does_not_resurrect_initial(self):
170
  self.load_initial_clock_fixture()
171
- self.page.evaluate("initialNow += 1000; searchResponseCache.clear(); doSearch()")
172
  self.assert_initial_generation('G2')
173
  self.initial_generation = 'G3'
174
- self.page.evaluate('searchResponseCache.clear()')
175
  self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')
176
  self.assert_initial_generation('G3')
177
 
@@ -201,14 +201,14 @@ class InitialIntentReaderRouteTests(unittest.TestCase):
201
  now+=1000; const acquired=now;
202
  setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL-1;
203
  flushWrite();
204
- const keptAge=searchResponseCache.get(key)?.time===acquired;
205
  now++; const expiredAtBoundary=getCachedSearchResponse(key)===null;
206
  setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL;
207
  flushWrite();
208
- const flushDropsExpired=!searchResponseCache.has(key) && !searchResponseStore.pendingWrites.has(key);
209
  return {expiredPending,expiredAfterFlush,keptAge,expiredAtBoundary,flushDropsExpired};
210
  } finally {
211
- cancelPendingSearchCacheWrites();searchResponseCache.delete(key);
212
  Date.now=clock;requestAnimationFrame=raf;cancelAnimationFrame=cancel;
213
  }
214
  }''')
@@ -218,7 +218,7 @@ class InitialIntentReaderRouteTests(unittest.TestCase):
218
  def hold_initial_and_search(self):
219
  self.page.evaluate('''() => {
220
  cancelSearchPrefetch();
221
- searchResponseCache.clear(); initialPayloadCache.clear(); resultSnapshots.snapshots.clear();
222
  STATE.query = ''; STATE.page = 1;
223
  if (typeof readInitialSearchPayload === 'function') readInitialSearchPayload = () => null;
224
  window.initialFlights = []; window.searchFlights = [];
@@ -309,7 +309,7 @@ class InitialIntentReaderRouteTests(unittest.TestCase):
309
  self.hold_initial_and_search()
310
  self.evaluate_bounded('''async () => {
311
  initialFlights[0].resolve(payload('seed')); await oldInitial;
312
- resultSnapshots.snapshots.clear(); initialPayloadCache.clear(); searchResponseCache.clear();
313
  displayedSearchView = null;
314
  getReturnPositionTarget = () => ({index:0});
315
  readSearchViewport = () => new Promise(resolve => { window.releaseViewport = resolve; });
 
131
  el.textContent = JSON.stringify(changed);
132
  }''')
133
  for age in (240000, 479999):
134
+ self.page.evaluate('age => { initialNow = 1000000 + age; searchResponseStore.cache.clear(); }', age)
135
  self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')
136
  self.assert_initial_generation('G1')
137
  self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 0))
 
152
  def test_initial_payload_cannot_overwrite_newer_response(self):
153
  self.load_initial_clock_fixture()
154
  self.page.evaluate('''() => {
155
+ initialNow += 1000; searchResponseStore.cache.clear(); doSearch();
156
  }''')
157
  self.assert_initial_generation('G2')
158
  self.assertEqual(len(self.api_requests), 1)
 
161
  self.assertEqual(self.page.evaluate('getCachedSearchResponse(getCurrentSearchCacheKey(1)).generation'), 'G2')
162
  self.assertEqual((len(self.initial_requests), len(self.api_requests)), (0, 1))
163
  self.initial_generation = 'G3'
164
+ self.page.evaluate('searchResponseStore.cache.clear()')
165
  self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')
166
  self.assert_initial_generation('G3')
167
  self.assertEqual((len(self.initial_requests), len(self.api_requests)), (1, 1))
168
 
169
  def test_newer_response_eviction_does_not_resurrect_initial(self):
170
  self.load_initial_clock_fixture()
171
+ self.page.evaluate("initialNow += 1000; searchResponseStore.cache.clear(); doSearch()")
172
  self.assert_initial_generation('G2')
173
  self.initial_generation = 'G3'
174
+ self.page.evaluate('searchResponseStore.cache.clear()')
175
  self.evaluate_bounded('async () => { await searchWithInitialFallbackFresh(); }')
176
  self.assert_initial_generation('G3')
177
 
 
201
  now+=1000; const acquired=now;
202
  setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL-1;
203
  flushWrite();
204
+ const keptAge=searchResponseStore.cache.get(key)?.time===acquired;
205
  now++; const expiredAtBoundary=getCachedSearchResponse(key)===null;
206
  setCachedSearchResponse(key,data,true); now+=SEARCH_CACHE_TTL;
207
  flushWrite();
208
+ const flushDropsExpired=!searchResponseStore.cache.has(key) && !searchResponseStore.pendingWrites.has(key);
209
  return {expiredPending,expiredAfterFlush,keptAge,expiredAtBoundary,flushDropsExpired};
210
  } finally {
211
+ cancelPendingSearchCacheWrites();searchResponseStore.cache.delete(key);
212
  Date.now=clock;requestAnimationFrame=raf;cancelAnimationFrame=cancel;
213
  }
214
  }''')
 
218
  def hold_initial_and_search(self):
219
  self.page.evaluate('''() => {
220
  cancelSearchPrefetch();
221
+ searchResponseStore.cache.clear(); initialPayloadCache.clear(); resultSnapshots.snapshots.clear();
222
  STATE.query = ''; STATE.page = 1;
223
  if (typeof readInitialSearchPayload === 'function') readInitialSearchPayload = () => null;
224
  window.initialFlights = []; window.searchFlights = [];
 
309
  self.hold_initial_and_search()
310
  self.evaluate_bounded('''async () => {
311
  initialFlights[0].resolve(payload('seed')); await oldInitial;
312
+ resultSnapshots.snapshots.clear(); initialPayloadCache.clear(); searchResponseStore.cache.clear();
313
  displayedSearchView = null;
314
  getReturnPositionTarget = () => ({index:0});
315
  readSearchViewport = () => new Promise(resolve => { window.releaseViewport = resolve; });
tests/search/browser/test_paging_recovery.py CHANGED
@@ -217,7 +217,7 @@ class PagingRecoveryTests(unittest.TestCase):
217
  const body = {page:1, page_size:1};
218
  const first = fetchSearchPage(key, '/api/search/shared-rejection', body, firstOwner.signal, 5000);
219
  const second = fetchSearchPage(key, '/api/search/shared-rejection', body, secondOwner.signal, 5000);
220
- const entry = pendingSearchPages.get(key), joined = entry.listeners.size;
221
  const outcomes = Promise.allSettled([first, second]);
222
  release();
223
  const settled = await outcomes;
@@ -226,7 +226,7 @@ class PagingRecoveryTests(unittest.TestCase):
226
  safe:!!error && typeof error.name === 'string' && typeof error.message === 'string',
227
  same:error === settled[1].reason,
228
  preserved:i < 7 || error === reason,
229
- name:error?.name, cleaned:!pendingSearchPages.has(key) && entry.listeners.size === 0});
230
  }
231
  return cases;
232
  } finally { window.fetch = original; }
@@ -270,7 +270,7 @@ class PagingRecoveryTests(unittest.TestCase):
270
  cases.push({phase, index:i, calls, statuses:settled.map(item => item.status),
271
  same:error === settled[1].reason, identity:i < 2 || error === reason,
272
  name:error?.name, message:error?.message, status:error?.status ?? null, code:error?.code ?? null,
273
- cleaned:![...pendingSearchPages.keys()].some(key => key.includes(query.query))});
274
  }
275
  return cases;
276
  } finally { window.fetch = original; frame.remove(); }
@@ -300,13 +300,13 @@ class PagingRecoveryTests(unittest.TestCase):
300
  const body = {page:1, page_size:1};
301
  const first = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);
302
  const second = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);
303
- const entry = pendingSearchPages.get(key);
304
  const settled = await Promise.allSettled([first, second]), error = settled[0].reason;
305
  cases.push({field:String(field), statuses:settled.map(item => item.status),
306
  safe:error instanceof Error && typeof error.message === 'string',
307
  same:error === settled[1].reason, cause:error?.cause === getterError,
308
  recoverable:isRecoverableSearchError(error),
309
- cleaned:!pendingSearchPages.has(key) && entry.listeners.size === 0});
310
  }
311
  return cases;
312
  } finally { window.fetch = original; }
@@ -331,13 +331,13 @@ class PagingRecoveryTests(unittest.TestCase):
331
  const body = {page:1, page_size:1}, key = 'shared-cancel';
332
  const cancelled = fetchSearchPage(key, '/api/search/shared-cancel', body, owner.signal, 5000);
333
  const remaining = fetchSearchPage(key, '/api/search/shared-cancel', body, undefined, 5000);
334
- const entry = pendingSearchPages.get(key);
335
  const outcomes = Promise.allSettled([cancelled, remaining]);
336
  owner.abort(); release();
337
  const settled = await outcomes;
338
  return {statuses:settled.map(item => item.status), names:settled.map(item => item.reason?.name),
339
  calls, aborted:transportSignal.aborted,
340
- cleaned:!pendingSearchPages.has(key) && entry.listeners.size === 0};
341
  } finally { window.fetch = original; }
342
  }''')
343
  self.assertEqual(result, dict(statuses=['rejected', 'rejected'], names=['AbortError', 'Error'],
@@ -389,7 +389,7 @@ class PagingRecoveryTests(unittest.TestCase):
389
  def expire_pending(self, mode):
390
  self.page.evaluate('''mode => {
391
  window.pagingMode = mode;
392
- pendingSearchPages.forEach(entry => { entry.deadline = Date.now() - 1; });
393
  document.dispatchEvent(new Event('visibilitychange'));
394
  }''', mode)
395
 
@@ -416,7 +416,7 @@ class PagingRecoveryTests(unittest.TestCase):
416
  Object.defineProperty(document, 'hidden', {configurable: true, value: true});
417
  Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'hidden'});
418
  document.dispatchEvent(new Event('visibilitychange'));
419
- pendingSearchPages.forEach(entry => entry.deadline = Date.now() + 25000);
420
  pagingMode = 'normal';
421
  Object.defineProperty(document, 'hidden', {configurable: true, value: false});
422
  Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'visible'});
 
217
  const body = {page:1, page_size:1};
218
  const first = fetchSearchPage(key, '/api/search/shared-rejection', body, firstOwner.signal, 5000);
219
  const second = fetchSearchPage(key, '/api/search/shared-rejection', body, secondOwner.signal, 5000);
220
+ const entry = getSearchTransport().pending.get(key), joined = entry.listeners.size;
221
  const outcomes = Promise.allSettled([first, second]);
222
  release();
223
  const settled = await outcomes;
 
226
  safe:!!error && typeof error.name === 'string' && typeof error.message === 'string',
227
  same:error === settled[1].reason,
228
  preserved:i < 7 || error === reason,
229
+ name:error?.name, cleaned:!getSearchTransport().pending.has(key) && entry.listeners.size === 0});
230
  }
231
  return cases;
232
  } finally { window.fetch = original; }
 
270
  cases.push({phase, index:i, calls, statuses:settled.map(item => item.status),
271
  same:error === settled[1].reason, identity:i < 2 || error === reason,
272
  name:error?.name, message:error?.message, status:error?.status ?? null, code:error?.code ?? null,
273
+ cleaned:![...getSearchTransport().pending.keys()].some(key => key.includes(query.query))});
274
  }
275
  return cases;
276
  } finally { window.fetch = original; frame.remove(); }
 
300
  const body = {page:1, page_size:1};
301
  const first = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);
302
  const second = fetchSearchPage(key, '/api/search/shared-getter', body, undefined, 5000);
303
+ const entry = getSearchTransport().pending.get(key);
304
  const settled = await Promise.allSettled([first, second]), error = settled[0].reason;
305
  cases.push({field:String(field), statuses:settled.map(item => item.status),
306
  safe:error instanceof Error && typeof error.message === 'string',
307
  same:error === settled[1].reason, cause:error?.cause === getterError,
308
  recoverable:isRecoverableSearchError(error),
309
+ cleaned:!getSearchTransport().pending.has(key) && entry.listeners.size === 0});
310
  }
311
  return cases;
312
  } finally { window.fetch = original; }
 
331
  const body = {page:1, page_size:1}, key = 'shared-cancel';
332
  const cancelled = fetchSearchPage(key, '/api/search/shared-cancel', body, owner.signal, 5000);
333
  const remaining = fetchSearchPage(key, '/api/search/shared-cancel', body, undefined, 5000);
334
+ const entry = getSearchTransport().pending.get(key);
335
  const outcomes = Promise.allSettled([cancelled, remaining]);
336
  owner.abort(); release();
337
  const settled = await outcomes;
338
  return {statuses:settled.map(item => item.status), names:settled.map(item => item.reason?.name),
339
  calls, aborted:transportSignal.aborted,
340
+ cleaned:!getSearchTransport().pending.has(key) && entry.listeners.size === 0};
341
  } finally { window.fetch = original; }
342
  }''')
343
  self.assertEqual(result, dict(statuses=['rejected', 'rejected'], names=['AbortError', 'Error'],
 
389
  def expire_pending(self, mode):
390
  self.page.evaluate('''mode => {
391
  window.pagingMode = mode;
392
+ getSearchTransport().pending.forEach(entry => { entry.deadline = Date.now() - 1; });
393
  document.dispatchEvent(new Event('visibilitychange'));
394
  }''', mode)
395
 
 
416
  Object.defineProperty(document, 'hidden', {configurable: true, value: true});
417
  Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'hidden'});
418
  document.dispatchEvent(new Event('visibilitychange'));
419
+ getSearchTransport().pending.forEach(entry => entry.deadline = Date.now() + 25000);
420
  pagingMode = 'normal';
421
  Object.defineProperty(document, 'hidden', {configurable: true, value: false});
422
  Object.defineProperty(document, 'visibilityState', {configurable: true, value: 'visible'});
tests/search/browser/test_position_window.py CHANGED
@@ -161,7 +161,7 @@ class PositionWindowTests(unittest.TestCase):
161
  self.page.evaluate('for(let i=0;i<20;i++)renderVisible()')
162
  self.page.wait_for_timeout(800)
163
  self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)
164
- self.assertFalse(self.page.evaluate('''[...pendingSearchPages.values()].some(entry=>
165
  entry.listeners.size && !entry.controller.signal.aborted)'''))
166
  self.page.evaluate('rejectGapTransport=false')
167
  self.page.locator('#search-window-status button').click()
 
161
  self.page.evaluate('for(let i=0;i<20;i++)renderVisible()')
162
  self.page.wait_for_timeout(800)
163
  self.assertEqual(self.page.evaluate('gapTransportCalls'), 3)
164
+ self.assertFalse(self.page.evaluate('''[...getSearchTransport().pending.values()].some(entry=>
165
  entry.listeners.size && !entry.controller.signal.aborted)'''))
166
  self.page.evaluate('rejectGapTransport=false')
167
  self.page.locator('#search-window-status button').click()
tests/search/browser/test_prefetch_pipeline.py CHANGED
@@ -100,14 +100,15 @@ class PrefetchPipelineTests(unittest.TestCase):
100
  self.start_pipeline()
101
  self.fixture.reach_bottom()
102
  self.page.evaluate('''() => {
103
- window.pageWork=[];const list=DOM.resultsList,insert=list.insertBefore,write=searchResponseCache.set;
 
104
  // Observe actual row publication, including module-internal renders.
105
  list.insertBefore=function(row,before){
106
  const result=insert.call(this,row,before);
107
  if(STATE._loadedPage>=2 && row.classList?.contains('result-item')) pageWork.push('render');
108
  return result;
109
  };
110
- searchResponseCache.set=function(key,value){
111
  if(value.data.page===2) pageWork.push('cache');return write.call(this,key,value);
112
  };
113
  aheadReleases[2]();
@@ -153,7 +154,7 @@ class PrefetchPipelineTests(unittest.TestCase):
153
  def test_matching_saved_pages_avoid_network_and_old_generation_is_rejected(self):
154
  result = self.page.evaluate('''async () => {
155
  cancelSearchPrefetch();
156
- STATE._pageCache={};searchResponseCache.clear();positionPersistence.recentPages.clear();
157
  const key=getSearchViewKey();const template={q:STATE.query,page:1,page_size:100};
158
  const metadata={generation:'stable',page:1,page_size:100,total:STATE.total,results:STATE.results};
159
  rememberSearchPageMetadata(metadata);
@@ -171,7 +172,7 @@ class PrefetchPipelineTests(unittest.TestCase):
171
  while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
172
  const reused=Object.keys(STATE._pageCache).map(Number);
173
  const calls=networkPages.slice();
174
- cancelSearchPrefetch();STATE._pageCache={};searchResponseCache.clear();
175
  cached.forEach(entry=>positionPersistence.recentPages.set(JSON.stringify(entry.id), {...entry,generation:'old'}));
176
  prefetchSearchPages('/api/search',template);
177
  while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
 
100
  self.start_pipeline()
101
  self.fixture.reach_bottom()
102
  self.page.evaluate('''() => {
103
+ window.pageWork=[];const list=DOM.resultsList,insert=list.insertBefore;
104
+ const cache=searchResponseStore.cache,write=cache.set;
105
  // Observe actual row publication, including module-internal renders.
106
  list.insertBefore=function(row,before){
107
  const result=insert.call(this,row,before);
108
  if(STATE._loadedPage>=2 && row.classList?.contains('result-item')) pageWork.push('render');
109
  return result;
110
  };
111
+ cache.set=function(key,value){
112
  if(value.data.page===2) pageWork.push('cache');return write.call(this,key,value);
113
  };
114
  aheadReleases[2]();
 
154
  def test_matching_saved_pages_avoid_network_and_old_generation_is_rejected(self):
155
  result = self.page.evaluate('''async () => {
156
  cancelSearchPrefetch();
157
+ STATE._pageCache={};searchResponseStore.cache.clear();positionPersistence.recentPages.clear();
158
  const key=getSearchViewKey();const template={q:STATE.query,page:1,page_size:100};
159
  const metadata={generation:'stable',page:1,page_size:100,total:STATE.total,results:STATE.results};
160
  rememberSearchPageMetadata(metadata);
 
172
  while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
173
  const reused=Object.keys(STATE._pageCache).map(Number);
174
  const calls=networkPages.slice();
175
+ cancelSearchPrefetch();STATE._pageCache={};searchResponseStore.cache.clear();
176
  cached.forEach(entry=>positionPersistence.recentPages.set(JSON.stringify(entry.id), {...entry,generation:'old'}));
177
  prefetchSearchPages('/api/search',template);
178
  while(controllerActive()) await new Promise(resolve=>setTimeout(resolve,0));
tests/search/browser/test_scroll_stability.py CHANGED
@@ -293,12 +293,16 @@ class ReaderActionRefreshTests(unittest.TestCase):
293
  top:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision};
294
  let storage=0,renders=0,measures=0;
295
  const native={set:Storage.prototype.setItem,remove:Storage.prototype.removeItem,
296
- schedule:scheduleVirtualRender,measure:measureHeights};
297
  const observer=new MutationObserver(()=>{});
298
  observer.observe(DOM.resultsList,{subtree:true,childList:true,attributes:true,characterData:true});
299
  Storage.prototype.setItem=function(...args){storage++;return native.set.apply(this,args)};
300
  Storage.prototype.removeItem=function(...args){storage++;return native.remove.apply(this,args)};
301
- scheduleVirtualRender=()=>{renders++};measureHeights=()=>{measures++};
 
 
 
 
302
  try {
303
  for(let i=0;i<5;i++) refreshResultReaderActions();
304
  return {writes:observer.takeRecords().length,storage,renders,measures,
@@ -309,7 +313,7 @@ class ReaderActionRefreshTests(unittest.TestCase):
309
  top:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision})};
310
  } finally {
311
  observer.disconnect();Storage.prototype.setItem=native.set;Storage.prototype.removeItem=native.remove;
312
- scheduleVirtualRender=native.schedule;measureHeights=native.measure;
313
  }
314
  }''')
315
  self.assertEqual(result, dict(writes=0, storage=0, renders=0, measures=0,
 
293
  top:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision};
294
  let storage=0,renders=0,measures=0;
295
  const native={set:Storage.prototype.setItem,remove:Storage.prototype.removeItem,
296
+ schedule:scheduleVirtualRender,rect:Element.prototype.getBoundingClientRect};
297
  const observer=new MutationObserver(()=>{});
298
  observer.observe(DOM.resultsList,{subtree:true,childList:true,attributes:true,characterData:true});
299
  Storage.prototype.setItem=function(...args){storage++;return native.set.apply(this,args)};
300
  Storage.prototype.removeItem=function(...args){storage++;return native.remove.apply(this,args)};
301
+ scheduleVirtualRender=()=>{renders++};
302
+ Element.prototype.getBoundingClientRect=function(){
303
+ if(this.matches('.result-item')) measures++;
304
+ return native.rect.call(this);
305
+ };
306
  try {
307
  for(let i=0;i<5;i++) refreshResultReaderActions();
308
  return {writes:observer.takeRecords().length,storage,renders,measures,
 
313
  top:getResultScrollTop(),text:selection.toString(),revision:measuredHeightRevision})};
314
  } finally {
315
  observer.disconnect();Storage.prototype.setItem=native.set;Storage.prototype.removeItem=native.remove;
316
+ scheduleVirtualRender=native.schedule;Element.prototype.getBoundingClientRect=native.rect;
317
  }
318
  }''')
319
  self.assertEqual(result, dict(writes=0, storage=0, renders=0, measures=0,
tests/search/browser/test_search_accessibility_browser.py CHANGED
@@ -84,7 +84,7 @@ class SearchAccessibilityTests(unittest.TestCase):
84
  isRoot:!path,hasChildren:!!children.length,hasDirectFiles:true,showSelfToggle:!!children.length});
85
  STATE.mode='repo';STATE.folderTree=[node('',[node('alpha',[node('alpha/deep',[node('alpha/deep/hit')])]),node('beta')])];
86
  STATE.folderTreeCollapsed={};STATE.filterFolderSubtrees=['alpha/deep/hit'];STATE.filterFolderSelfs=['beta'];
87
- STATE.filterFolders=['alpha/deep/hit','beta'];DOM.filterFolderSection.style.display='';renderFilterFolderTree();
88
  }''')
89
  self.page.wait_for_function('!sidebarFolderTree.pending()')
90
  before = self.page.evaluate('''()=>({selfs:STATE.filterFolderSelfs.slice(),subtrees:STATE.filterFolderSubtrees.slice(),
@@ -130,9 +130,9 @@ class SearchAccessibilityTests(unittest.TestCase):
130
  self.page.evaluate('''()=>{
131
  STATE.folderTree=[{path:'wide',name:'wide',hasChildren:true,children:Array.from({length:256},(_,i)=>
132
  ({path:'wide/'+i,name:String(i),hasChildren:false,children:[],hasDirectFiles:true}))}];
133
- renderFilterFolderTree();setAllFoldersCollapsed(false);setAllFoldersCollapsed(true);
134
  routeRenderId++;STATE.folderTree=[{path:'new',name:'new',hasChildren:false,children:[],hasDirectFiles:true}];
135
- renderFilterFolderTree();
136
  }''')
137
  self.page.wait_for_function('!sidebarFolderTree.pending()')
138
  self.assertEqual(self.page.locator('#filter-folder-tree .filter-folder-item').count(), 1)
@@ -322,14 +322,14 @@ class SearchAccessibilityTests(unittest.TestCase):
322
  valid += ['older-' + str(i) for i in range(maximum)]
323
  stored = [None, 42, True, {}, ['nested']] + valid
324
  self.page.evaluate("value=>sessionStorage.setItem('voml_search_history', JSON.stringify(value))", stored)
325
- self.assertEqual(self.page.evaluate('getHistory()'), valid[:maximum])
326
  self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('voml_search_history'))"), stored)
327
  for raw in ('{broken', 'null', '42'):
328
  with self.subTest(raw=raw):
329
  self.page.evaluate("raw=>sessionStorage.setItem('voml_search_history', raw)", raw)
330
- self.assertEqual(self.page.evaluate('getHistory()'), [])
331
  self.page.evaluate("sessionStorage.removeItem('voml_search_history')")
332
- self.assertEqual(self.page.evaluate('getHistory()'), [])
333
  self.assertEqual(self.page.evaluate('''()=>{
334
  const original=Storage.prototype.getItem;
335
  try {
@@ -337,7 +337,7 @@ class SearchAccessibilityTests(unittest.TestCase):
337
  if(key==='voml_search_history') throw new DOMException('Blocked', 'SecurityError');
338
  return original.call(this,key);
339
  };
340
- return getHistory();
341
  } finally { Storage.prototype.getItem=original; }
342
  }'''), [])
343
 
@@ -353,7 +353,7 @@ class SearchAccessibilityTests(unittest.TestCase):
353
  self.page.wait_for_timeout(180)
354
  self.assertTrue(self.page.locator('#search-history-dropdown').is_visible())
355
  self.page.keyboard.press('Enter')
356
- self.assertEqual(self.page.evaluate('getHistory()'), ['second query'])
357
  self.assertTrue(self.page.get_by_role('button', name='搜索:second query', exact=True).evaluate('node=>node===document.activeElement'))
358
  self.page.keyboard.press('Escape')
359
  self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')
@@ -361,7 +361,7 @@ class SearchAccessibilityTests(unittest.TestCase):
361
  field.blur()
362
  field.focus()
363
  self.page.get_by_role('button', name='清空历史', exact=True).press('Enter')
364
- self.assertEqual(self.page.evaluate('getHistory()'), [])
365
  self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')
366
  self.assertTrue(self.page.locator('#search-history-dropdown').is_hidden())
367
 
@@ -387,7 +387,7 @@ class SearchAccessibilityTests(unittest.TestCase):
387
  def test_single_repository_browser_order_is_not_count_sorted(self):
388
  observed = self.page.evaluate("""()=>{
389
  const list=document.createElement('div');
390
- renderBrowserListItems(list,{folders:[
391
  {name:'large',path:'large',count:30},
392
  {name:'small',path:'small',count:2},
393
  {name:'medium',path:'medium',count:10},
@@ -500,8 +500,9 @@ class SearchAccessibilityTests(unittest.TestCase):
500
  self.assertEqual(self.page.evaluate('navigations'), [['repo', 'Test']])
501
  self.page.evaluate('''()=>{
502
  STATE.repo='Test';const list=document.createElement('div');list.className='browser-list';
503
- DOM.sidebarContent.replaceChildren(createSidebarBreadcrumb('docs/sub'),list);
504
- renderBrowserListItems(list,{folders:[{name:'inner',path:'docs/sub/inner',count:1}],
 
505
  files:[{name:'book',ext:'txt',size:1}]},'Test','docs/sub');
506
  window.downloads=[];list.addEventListener('click',event=>{
507
  if(event.target.closest('.browser-action')){downloads.push(event.target.textContent);event.stopImmediatePropagation();}
@@ -546,7 +547,7 @@ class SearchAccessibilityTests(unittest.TestCase):
546
  DOM.filterFolderSection.style.display='';
547
  STATE.folderTree=[{name:'docs',path:'docs',count:1,showSelfToggle:true,children:[
548
  {name:'child',path:'docs/child',count:1,children:[]}]}];
549
- STATE.folderTreeCollapsed={docs:false};renderFilterFolderTree();
550
  }''')
551
  self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs', exact=True).count(), 1)
552
  self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs/child', exact=True).count(), 1)
 
84
  isRoot:!path,hasChildren:!!children.length,hasDirectFiles:true,showSelfToggle:!!children.length});
85
  STATE.mode='repo';STATE.folderTree=[node('',[node('alpha',[node('alpha/deep',[node('alpha/deep/hit')])]),node('beta')])];
86
  STATE.folderTreeCollapsed={};STATE.filterFolderSubtrees=['alpha/deep/hit'];STATE.filterFolderSelfs=['beta'];
87
+ STATE.filterFolders=['alpha/deep/hit','beta'];DOM.filterFolderSection.style.display='';getSidebarFolderTree().render();
88
  }''')
89
  self.page.wait_for_function('!sidebarFolderTree.pending()')
90
  before = self.page.evaluate('''()=>({selfs:STATE.filterFolderSelfs.slice(),subtrees:STATE.filterFolderSubtrees.slice(),
 
130
  self.page.evaluate('''()=>{
131
  STATE.folderTree=[{path:'wide',name:'wide',hasChildren:true,children:Array.from({length:256},(_,i)=>
132
  ({path:'wide/'+i,name:String(i),hasChildren:false,children:[],hasDirectFiles:true}))}];
133
+ getSidebarFolderTree().render();setAllFoldersCollapsed(false);setAllFoldersCollapsed(true);
134
  routeRenderId++;STATE.folderTree=[{path:'new',name:'new',hasChildren:false,children:[],hasDirectFiles:true}];
135
+ getSidebarFolderTree().render();
136
  }''')
137
  self.page.wait_for_function('!sidebarFolderTree.pending()')
138
  self.assertEqual(self.page.locator('#filter-folder-tree .filter-folder-item').count(), 1)
 
322
  valid += ['older-' + str(i) for i in range(maximum)]
323
  stored = [None, 42, True, {}, ['nested']] + valid
324
  self.page.evaluate("value=>sessionStorage.setItem('voml_search_history', JSON.stringify(value))", stored)
325
+ self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), valid[:maximum])
326
  self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('voml_search_history'))"), stored)
327
  for raw in ('{broken', 'null', '42'):
328
  with self.subTest(raw=raw):
329
  self.page.evaluate("raw=>sessionStorage.setItem('voml_search_history', raw)", raw)
330
+ self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), [])
331
  self.page.evaluate("sessionStorage.removeItem('voml_search_history')")
332
+ self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), [])
333
  self.assertEqual(self.page.evaluate('''()=>{
334
  const original=Storage.prototype.getItem;
335
  try {
 
337
  if(key==='voml_search_history') throw new DOMException('Blocked', 'SecurityError');
338
  return original.call(this,key);
339
  };
340
+ return searchHistoryStore.get();
341
  } finally { Storage.prototype.getItem=original; }
342
  }'''), [])
343
 
 
353
  self.page.wait_for_timeout(180)
354
  self.assertTrue(self.page.locator('#search-history-dropdown').is_visible())
355
  self.page.keyboard.press('Enter')
356
+ self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), ['second query'])
357
  self.assertTrue(self.page.get_by_role('button', name='搜索:second query', exact=True).evaluate('node=>node===document.activeElement'))
358
  self.page.keyboard.press('Escape')
359
  self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')
 
361
  field.blur()
362
  field.focus()
363
  self.page.get_by_role('button', name='清空历史', exact=True).press('Enter')
364
+ self.assertEqual(self.page.evaluate('searchHistoryStore.get()'), [])
365
  self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')
366
  self.assertTrue(self.page.locator('#search-history-dropdown').is_hidden())
367
 
 
387
  def test_single_repository_browser_order_is_not_count_sorted(self):
388
  observed = self.page.evaluate("""()=>{
389
  const list=document.createElement('div');
390
+ getSidebarDirectoryView().items(list,{folders:[
391
  {name:'large',path:'large',count:30},
392
  {name:'small',path:'small',count:2},
393
  {name:'medium',path:'medium',count:10},
 
500
  self.assertEqual(self.page.evaluate('navigations'), [['repo', 'Test']])
501
  self.page.evaluate('''()=>{
502
  STATE.repo='Test';const list=document.createElement('div');list.className='browser-list';
503
+ const directory=getSidebarDirectoryView();
504
+ DOM.sidebarContent.replaceChildren(directory.breadcrumb('docs/sub'),list);
505
+ directory.items(list,{folders:[{name:'inner',path:'docs/sub/inner',count:1}],
506
  files:[{name:'book',ext:'txt',size:1}]},'Test','docs/sub');
507
  window.downloads=[];list.addEventListener('click',event=>{
508
  if(event.target.closest('.browser-action')){downloads.push(event.target.textContent);event.stopImmediatePropagation();}
 
547
  DOM.filterFolderSection.style.display='';
548
  STATE.folderTree=[{name:'docs',path:'docs',count:1,showSelfToggle:true,children:[
549
  {name:'child',path:'docs/child',count:1,children:[]}]}];
550
+ STATE.folderTreeCollapsed={docs:false};getSidebarFolderTree().render();
551
  }''')
552
  self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs', exact=True).count(), 1)
553
  self.assertEqual(self.page.get_by_role('checkbox', name='选择文件夹:docs/child', exact=True).count(), 1)
tests/search/browser/test_search_positions.py CHANGED
@@ -196,7 +196,7 @@ class SearchPositionTests(unittest.TestCase):
196
  self.page.evaluate("ROUTER.navigate('global')")
197
  self.page.wait_for_function("STATE.mode==='global' && !STATE.isLoading")
198
  self.page.evaluate('''() => {
199
- resultSnapshots.snapshots.clear(); searchResponseCache.clear();
200
  STATE.filterExtensions=[]; STATE.query='paging-original'; DOM.searchInput.value=STATE.query;
201
  scheduleFilterSearch();
202
  }''')
@@ -263,8 +263,8 @@ class SearchPositionTests(unittest.TestCase):
263
  kept = self.page.evaluate('''() => {
264
  resultSnapshots.snapshots.clear();
265
  resultSnapshots.snapshots.set('small', {bytes: 1024});
266
- resultSnapshots.snapshots.set('large', {bytes: SEARCH_VIEW_SNAPSHOT_BYTES_MAX+1});
267
- trimSearchViewSnapshots(); return [...resultSnapshots.snapshots.keys()];
268
  }''')
269
  self.assertEqual(kept, ['small'])
270
 
@@ -451,7 +451,7 @@ class SearchPositionTests(unittest.TestCase):
451
  def test_window_restore_does_not_fetch_unvisited_prefix(self):
452
  self.begin_rebuild('''() => {
453
  prefetchNextPage=()=>{}; // Measure the restore-critical set, independently of lookahead.
454
- pagingTotal=800;searchResponseCache.clear();
455
  const originalKey=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
456
  positionPersistence.positions.get(originalKey).loadedPage=8;
457
  const original=fetchPositionPage;window.restoreCalls=[];window.restorePeak=0;let active=0;
@@ -472,7 +472,7 @@ class SearchPositionTests(unittest.TestCase):
472
  def test_window_retry_reuses_completed_neighbor(self):
473
  self.begin_rebuild('''() => {
474
  prefetchNextPage=()=>{};
475
- pagingTotal=400;searchResponseCache.clear();
476
  const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
477
  positionPersistence.positions.get(key).loadedPage=4;
478
  const original=fetchPositionPage;window.restoreCalls=[];window.failPage=true;
@@ -493,7 +493,7 @@ class SearchPositionTests(unittest.TestCase):
493
 
494
  def test_parallel_generation_mismatch_discards_entire_buffer(self):
495
  self.begin_rebuild('''() => {
496
- pagingTotal=400;searchResponseCache.clear();
497
  const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
498
  positionPersistence.positions.get(key).loadedPage=4;
499
  const original=fetchPositionPage;window.coherent=false;
 
196
  self.page.evaluate("ROUTER.navigate('global')")
197
  self.page.wait_for_function("STATE.mode==='global' && !STATE.isLoading")
198
  self.page.evaluate('''() => {
199
+ resultSnapshots.snapshots.clear(); searchResponseStore.cache.clear();
200
  STATE.filterExtensions=[]; STATE.query='paging-original'; DOM.searchInput.value=STATE.query;
201
  scheduleFilterSearch();
202
  }''')
 
263
  kept = self.page.evaluate('''() => {
264
  resultSnapshots.snapshots.clear();
265
  resultSnapshots.snapshots.set('small', {bytes: 1024});
266
+ resultSnapshots.snapshots.set('large', {bytes: VoiceOfMLSnapshotPolicy.BYTES_MAX+1});
267
+ resultSnapshots.trim(); return [...resultSnapshots.snapshots.keys()];
268
  }''')
269
  self.assertEqual(kept, ['small'])
270
 
 
451
  def test_window_restore_does_not_fetch_unvisited_prefix(self):
452
  self.begin_rebuild('''() => {
453
  prefetchNextPage=()=>{}; // Measure the restore-critical set, independently of lookahead.
454
+ pagingTotal=800;searchResponseStore.cache.clear();
455
  const originalKey=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
456
  positionPersistence.positions.get(originalKey).loadedPage=8;
457
  const original=fetchPositionPage;window.restoreCalls=[];window.restorePeak=0;let active=0;
 
472
  def test_window_retry_reuses_completed_neighbor(self):
473
  self.begin_rebuild('''() => {
474
  prefetchNextPage=()=>{};
475
+ pagingTotal=400;searchResponseStore.cache.clear();
476
  const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
477
  positionPersistence.positions.get(key).loadedPage=4;
478
  const original=fetchPositionPage;window.restoreCalls=[];window.failPage=true;
 
493
 
494
  def test_parallel_generation_mismatch_discards_entire_buffer(self):
495
  self.begin_rebuild('''() => {
496
+ pagingTotal=400;searchResponseStore.cache.clear();
497
  const key=[...positionPersistence.positions.keys()].find(key=>JSON.parse(key).query==='paging-original');
498
  positionPersistence.positions.get(key).loadedPage=4;
499
  const original=fetchPositionPage;window.coherent=false;
tests/search/browser/test_sidebar_keyboard.py CHANGED
@@ -26,7 +26,7 @@ class SidebarKeyboardTests(unittest.TestCase):
26
  # Let startup's shared requests settle before replacing their state.
27
  (page or self.page).wait_for_function('''() => getSidebarFilters().status().token > 0 &&
28
  getSidebarFilters().status().done === getSidebarFilters().status().token && !API._repoPending &&
29
- !API._bootstrapPending && sidebarInitialPending.size === 0''', timeout=15000)
30
 
31
  def test_deep_sidebar_toggles_skip_full_result_snapshots(self):
32
  result = self.page.evaluate('''async () => {
@@ -64,7 +64,7 @@ class SidebarKeyboardTests(unittest.TestCase):
64
  result = self.page.evaluate('''() => {
65
  const repo = 'x"><img src=x onerror="window.injected=true">';
66
  const row = document.createElement('div');
67
- row.innerHTML = buildResultHTML({Repo:repo, File:'book', Extension:'txt', Folder:['docs'], Size:1}, 0);
68
  DOM.resultsList.append(row);
69
  return {images:row.querySelectorAll('img').length,
70
  attributes:Array.from(row.querySelectorAll('[data-repo]'), node=>node.dataset.repo),
@@ -82,7 +82,7 @@ class SidebarKeyboardTests(unittest.TestCase):
82
  DOM.historyToggle.dispatchEvent(new Event('change',{bubbles:true}));
83
  STATE.folderTree=[{name:'root',path:'root',count:1,selfCount:0,children:[
84
  {name:'child',path:'root/child',count:1,selfCount:1,children:[]}]}];
85
- STATE.folderTreeCollapsed={root:true};renderFilterFolderTree();
86
  DOM.filterFolderTree.querySelector('.tree-toggle').click();
87
  const neutral=captures;
88
  DOM.sortSelect.dispatchEvent(new Event('change',{bubbles:true}));
@@ -260,7 +260,7 @@ class SidebarKeyboardTests(unittest.TestCase):
260
  STATE.mode='repo';STATE.repo='Test';STATE.repoFull='VoiceOfML/Test';
261
  STATE.folderTree=[{path:'docs',name:'docs',count:1,children:[],hasDirectFiles:true}];
262
  STATE.filterFolderSelfs=[];STATE.filterFolderSubtrees=[];STATE.filterFolders=[];
263
- DOM.filterFolderSection.style.display='';renderFilterFolderTree();
264
  }''')
265
  self.page.locator('#filter-min-size').fill('3')
266
  self.page.locator('#filter-folder-tree input').check()
@@ -331,7 +331,7 @@ class SidebarKeyboardTests(unittest.TestCase):
331
  STATE.filterRepos=[];STATE.filterMinSize=null;STATE.filterMaxSize=null;
332
  history.replaceState(null,'','/');
333
  window.__breadcrumbClick=folder=>{const row=document.createElement('div');
334
- row.innerHTML=buildResultHTML({Repo:'VoiceOfML/Test',File:'deep',Extension:'txt',Folder:['docs','子'],Size:1},0);
335
  DOM.resultsList.append(row);
336
  Array.from(row.querySelectorAll('.path-folder')).find(link=>link.dataset.folder===folder).click();};
337
  }''')
@@ -395,7 +395,7 @@ class SidebarKeyboardTests(unittest.TestCase):
395
  Array.from({length:1000},(_,i)=>({name:'child'+i,path:'root/'+i,count:1,selfCount:1,children:[]}))}];
396
  STATE.folderTreeCollapsed={root:true};
397
  STATE.filterFolderSubtrees=[]; STATE.filterFolderSelfs=[]; STATE.filterFolders=[];
398
- renderFilterFolderTree();
399
  const initial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
400
  const root=DOM.filterFolderTree.querySelector('.filter-folder-item');
401
  root.querySelector('input').click();
@@ -431,7 +431,7 @@ class SidebarKeyboardTests(unittest.TestCase):
431
  }
432
  return result;
433
  };
434
- try {renderFilterFolderTree();renderFilterFolderTree();deferred=sidebarFolderTree.pending()>0;}
435
  finally {Element.prototype.appendChild=append;}
436
  while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,0));
437
  const rows=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
@@ -449,7 +449,7 @@ class SidebarKeyboardTests(unittest.TestCase):
449
  STATE.folderTree=[{name:'root',path:'root',count:1000,hasChildren:true,children:
450
  Array.from({length:1000},(_,i)=>({name:String(i),path:'root/'+i,count:1,hasDirectFiles:true,children:[]}))}];
451
  STATE.folderTreeCollapsed={root:true};STATE.filterFolderSubtrees=[];STATE.filterFolderSelfs=[];
452
- renderFilterFolderTree();const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');
453
  toggle.click();const partial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
454
  toggle.click();await new Promise(r=>setTimeout(r,30));
455
  const stopped=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===partial && !sidebarFolderTree.pending();
@@ -457,7 +457,7 @@ class SidebarKeyboardTests(unittest.TestCase):
457
  while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));
458
  const final=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
459
  const late=DOM.filterFolderTree.querySelector('[data-path="root/999"] input').checked;
460
- STATE.folderTree=[{name:'new',path:'new',count:1,hasDirectFiles:true,children:[]}];renderFilterFolderTree();
461
  await new Promise(r=>setTimeout(r,30));
462
  return {stopped,final,late,current:DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===1};
463
  }''')
@@ -468,7 +468,7 @@ class SidebarKeyboardTests(unittest.TestCase):
468
  STATE.folderTree=[{name:'root',path:'root',count:500,hasChildren:true,children:[
469
  {name:'branch',path:'root/b',count:500,hasChildren:true,children:Array.from({length:500},(_,i)=>
470
  ({name:String(i),path:'root/b/'+i,count:1,hasDirectFiles:true,children:[]}))}]}];
471
- STATE.folderTreeCollapsed={root:true,'root/b':false};renderFilterFolderTree();
472
  const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');toggle.click();toggle.click();
473
  const stopped=!sidebarFolderTree.pending();toggle.click();
474
  while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));
@@ -538,7 +538,7 @@ class SidebarKeyboardTests(unittest.TestCase):
538
  result = self.page.evaluate('''async () => {
539
  const native=window.fetch, calls=[];
540
  API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;
541
- sidebarInitialCache.clear();sidebarInitialPending.clear();
542
  const expected=[{name:'VoiceOfML/Test',count:1}];
543
  window.fetch=url=>{
544
  calls.push(url);
@@ -596,7 +596,7 @@ class SidebarKeyboardTests(unittest.TestCase):
596
  self.wait_for_startup_metadata()
597
  result = self.page.evaluate('''async () => {
598
  API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;
599
- sidebarInitialCache.clear();sidebarInitialPending.clear();
600
  const native=window.fetch;let bootstrap=0,repos=0,sidebar=0;
601
  const expected=[{name:'VoiceOfML/Test',count:1}];
602
  window.fetch=(url,options)=>{
@@ -659,7 +659,7 @@ class SidebarKeyboardTests(unittest.TestCase):
659
  self.wait_for_startup_metadata()
660
  result = self.page.evaluate('''async () => {
661
  API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;
662
- sidebarInitialCache.clear();sidebarInitialPending.clear();
663
  const native=window.fetch, expected=[{name:'VoiceOfML/Test',count:1}], calls=[];
664
  window.fetch=url=>{
665
  calls.push(url);
 
26
  # Let startup's shared requests settle before replacing their state.
27
  (page or self.page).wait_for_function('''() => getSidebarFilters().status().token > 0 &&
28
  getSidebarFilters().status().done === getSidebarFilters().status().token && !API._repoPending &&
29
+ !API._bootstrapPending && catalog.sidebarInitialPending.size === 0''', timeout=15000)
30
 
31
  def test_deep_sidebar_toggles_skip_full_result_snapshots(self):
32
  result = self.page.evaluate('''async () => {
 
64
  result = self.page.evaluate('''() => {
65
  const repo = 'x"><img src=x onerror="window.injected=true">';
66
  const row = document.createElement('div');
67
+ row.innerHTML = getResultRows().buildHTML({Repo:repo, File:'book', Extension:'txt', Folder:['docs'], Size:1}, 0);
68
  DOM.resultsList.append(row);
69
  return {images:row.querySelectorAll('img').length,
70
  attributes:Array.from(row.querySelectorAll('[data-repo]'), node=>node.dataset.repo),
 
82
  DOM.historyToggle.dispatchEvent(new Event('change',{bubbles:true}));
83
  STATE.folderTree=[{name:'root',path:'root',count:1,selfCount:0,children:[
84
  {name:'child',path:'root/child',count:1,selfCount:1,children:[]}]}];
85
+ STATE.folderTreeCollapsed={root:true};getSidebarFolderTree().render();
86
  DOM.filterFolderTree.querySelector('.tree-toggle').click();
87
  const neutral=captures;
88
  DOM.sortSelect.dispatchEvent(new Event('change',{bubbles:true}));
 
260
  STATE.mode='repo';STATE.repo='Test';STATE.repoFull='VoiceOfML/Test';
261
  STATE.folderTree=[{path:'docs',name:'docs',count:1,children:[],hasDirectFiles:true}];
262
  STATE.filterFolderSelfs=[];STATE.filterFolderSubtrees=[];STATE.filterFolders=[];
263
+ DOM.filterFolderSection.style.display='';getSidebarFolderTree().render();
264
  }''')
265
  self.page.locator('#filter-min-size').fill('3')
266
  self.page.locator('#filter-folder-tree input').check()
 
331
  STATE.filterRepos=[];STATE.filterMinSize=null;STATE.filterMaxSize=null;
332
  history.replaceState(null,'','/');
333
  window.__breadcrumbClick=folder=>{const row=document.createElement('div');
334
+ row.innerHTML=getResultRows().buildHTML({Repo:'VoiceOfML/Test',File:'deep',Extension:'txt',Folder:['docs','子'],Size:1},0);
335
  DOM.resultsList.append(row);
336
  Array.from(row.querySelectorAll('.path-folder')).find(link=>link.dataset.folder===folder).click();};
337
  }''')
 
395
  Array.from({length:1000},(_,i)=>({name:'child'+i,path:'root/'+i,count:1,selfCount:1,children:[]}))}];
396
  STATE.folderTreeCollapsed={root:true};
397
  STATE.filterFolderSubtrees=[]; STATE.filterFolderSelfs=[]; STATE.filterFolders=[];
398
+ getSidebarFolderTree().render();
399
  const initial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
400
  const root=DOM.filterFolderTree.querySelector('.filter-folder-item');
401
  root.querySelector('input').click();
 
431
  }
432
  return result;
433
  };
434
+ try {getSidebarFolderTree().render();getSidebarFolderTree().render();deferred=sidebarFolderTree.pending()>0;}
435
  finally {Element.prototype.appendChild=append;}
436
  while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,0));
437
  const rows=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
 
449
  STATE.folderTree=[{name:'root',path:'root',count:1000,hasChildren:true,children:
450
  Array.from({length:1000},(_,i)=>({name:String(i),path:'root/'+i,count:1,hasDirectFiles:true,children:[]}))}];
451
  STATE.folderTreeCollapsed={root:true};STATE.filterFolderSubtrees=[];STATE.filterFolderSelfs=[];
452
+ getSidebarFolderTree().render();const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');
453
  toggle.click();const partial=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
454
  toggle.click();await new Promise(r=>setTimeout(r,30));
455
  const stopped=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===partial && !sidebarFolderTree.pending();
 
457
  while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));
458
  const final=DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length;
459
  const late=DOM.filterFolderTree.querySelector('[data-path="root/999"] input').checked;
460
+ STATE.folderTree=[{name:'new',path:'new',count:1,hasDirectFiles:true,children:[]}];getSidebarFolderTree().render();
461
  await new Promise(r=>setTimeout(r,30));
462
  return {stopped,final,late,current:DOM.filterFolderTree.querySelectorAll('.filter-folder-item').length===1};
463
  }''')
 
468
  STATE.folderTree=[{name:'root',path:'root',count:500,hasChildren:true,children:[
469
  {name:'branch',path:'root/b',count:500,hasChildren:true,children:Array.from({length:500},(_,i)=>
470
  ({name:String(i),path:'root/b/'+i,count:1,hasDirectFiles:true,children:[]}))}]}];
471
+ STATE.folderTreeCollapsed={root:true,'root/b':false};getSidebarFolderTree().render();
472
  const toggle=DOM.filterFolderTree.querySelector('.tree-toggle');toggle.click();toggle.click();
473
  const stopped=!sidebarFolderTree.pending();toggle.click();
474
  while(sidebarFolderTree.pending()) await new Promise(r=>setTimeout(r,10));
 
538
  result = self.page.evaluate('''async () => {
539
  const native=window.fetch, calls=[];
540
  API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;
541
+ catalog.sidebarInitialCache.clear();catalog.sidebarInitialPending.clear();
542
  const expected=[{name:'VoiceOfML/Test',count:1}];
543
  window.fetch=url=>{
544
  calls.push(url);
 
596
  self.wait_for_startup_metadata()
597
  result = self.page.evaluate('''async () => {
598
  API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;
599
+ catalog.sidebarInitialCache.clear();catalog.sidebarInitialPending.clear();
600
  const native=window.fetch;let bootstrap=0,repos=0,sidebar=0;
601
  const expected=[{name:'VoiceOfML/Test',count:1}];
602
  window.fetch=(url,options)=>{
 
659
  self.wait_for_startup_metadata()
660
  result = self.page.evaluate('''async () => {
661
  API._bootstrapCache=null;API._bootstrapPending=null;API._repoCache=null;API._repoPending=null;
662
+ catalog.sidebarInitialCache.clear();catalog.sidebarInitialPending.clear();
663
  const native=window.fetch, expected=[{name:'VoiceOfML/Test',count:1}], calls=[];
664
  window.fetch=url=>{
665
  calls.push(url);
tests/search/reader-navigation/test_search_history_races.mjs CHANGED
@@ -36,7 +36,7 @@ function fixture(names, values = {}) {
36
  function transportFixture() {
37
  let now = 0, timerId = 0;
38
  const timers = new Map(), calls = [];
39
- const c = fixture(['getSearchTransport', 'createSearchPageRequest', 'fetchSearchPage',
40
  'expireSearchRequests', 'normalizeSearchError', 'suspendSearchRequests', 'resumeSearchRequests'],
41
  {DOMException, document:{hidden:false}, APPEND_REQUEST_TIMEOUT:50,
42
  Date:{now:()=>now}, scheduleScrollRecovery(){},
@@ -451,7 +451,7 @@ test('published state is a detached narrow projection without mutable ownership'
451
  assert.equal(c.state.ready, true);
452
  });
453
 
454
- test('app adapter publishes readable input state and delegates submit with history options', () => {
455
  const modules = vm.createContext({});
456
  for (const path of ['domain/ownership.js', 'application/controller.js'])
457
  vm.runInContext(fs.readFileSync('static/search/input/' + path, 'utf8'), modules);
@@ -469,13 +469,14 @@ test('app adapter publishes readable input state and delegates submit with histo
469
  submitSearchQuery(query, options) { queries.push([query, {...options}]); }
470
  });
471
  c.setupSearchInput();
472
- assert.equal(c.searchInputReady, false, 'mounting alone does not complete startup');
473
  input.dispatchEvent(new Event('input'));
474
- assert.equal(c.searchInputReady, false, 'early input waits for route initialization');
475
  assert.equal(c.searchTimer, null);
476
  assert.equal(callback, undefined);
477
  c.finishInitialSearchInput(c.initialSearchDraftIsCurrent());
478
- assert.equal(c.searchInputReady, true, 'the controller publishes completed startup');
 
479
  input.dispatchEvent(new Event('input'));
480
  assert.equal(c.searchTimer, 42);
481
  callback();
 
36
  function transportFixture() {
37
  let now = 0, timerId = 0;
38
  const timers = new Map(), calls = [];
39
+ const c = fixture(['getSearchTransport', 'fetchSearchPage',
40
  'expireSearchRequests', 'normalizeSearchError', 'suspendSearchRequests', 'resumeSearchRequests'],
41
  {DOMException, document:{hidden:false}, APPEND_REQUEST_TIMEOUT:50,
42
  Date:{now:()=>now}, scheduleScrollRecovery(){},
 
451
  assert.equal(c.state.ready, true);
452
  });
453
 
454
+ test('app adapter waits for startup and delegates submit with history options', () => {
455
  const modules = vm.createContext({});
456
  for (const path of ['domain/ownership.js', 'application/controller.js'])
457
  vm.runInContext(fs.readFileSync('static/search/input/' + path, 'utf8'), modules);
 
469
  submitSearchQuery(query, options) { queries.push([query, {...options}]); }
470
  });
471
  c.setupSearchInput();
472
+ assert.equal(c.searchTimer, null, 'mounting alone does not schedule a search');
473
  input.dispatchEvent(new Event('input'));
474
+ assert.equal(c.initialSearchDraft, true, 'early input waits for route initialization');
475
  assert.equal(c.searchTimer, null);
476
  assert.equal(callback, undefined);
477
  c.finishInitialSearchInput(c.initialSearchDraftIsCurrent());
478
+ assert.equal(c.initialSearchDraft, false);
479
+ assert.equal(c.searchTimer, 42, 'startup schedules the current draft');
480
  input.dispatchEvent(new Event('input'));
481
  assert.equal(c.searchTimer, 42);
482
  callback();
tests/search/ui/history_quotation_contracts.mjs CHANGED
@@ -66,7 +66,7 @@ function historyFixture() {
66
  const submissions = [];
67
  c.submitSearchQuery = (...args) => { submissions.push(plain(args)); };
68
  c.searchHistoryStore = c.VoiceOfMLSearchHistoryStore.create(() => c.sessionStorage);
69
- for (const name of ['getSearchHistoryController', 'getHistory', 'saveHistory', 'addHistoryItem', 'renderDropdown', 'hideSearchHistory', 'setupSearchHistory', 'removeHistoryItem']) {
70
  const source = app.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));
71
  // Single-line host wrappers end on their declaration line.
72
  const line = app.split('\n').find(line => line.startsWith('function ' + name + '('));
@@ -101,20 +101,20 @@ test('history and quotation are registered in HTML, composition, resources, offl
101
 
102
  test('history rejects corrupt session JSON, storage failures, live preference, empty query and capped deduplication', () => {
103
  const f = historyFixture(), {c} = f;
104
- for (const value of [null, '{bad', 'false', '0', 'null']) { f.setStored(value); assert.deepEqual(plain(c.getHistory()), []); }
105
  f.setStored('{"unexpected":true}');
106
- assert.deepEqual(plain(c.getHistory()), []);
107
  f.setStored(JSON.stringify([null, {}, 1, "valid", ...Array.from({length:25}, (_, i)=>String(i))]));
108
- assert.deepEqual(plain(c.getHistory()), ["valid", ...Array.from({length:19}, (_, i)=>String(i))]);
109
  c.renderDropdown(); assert.equal(f.rows.length, 20); assert.match(f.dropdown.innerHTML, /history-clear-all/);
110
  c.saveHistory([]);
111
  for (let i = 0; i < 25; i++) c.addHistoryItem('q' + i);
112
- assert.equal(c.getHistory().length, 20); assert.equal(c.getHistory()[19], 'q5');
113
- c.addHistoryItem('q12'); assert.equal(c.getHistory()[0], 'q12'); assert.equal(c.getHistory().length, 20);
114
- c.addHistoryItem(''); c.STATE.recordHistory = false; c.addHistoryItem('disabled'); assert.equal(c.getHistory()[0], 'q12');
115
- c.STATE.recordHistory = true; c.addHistoryItem('live'); assert.equal(c.getHistory()[0], 'live');
116
  c.sessionStorage = {getItem() { throw Error('denied'); }, setItem() { throw Error('full'); }};
117
- assert.deepEqual(plain(c.getHistory()), []); assert.doesNotThrow(() => c.addHistoryItem('safe'));
118
  });
119
 
120
  test('history keyboard, delete focus, native activation, clear and submission ownership survive extraction', () => {
@@ -125,14 +125,14 @@ test('history keyboard, delete focus, native activation, clear and submission ow
125
  f.key('ArrowDown', f.rows[0].text); assert.equal(c.document.activeElement, f.rows[1].text);
126
  f.rows[1].del.focus(); c.renderDropdown(); assert.equal(c.document.activeElement, f.rows[1].del);
127
  f.dropdown.fire('click', {target: f.rows[1].del, detail: 0});
128
- assert.deepEqual(plain(c.getHistory()), ['one', 'three']); assert.equal(c.document.activeElement, f.rows[1].text);
129
  f.dropdown.fire('click', {target: f.rows[1].text, detail: 0});
130
  assert.deepEqual(f.submissions, [['three', {restore: true, blur: true}]]); assert.equal(c.document.activeElement, f.results);
131
  f.input.focus(); assert.ok(f.key('Escape').stopped); assert.equal(c.document.activeElement, f.input); assert.equal(f.dropdown.style.display, 'none');
132
  f.input.focus(); f.key('ArrowUp'); assert.equal(c.document.activeElement, f.input);
133
  const clear = {closest: selector => selector === '.history-clear-all' ? clear : null};
134
  f.dropdown.fire('click', {target: clear, detail: 0});
135
- assert.deepEqual(plain(c.getHistory()), []); assert.equal(f.dropdown.style.display, 'none'); assert.equal(c.document.activeElement, f.input);
136
  });
137
 
138
  test('history arrow navigation lets the browser scroll the focused entry into view', () => {
@@ -162,7 +162,7 @@ test('history preserves listener order, live IME guards, hover/blur delay and lo
162
  f.dropdown.fire('mouseleave'); await f.fire(150); assert.equal(f.dropdown.style.display, 'none');
163
  f.input.focus(); f.dropdown.fire('touchstart', {target: f.rows[0].text}); f.dropdown.fire('touchcancel'); assert.equal([...f.timers.values()].some(t => t.delay === 600), false);
164
  const old = f.rows[0].text; f.dropdown.fire('mousedown', {target: old}); await f.fire(600);
165
- f.dropdown.fire('click', {target: old, detail: 1}); assert.equal(f.submissions.length, 0); assert.deepEqual(plain(c.getHistory()), ['two']);
166
  f.dropdown.fire('click', {target: f.rows[0].text, detail: 0}); assert.equal(f.submissions.length, 1);
167
  f.input.focus(); c.document.fire('pointerdown', {target: f.results}); assert.equal(f.dropdown.style.display, 'none');
168
  });
 
66
  const submissions = [];
67
  c.submitSearchQuery = (...args) => { submissions.push(plain(args)); };
68
  c.searchHistoryStore = c.VoiceOfMLSearchHistoryStore.create(() => c.sessionStorage);
69
+ for (const name of ['getSearchHistoryController', 'saveHistory', 'addHistoryItem', 'renderDropdown', 'hideSearchHistory', 'setupSearchHistory']) {
70
  const source = app.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm'));
71
  // Single-line host wrappers end on their declaration line.
72
  const line = app.split('\n').find(line => line.startsWith('function ' + name + '('));
 
101
 
102
  test('history rejects corrupt session JSON, storage failures, live preference, empty query and capped deduplication', () => {
103
  const f = historyFixture(), {c} = f;
104
+ for (const value of [null, '{bad', 'false', '0', 'null']) { f.setStored(value); assert.deepEqual(plain(c.searchHistoryStore.get()), []); }
105
  f.setStored('{"unexpected":true}');
106
+ assert.deepEqual(plain(c.searchHistoryStore.get()), []);
107
  f.setStored(JSON.stringify([null, {}, 1, "valid", ...Array.from({length:25}, (_, i)=>String(i))]));
108
+ assert.deepEqual(plain(c.searchHistoryStore.get()), ["valid", ...Array.from({length:19}, (_, i)=>String(i))]);
109
  c.renderDropdown(); assert.equal(f.rows.length, 20); assert.match(f.dropdown.innerHTML, /history-clear-all/);
110
  c.saveHistory([]);
111
  for (let i = 0; i < 25; i++) c.addHistoryItem('q' + i);
112
+ assert.equal(c.searchHistoryStore.get().length, 20); assert.equal(c.searchHistoryStore.get()[19], 'q5');
113
+ c.addHistoryItem('q12'); assert.equal(c.searchHistoryStore.get()[0], 'q12'); assert.equal(c.searchHistoryStore.get().length, 20);
114
+ c.addHistoryItem(''); c.STATE.recordHistory = false; c.addHistoryItem('disabled'); assert.equal(c.searchHistoryStore.get()[0], 'q12');
115
+ c.STATE.recordHistory = true; c.addHistoryItem('live'); assert.equal(c.searchHistoryStore.get()[0], 'live');
116
  c.sessionStorage = {getItem() { throw Error('denied'); }, setItem() { throw Error('full'); }};
117
+ assert.deepEqual(plain(c.searchHistoryStore.get()), []); assert.doesNotThrow(() => c.addHistoryItem('safe'));
118
  });
119
 
120
  test('history keyboard, delete focus, native activation, clear and submission ownership survive extraction', () => {
 
125
  f.key('ArrowDown', f.rows[0].text); assert.equal(c.document.activeElement, f.rows[1].text);
126
  f.rows[1].del.focus(); c.renderDropdown(); assert.equal(c.document.activeElement, f.rows[1].del);
127
  f.dropdown.fire('click', {target: f.rows[1].del, detail: 0});
128
+ assert.deepEqual(plain(c.searchHistoryStore.get()), ['one', 'three']); assert.equal(c.document.activeElement, f.rows[1].text);
129
  f.dropdown.fire('click', {target: f.rows[1].text, detail: 0});
130
  assert.deepEqual(f.submissions, [['three', {restore: true, blur: true}]]); assert.equal(c.document.activeElement, f.results);
131
  f.input.focus(); assert.ok(f.key('Escape').stopped); assert.equal(c.document.activeElement, f.input); assert.equal(f.dropdown.style.display, 'none');
132
  f.input.focus(); f.key('ArrowUp'); assert.equal(c.document.activeElement, f.input);
133
  const clear = {closest: selector => selector === '.history-clear-all' ? clear : null};
134
  f.dropdown.fire('click', {target: clear, detail: 0});
135
+ assert.deepEqual(plain(c.searchHistoryStore.get()), []); assert.equal(f.dropdown.style.display, 'none'); assert.equal(c.document.activeElement, f.input);
136
  });
137
 
138
  test('history arrow navigation lets the browser scroll the focused entry into view', () => {
 
162
  f.dropdown.fire('mouseleave'); await f.fire(150); assert.equal(f.dropdown.style.display, 'none');
163
  f.input.focus(); f.dropdown.fire('touchstart', {target: f.rows[0].text}); f.dropdown.fire('touchcancel'); assert.equal([...f.timers.values()].some(t => t.delay === 600), false);
164
  const old = f.rows[0].text; f.dropdown.fire('mousedown', {target: old}); await f.fire(600);
165
+ f.dropdown.fire('click', {target: old, detail: 1}); assert.equal(f.submissions.length, 0); assert.deepEqual(plain(c.searchHistoryStore.get()), ['two']);
166
  f.dropdown.fire('click', {target: f.rows[0].text, detail: 0}); assert.equal(f.submissions.length, 1);
167
  f.input.focus(); c.document.fire('pointerdown', {target: f.results}); assert.equal(f.dropdown.style.display, 'none');
168
  });
tests/search/ui/shell_contracts.mjs CHANGED
@@ -10,7 +10,7 @@ const names = ['search/shell/presentation/view.js', 'search/shell/application/co
10
  const app = fs.readFileSync('static/app.js', 'utf8');
11
  const space = fs.existsSync('pyrightconfig.json');
12
  const functions = ['getShell', 'toggleTheme', 'applyTheme', 'toggleMobile', 'applyMobileMode',
13
- 'focusSearchSidebar', 'toggleLeftSidebar', 'toggleRightSidebar', 'closeLeftSidebar',
14
  'closeRightSidebar', 'updateSidebarVisibility'];
15
 
16
  function fixture() {
@@ -173,6 +173,6 @@ test('sidebar focus skips disabled, invisible and hidden or inert controls and f
173
  const inertParent = f.element('inertParent', sidebar); inertParent.inert = true;
174
  const inert = f.element('inert', inertParent);
175
  sidebar.controls = [disabled, invisible, inert, f.leftControl];
176
- f.c.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, f.leftControl);
177
- sidebar.controls.pop(); f.c.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, sidebar);
178
  });
 
10
  const app = fs.readFileSync('static/app.js', 'utf8');
11
  const space = fs.existsSync('pyrightconfig.json');
12
  const functions = ['getShell', 'toggleTheme', 'applyTheme', 'toggleMobile', 'applyMobileMode',
13
+ 'toggleLeftSidebar', 'toggleRightSidebar', 'closeLeftSidebar',
14
  'closeRightSidebar', 'updateSidebarVisibility'];
15
 
16
  function fixture() {
 
173
  const inertParent = f.element('inertParent', sidebar); inertParent.inert = true;
174
  const inert = f.element('inert', inertParent);
175
  sidebar.controls = [disabled, invisible, inert, f.leftControl];
176
+ f.c.VoiceOfMLShellView.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, f.leftControl);
177
+ sidebar.controls.pop(); f.c.VoiceOfMLShellView.focusSearchSidebar(sidebar); assert.equal(f.document.activeElement, sidebar);
178
  });
tests/search/ui/virtual_results_contracts.mjs CHANGED
@@ -76,10 +76,11 @@ function fixture(count = 100) {
76
  } else {
77
  c.VSCROLL = c.VoiceOfMLVirtualHeights.createState();
78
  vm.runInContext(source.match(/^function getVirtualResults\([^]*?^}/m)[0], c);
79
- for (const name of names.filter(n => !['layoutResultScrollSegment', 'reconcileVirtualRows'].includes(n))) {
80
  const match = source.match(new RegExp('^function ' + name + '\\([^\\n]*', 'm'));
81
  vm.runInContext(match[0], c);
82
  }
 
83
  }
84
  return {c, STATE, list, container, events, frames, document,
85
  flush() { const pending = [...frames.values()]; frames.clear(); for (const fn of pending) fn(); },
 
76
  } else {
77
  c.VSCROLL = c.VoiceOfMLVirtualHeights.createState();
78
  vm.runInContext(source.match(/^function getVirtualResults\([^]*?^}/m)[0], c);
79
+ for (const name of names.filter(n => !['layoutResultScrollSegment', 'reconcileVirtualRows', 'measureHeights'].includes(n))) {
80
  const match = source.match(new RegExp('^function ' + name + '\\([^\\n]*', 'm'));
81
  vm.runInContext(match[0], c);
82
  }
83
+ c.measureHeights = c.getVirtualResults().measureHeights;
84
  }
85
  return {c, STATE, list, container, events, frames, document,
86
  flush() { const pending = [...frames.values()]; frames.clear(); for (const fn of pending) fn(); },
typings/reader-chapter-format-strict.d.ts CHANGED
@@ -28,7 +28,7 @@ export interface ChapterFormatContext {
28
  assertReaderActive(): void;
29
  trustedReaderAssetManifestUrl(url: string): string | null;
30
  trustedChapterUrl(path: string, base: string): string | null;
31
- trustedChapterResourceUrl(value: string, base: string, attribute: string, manifestBase: string): string | null;
32
  trustedChapterReferenceUrl(value: string | null, base: string | null, manifestBase: string): {url: string; fragment: string} | null;
33
  readerContentUrl(url: string): string;
34
  isReaderGenerationCurrent(kind: string, generation: number): boolean;
 
28
  assertReaderActive(): void;
29
  trustedReaderAssetManifestUrl(url: string): string | null;
30
  trustedChapterUrl(path: string, base: string): string | null;
31
+ trustedChapterResourceUrl(raw: string, base: string, manifestBase: string): string | null;
32
  trustedChapterReferenceUrl(value: string | null, base: string | null, manifestBase: string): {url: string; fragment: string} | null;
33
  readerContentUrl(url: string): string;
34
  isReaderGenerationCurrent(kind: string, generation: number): boolean;
typings/reader-pdf-engine-strict.d.ts CHANGED
@@ -33,7 +33,7 @@ export interface RangeHooks {
33
  export interface EngineContext {
34
  assertReaderActive(): void; readerAbortError(): Error; trackReaderResource(destroy: () => void): () => void;
35
  readerAbortController: AbortController; READER_PROXY_TIMEOUT_MS: number;
36
- sourceUrl: string; contentUrl: string; PDFJS_WORKER_URL: string; PDFJS_URL: string;
37
  PDFJS_WASM_URL: string; PDFJS_CMAP_URL: string; PDFJS_STANDARD_FONT_URL: string;
38
  capability: { mode?: string | null }; extension: string; ocrManifestUrl: string | null; pdfV3Manifest: unknown;
39
  readerRestorationLoaded: boolean; restorationFailed: boolean; readerRestorationEntry: Restoration | null;
@@ -45,7 +45,7 @@ export interface EngineContext {
45
  preparePdfInitialRange(options: {url: string; rangeChunkSize: number}, hooks: RangeHooks): Promise<InitialRange | null>;
46
  retryReaderProxy<T>(callback: () => Promise<T>): Promise<T>; retryableReaderProxyError(error: unknown): boolean;
47
  loadPdfTaskWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, url: string, initial?: Initial): Promise<PdfDocument>;
48
- loadPdfWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, target?: string, proxy?: string, takeInitial?: (url: string) => Initial): Promise<PdfDocument>;
49
  preloadPdfEngine(): Promise<PdfModule>; loadPdfEngine(): Promise<PdfModule>;
50
  preparePdfWorker(pdfjs: PdfModule, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;
51
  preparePdfWorkerAttempt(pdfjs: PdfModule, attempt: number, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;
 
33
  export interface EngineContext {
34
  assertReaderActive(): void; readerAbortError(): Error; trackReaderResource(destroy: () => void): () => void;
35
  readerAbortController: AbortController; READER_PROXY_TIMEOUT_MS: number;
36
+ sourceUrl: string; PDFJS_WORKER_URL: string; PDFJS_URL: string;
37
  PDFJS_WASM_URL: string; PDFJS_CMAP_URL: string; PDFJS_STANDARD_FONT_URL: string;
38
  capability: { mode?: string | null }; extension: string; ocrManifestUrl: string | null; pdfV3Manifest: unknown;
39
  readerRestorationLoaded: boolean; restorationFailed: boolean; readerRestorationEntry: Restoration | null;
 
45
  preparePdfInitialRange(options: {url: string; rangeChunkSize: number}, hooks: RangeHooks): Promise<InitialRange | null>;
46
  retryReaderProxy<T>(callback: () => Promise<T>): Promise<T>; retryableReaderProxyError(error: unknown): boolean;
47
  loadPdfTaskWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, url: string, initial?: Initial): Promise<PdfDocument>;
48
+ loadPdfWithTimeout(pdfjs: PdfModule, options: (url: string) => PdfOptions, proxyUrl: string, takeInitial?: (url: string) => Initial): Promise<PdfDocument>;
49
  preloadPdfEngine(): Promise<PdfModule>; loadPdfEngine(): Promise<PdfModule>;
50
  preparePdfWorker(pdfjs: PdfModule, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;
51
  preparePdfWorkerAttempt(pdfjs: PdfModule, attempt: number, firstPage?: boolean, signal?: AbortSignal | null): Promise<PdfModule>;