vomebook commited on
Commit
58d59b4
·
1 Parent(s): a055f49

Fix reviewed search and Reader regressions

Browse files
backend/reader/document/http/transport.py CHANGED
@@ -27,7 +27,7 @@ class DocumentState(RangeCacheState, Protocol):
27
  class OpenResponse(Protocol):
28
  def __call__(self, session: object, url: str, timeout: aiohttp.ClientTimeout, *,
29
  method: str, request_headers: dict[str, str], url_validator: Callable[[str], str],
30
- auto_decompress: bool) -> Awaitable[aiohttp.ClientResponse]: ...
31
 
32
 
33
  class ProxyTiming(Protocol):
@@ -206,6 +206,8 @@ async def stream_document(
206
  request_headers=forwarded_headers,
207
  url_validator=url_validator,
208
  auto_decompress=False,
 
 
209
  )
210
  headers_at = deps.clock()
211
  if upstream.status == 429:
 
27
  class OpenResponse(Protocol):
28
  def __call__(self, session: object, url: str, timeout: aiohttp.ClientTimeout, *,
29
  method: str, request_headers: dict[str, str], url_validator: Callable[[str], str],
30
+ auto_decompress: bool, cache_redirects: bool = True) -> Awaitable[aiohttp.ClientResponse]: ...
31
 
32
 
33
  class ProxyTiming(Protocol):
 
206
  request_headers=forwarded_headers,
207
  url_validator=url_validator,
208
  auto_decompress=False,
209
+ # Validate freshness against the source, not an older signed target.
210
+ cache_redirects=not (fresh_range or has_conditionals),
211
  )
212
  headers_at = deps.clock()
213
  if upstream.status == 429:
quality/reviewed-audit-source-transition.json CHANGED
@@ -128,7 +128,7 @@
128
  ]
129
  },
130
  "backend/reader/document/http/transport.py": {
131
- "current_sha256": "641f1f6282542946dd5d0ab9ac7a85d7b506a109e104063839b07ffc5b299faa",
132
  "parent_sha256": "4c75cd63a93bcdf1d7b03949d6478cb8d35f74b5fc869e2895b3a6f54b96cb92",
133
  "hunks": [
134
  [
@@ -136,13 +136,23 @@
136
  "from backend.reader.document.domain.range_cache import (RangeCacheState, range_cache_seconds,\n requires_fresh_range, resident_age_headers)\n",
137
  "from backend.reader.document.domain.range_cache import RangeCacheState, range_cache_seconds, requires_fresh_range\n"
138
  ],
 
 
 
 
 
139
  [
140
  170,
141
  " current_time = deps.clock()\n if current_time - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n cached_headers = resident_age_headers(cached_headers, cached_at, current_time)\n",
142
  " if deps.clock() - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n"
143
  ],
144
  [
145
- 210,
 
 
 
 
 
146
  " if upstream.status == 429:\n # We generate our own error body, so do not copy its upstream\n # representation headers. Keep the origin's retry deadline even\n # when its (unused) error body is compressed or too large.\n retry_headers = {\"Cache-Control\": \"no-store\"}\n retry_after = upstream.headers.get(\"Retry-After\", \"\").strip()\n if re.fullmatch(r\"[ -~]{1,128}\", retry_after):\n retry_headers[\"Retry-After\"] = retry_after\n if request.method == \"HEAD\":\n return Response(status_code=429, headers=retry_headers)\n return JSONResponse({\"error\": \"上游阅读文件加载失败: HTTP 429\"},\n status_code=429, headers=retry_headers)\n",
147
  ""
148
  ]
 
128
  ]
129
  },
130
  "backend/reader/document/http/transport.py": {
131
+ "current_sha256": "6a39be6b5adb79031dbedf75bcae5c93a83fd8fb1d3f89db5f1c2c6bd430110d",
132
  "parent_sha256": "4c75cd63a93bcdf1d7b03949d6478cb8d35f74b5fc869e2895b3a6f54b96cb92",
133
  "hunks": [
134
  [
 
136
  "from backend.reader.document.domain.range_cache import (RangeCacheState, range_cache_seconds,\n requires_fresh_range, resident_age_headers)\n",
137
  "from backend.reader.document.domain.range_cache import RangeCacheState, range_cache_seconds, requires_fresh_range\n"
138
  ],
139
+ [
140
+ 29,
141
+ " auto_decompress: bool, cache_redirects: bool = True) -> Awaitable[aiohttp.ClientResponse]: ...\n",
142
+ " auto_decompress: bool) -> Awaitable[aiohttp.ClientResponse]: ...\n"
143
+ ],
144
  [
145
  170,
146
  " current_time = deps.clock()\n if current_time - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n cached_headers = resident_age_headers(cached_headers, cached_at, current_time)\n",
147
  " if deps.clock() - cached_at < range_cache_seconds(cached_headers, deps.cache_ttl()):\n"
148
  ],
149
  [
150
+ 208,
151
+ " # Validate freshness against the source, not an older signed target.\n cache_redirects=not (fresh_range or has_conditionals),\n",
152
+ ""
153
+ ],
154
+ [
155
+ 212,
156
  " if upstream.status == 429:\n # We generate our own error body, so do not copy its upstream\n # representation headers. Keep the origin's retry deadline even\n # when its (unused) error body is compressed or too large.\n retry_headers = {\"Cache-Control\": \"no-store\"}\n retry_after = upstream.headers.get(\"Retry-After\", \"\").strip()\n if re.fullmatch(r\"[ -~]{1,128}\", retry_after):\n retry_headers[\"Retry-After\"] = retry_after\n if request.method == \"HEAD\":\n return Response(status_code=429, headers=retry_headers)\n return JSONResponse({\"error\": \"上游阅读文件加载失败: HTTP 429\"},\n status_code=429, headers=retry_headers)\n",
157
  ""
158
  ]
scripts/backend_paths.py CHANGED
@@ -14,7 +14,7 @@ MAP_SHA = 'de3275d169af9795a92185609797178a282802309f43c1f2628e65b75f0b6e76'
14
  TRANSITION_FILE = 'quality/reviewed-functional-source-transition.json'
15
  TRANSITION_SHA = '3b284323fdf226820b69b074473f7933f563bf41f3d011bdbb9273be0efeb97b'
16
  AUDIT_TRANSITION_FILE = 'quality/reviewed-audit-source-transition.json'
17
- AUDIT_TRANSITION_SHA = '275e5d37fb79e1d80e2f3e22e9c25d67d620549d376003d66128a94edb4b9570'
18
  SEARCH_PERF_TRANSITION_FILE = 'quality/reviewed-wildcard-scope-transition.json'
19
  SEARCH_PERF_TRANSITION_SHA = 'b60180abab5ccc8a0af958e60f4cabe46e2fab6c439c1d3150762324dcd6a48a'
20
  # These files have exact Refactor23 hashes but no import-relocation entries.
 
14
  TRANSITION_FILE = 'quality/reviewed-functional-source-transition.json'
15
  TRANSITION_SHA = '3b284323fdf226820b69b074473f7933f563bf41f3d011bdbb9273be0efeb97b'
16
  AUDIT_TRANSITION_FILE = 'quality/reviewed-audit-source-transition.json'
17
+ AUDIT_TRANSITION_SHA = 'd07320b74be14a5e3f4f1dcf4c766deee50441306bf470be8504f488111cd6d4'
18
  SEARCH_PERF_TRANSITION_FILE = 'quality/reviewed-wildcard-scope-transition.json'
19
  SEARCH_PERF_TRANSITION_SHA = 'b60180abab5ccc8a0af958e60f4cabe46e2fab6c439c1d3150762324dcd6a48a'
20
  # These files have exact Refactor23 hashes but no import-relocation entries.
static/app.js CHANGED
@@ -2482,9 +2482,14 @@ function clearResultsSkeleton() {
2482
  }
2483
 
2484
  function renderResults(animate = false) {
2485
- pendingResultEntrance = false;
2486
  if (!positionRestore && STATE._loadedPage >= 1) rememberDisplayedSearchView();
2487
  activateSearchView();
 
 
 
 
 
 
2488
  clearResultsSkeleton();
2489
  if (STATE.results.length === 0) {
2490
  DOM.resultsList.innerHTML = "";
@@ -3696,7 +3701,7 @@ async function init() {
3696
  if (DOM.mirrorLinksToggle) DOM.mirrorLinksToggle.addEventListener("change", () => {
3697
  STATE.useMirrorLinks = DOM.mirrorLinksToggle.checked;
3698
  syncStateToURL(true);
3699
- if (STATE.results.length > 0) renderResults();
3700
  });
3701
  getResultInteractions().installSelection();
3702
  DOM.hamburgerBtn.addEventListener("click", toggleLeftSidebar);
 
2482
  }
2483
 
2484
  function renderResults(animate = false) {
 
2485
  if (!positionRestore && STATE._loadedPage >= 1) rememberDisplayedSearchView();
2486
  activateSearchView();
2487
+ redrawResults(animate);
2488
+ }
2489
+
2490
+ // Presentation changes must not assign the pending search key to existing rows.
2491
+ function redrawResults(animate = false) {
2492
+ pendingResultEntrance = false;
2493
  clearResultsSkeleton();
2494
  if (STATE.results.length === 0) {
2495
  DOM.resultsList.innerHTML = "";
 
3701
  if (DOM.mirrorLinksToggle) DOM.mirrorLinksToggle.addEventListener("change", () => {
3702
  STATE.useMirrorLinks = DOM.mirrorLinksToggle.checked;
3703
  syncStateToURL(true);
3704
+ if (STATE.results.length > 0) redrawResults();
3705
  });
3706
  getResultInteractions().installSelection();
3707
  DOM.hamburgerBtn.addEventListener("click", toggleLeftSidebar);
static/reader/core/reader-bindings.mjs CHANGED
@@ -541,6 +541,8 @@ export function createReaderBindings(readerContext) {
541
  /** @type {Element} */ (document.querySelector("#bookmark-add")).addEventListener("click", async (event) => {
542
  const button = /** @type {HTMLButtonElement} */ (event.currentTarget),
543
  editing = readerContext.panelState.editingBookmark;
 
 
544
  const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();
545
  const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,
546
  excerpt = readerContext.bookmarkExcerptInput.value.trim();
@@ -561,6 +563,7 @@ export function createReaderBindings(readerContext) {
561
  createdAt: Date.now()
562
  }
563
  );
 
564
  const invoker = readerContext.bookmarkInvoker;
565
  readerContext.closeBookmarkPopover();
566
  if (!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden) {
@@ -573,9 +576,10 @@ export function createReaderBindings(readerContext) {
573
  ).focus();
574
  }
575
  } catch (_) {
576
- /** @type {Element} */ (document.querySelector("#bookmark-prompt")).textContent = "书签保存失败,请重试。";
 
577
  } finally {
578
- button.disabled = false;
579
  }
580
  });
581
  readerContext.bookmarkPopover.addEventListener("keydown", (event) => {
 
541
  /** @type {Element} */ (document.querySelector("#bookmark-add")).addEventListener("click", async (event) => {
542
  const button = /** @type {HTMLButtonElement} */ (event.currentTarget),
543
  editing = readerContext.panelState.editingBookmark;
544
+ const saveGeneration = readerContext.nextReaderGeneration("bookmark-dialog");
545
+ const ownsDialog = () => readerContext.isReaderGenerationCurrent("bookmark-dialog", saveGeneration);
546
  const snapshot = readerContext.pendingBookmarkSnapshot || editing || readerContext.captureBookmarkSnapshot();
547
  const label = readerContext.bookmarkLabelInput.value.trim() || snapshot.label,
548
  excerpt = readerContext.bookmarkExcerptInput.value.trim();
 
563
  createdAt: Date.now()
564
  }
565
  );
566
+ if (!ownsDialog()) return;
567
  const invoker = readerContext.bookmarkInvoker;
568
  readerContext.closeBookmarkPopover();
569
  if (!/** @type {HTMLElement} */ (document.querySelector("#bookmarks-panel")).hidden) {
 
576
  ).focus();
577
  }
578
  } catch (_) {
579
+ if (ownsDialog())
580
+ /** @type {Element} */ (document.querySelector("#bookmark-prompt")).textContent = "书签保存失败,请重试。";
581
  } finally {
582
+ if (ownsDialog()) button.disabled = false;
583
  }
584
  });
585
  readerContext.bookmarkPopover.addEventListener("keydown", (event) => {
static/reader/formats/reader-chapter-format.mjs CHANGED
@@ -1,4 +1,5 @@
1
  import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs";
 
2
 
3
  // The current MOBI chapter manifest for this five-volume edition contains
4
  // cross-volume sidebar targets that point back into volume 1. Its own verified
@@ -747,10 +748,9 @@ export function createReaderChapterFormat(readerContext) {
747
  readerContext.chapterManifestLoader = chapterManifestLoader;
748
  setChapterToc();
749
  await readerContext.getInitialReaderRestoration();
750
- const savedChapter = Number(readerContext.readerRestorationEntry?.chapterIndex) - 1;
751
- const initialChapter = Number.isInteger(savedChapter)
752
- ? Math.max(0, Math.min(manifest.chapters.length - 1, savedChapter))
753
- : 0;
754
  const initial = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter]);
755
  chapterFocusIndex = initial.index;
756
  if (initialChapter > 0) ensureSentinel(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter - 1]), true);
@@ -764,7 +764,7 @@ export function createReaderChapterFormat(readerContext) {
764
  chapterScheduler.prefetch(chapterPrefetchIndices());
765
  await readerContext.awaitReader(Promise.race([firstChapter, openingLanding.promise]));
766
  } catch (error) {
767
- if (readerContext.readerRestorationEntry?.chapterIndex == null) throw error;
768
  throw Object.assign(new Error("阅读位置恢复失败,原进度已保留,请重试加载。", { cause: error }), {
769
  code: "READER_RESTORE"
770
  });
@@ -806,13 +806,11 @@ export function createReaderChapterFormat(readerContext) {
806
  /** @param {import("../../../typings/reader-progress-strict").ProgressState} entry @param {number} generation
807
  * @param {number} [progressFraction] A transient slider target, never stored in a bookmark or history entry. */
808
  async function restoreChapterPosition(entry, generation, progressFraction) {
809
- if (
810
- /-epub-chapters-v5\//.test(readerContext.chapterManifestUrl || readerContext.sourceUrl) &&
811
- entry.chapterManifest !== (readerContext.chapterManifestUrl || readerContext.sourceUrl)
812
- ) return false;
813
  const loader = readerContext.chapterManifestLoader;
814
- if (!loader || entry.chapterIndex === undefined || !Number.isInteger(entry.chapterIndex) ||
815
- !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
 
 
816
  const chapter = await loader(entry.chapterIndex);
817
  if (!chapter?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
818
  const viewport = readerContext.viewport, last = entry.chapterIndex === loader.count;
 
1
  import { EBOOK_LAYOUT_STYLE, wrapEbookTables } from "../ui/reader-document-styles.mjs";
2
+ import { chapterIndexInRange, matchesChapterManifest } from "../ui/reader-progress.mjs";
3
 
4
  // The current MOBI chapter manifest for this five-volume edition contains
5
  // cross-volume sidebar targets that point back into volume 1. Its own verified
 
748
  readerContext.chapterManifestLoader = chapterManifestLoader;
749
  setChapterToc();
750
  await readerContext.getInitialReaderRestoration();
751
+ const savedChapter = readerContext.readerRestorationEntry?.chapterIndex;
752
+ const hasSavedChapter = chapterIndexInRange(savedChapter, manifest.chapters.length);
753
+ const initialChapter = hasSavedChapter ? savedChapter - 1 : 0;
 
754
  const initial = /** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter]);
755
  chapterFocusIndex = initial.index;
756
  if (initialChapter > 0) ensureSentinel(/** @type {import("../../../typings/reader-chapter-format-strict").Chapter} */ (manifest.chapters[initialChapter - 1]), true);
 
764
  chapterScheduler.prefetch(chapterPrefetchIndices());
765
  await readerContext.awaitReader(Promise.race([firstChapter, openingLanding.promise]));
766
  } catch (error) {
767
+ if (!hasSavedChapter) throw error;
768
  throw Object.assign(new Error("阅读位置恢复失败,原进度已保留,请重试加载。", { cause: error }), {
769
  code: "READER_RESTORE"
770
  });
 
806
  /** @param {import("../../../typings/reader-progress-strict").ProgressState} entry @param {number} generation
807
  * @param {number} [progressFraction] A transient slider target, never stored in a bookmark or history entry. */
808
  async function restoreChapterPosition(entry, generation, progressFraction) {
 
 
 
 
809
  const loader = readerContext.chapterManifestLoader;
810
+ if (!loader || !chapterIndexInRange(entry.chapterIndex, loader.count) ||
811
+ !readerContext.isReaderGenerationCurrent("navigation", generation) ||
812
+ !matchesChapterManifest(entry.chapterManifest, readerContext.chapterManifestUrl || readerContext.sourceUrl,
813
+ readerContext.trustedReaderAssetManifestUrl)) return false;
814
  const chapter = await loader(entry.chapterIndex);
815
  if (!chapter?.isConnected || !readerContext.isReaderGenerationCurrent("navigation", generation)) return false;
816
  const viewport = readerContext.viewport, last = entry.chapterIndex === loader.count;
static/reader/formats/reader-html-format.mjs CHANGED
@@ -518,7 +518,33 @@ export function createReaderHtmlFormat(readerContext) {
518
  function sanitizeOfflineHtml(text) {
519
  // A global ALLOWED_URI_REGEXP would also strip every non-allow-listed plain
520
  // attribute (colspan/rowspan/width), so scope the inline-image rule to URLs.
521
- DOMPurify.addHook("uponSanitizeAttribute", restrictOfflineUrlAttribute);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  let clean;
523
  try {
524
  clean = DOMPurify.sanitize(text, {
@@ -529,7 +555,7 @@ export function createReaderHtmlFormat(readerContext) {
529
  FORBID_ATTR: ["action", "formaction", "srcdoc"]
530
  });
531
  } finally {
532
- DOMPurify.removeHook("uponSanitizeAttribute", restrictOfflineUrlAttribute);
533
  }
534
  const template = document.createElement("template");
535
  template.content.appendChild(clean);
 
518
  function sanitizeOfflineHtml(text) {
519
  // A global ALLOWED_URI_REGEXP would also strip every non-allow-listed plain
520
  // attribute (colspan/rowspan/width), so scope the inline-image rule to URLs.
521
+ // Use the original document URL, not the proxy, srcdoc, or a supplied <base>.
522
+ /** @type {URL | null} */
523
+ let base = null;
524
+ try {
525
+ const original = new URL(readerContext.downloadUrl || readerContext.sourceUrl);
526
+ if (/^https?:$/.test(original.protocol) && !original.username && !original.password) {
527
+ original.hash = "";
528
+ base = original;
529
+ }
530
+ } catch (_) {}
531
+ /** @param {Element} node @param {{attrName: string, attrValue: string, keepAttr: boolean}} data */
532
+ const restrict = (node, data) => {
533
+ if (base && data.attrName === "href" && node.localName === "a") {
534
+ const value = data.attrValue, hashIndex = value.indexOf("#");
535
+ if (hashIndex > 0 && !/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(value) &&
536
+ !/[\u0000-\u001f\u007f-\u009f\\]/.test(value)) {
537
+ try {
538
+ const target = new URL(value, base);
539
+ target.hash = "";
540
+ // Compare the full URL, including the query, before keeping only the fragment.
541
+ if (target.href === base.href) data.attrValue = value.slice(hashIndex);
542
+ } catch (_) {}
543
+ }
544
+ }
545
+ restrictOfflineUrlAttribute(node, data);
546
+ };
547
+ DOMPurify.addHook("uponSanitizeAttribute", restrict);
548
  let clean;
549
  try {
550
  clean = DOMPurify.sanitize(text, {
 
555
  FORBID_ATTR: ["action", "formaction", "srcdoc"]
556
  });
557
  } finally {
558
+ DOMPurify.removeHook("uponSanitizeAttribute", restrict);
559
  }
560
  const template = document.createElement("template");
561
  template.content.appendChild(clean);
static/reader/pdf/reader-pdf-network.mjs CHANGED
@@ -4,6 +4,7 @@ import { PDF_ADAPTIVE_CHUNK_BYTES, PDF_LARGE_FLAT_CHUNK_BYTES, PDF_DEFAULT_CHUNK
4
  from "./reader-pdf-range-hints.mjs";
5
 
6
  export const PDF_METADATA_RANGE_CONCURRENCY = 24;
 
7
  const PDF_LARGE_FLAT_BATCH_DELAY_MS = 12;
8
  const PDF_LARGE_FLAT_GAP_BUDGET = PDF_LARGE_FLAT_CHUNK_BYTES * 3;
9
 
@@ -62,16 +63,26 @@ async function readPdfRange(options, begin, end, {signal, readBytes, limit, rang
62
  cached = rangeCache?.get(key, begin, Math.min(end, expected.total), {total:expected.total, etag:expected.etag});
63
  } catch (_) { /* Cache allocation failure must retain normal network reading. */ }
64
  if (cached && expected) return {bytes:cached, total:expected.total, etag:expected.etag};
 
 
65
  const response = await fetch(options.url, {
66
- headers: {Range: `bytes=${begin}-${end-1}`}, signal, credentials:"same-origin"
67
  });
68
  const invalid = () => new Error("PDF_RANGE_INVALID");
69
  try {
70
  if (!response.ok) throw Object.assign(new Error(`server response (${response.status})`), {status:response.status});
71
  if (!expected && response.status === 200) {
72
- if (partialOnly) { await response.body?.cancel(); return null; }
73
- const bytes = await readBytes(response, limit);
74
- return {bytes, complete:true};
 
 
 
 
 
 
 
 
75
  }
76
  const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get("Content-Range") || "");
77
  if (response.status !== 206 || !match) throw invalid();
@@ -95,7 +106,9 @@ async function readPdfRange(options, begin, end, {signal, readBytes, limit, rang
95
  catch (_) { /* Retaining an optional copy must never fail the document. */ }
96
  return {bytes, total, etag, complete:bytes.byteLength === total};
97
  } catch (error) {
98
- await response.body?.cancel().catch(() => {});
 
 
99
  throw error;
100
  }
101
  }
 
4
  from "./reader-pdf-range-hints.mjs";
5
 
6
  export const PDF_METADATA_RANGE_CONCURRENCY = 24;
7
+ const PDF_WHOLE_BODY_TIMEOUT_MS = 120000;
8
  const PDF_LARGE_FLAT_BATCH_DELAY_MS = 12;
9
  const PDF_LARGE_FLAT_GAP_BUDGET = PDF_LARGE_FLAT_CHUNK_BYTES * 3;
10
 
 
63
  cached = rangeCache?.get(key, begin, Math.min(end, expected.total), {total:expected.total, etag:expected.etag});
64
  } catch (_) { /* Cache allocation failure must retain normal network reading. */ }
65
  if (cached && expected) return {bytes:cached, total:expected.total, etag:expected.etag};
66
+ const wholeOwner = !expected && !partialOnly ? new AbortController() : null;
67
+ const active = wholeOwner ? AbortSignal.any([signal, wholeOwner.signal]) : signal;
68
  const response = await fetch(options.url, {
69
+ headers: {Range: `bytes=${begin}-${end-1}`}, signal:active, credentials:"same-origin"
70
  });
71
  const invalid = () => new Error("PDF_RANGE_INVALID");
72
  try {
73
  if (!response.ok) throw Object.assign(new Error(`server response (${response.status})`), {status:response.status});
74
  if (!expected && response.status === 200) {
75
+ if (!wholeOwner) { await response.body?.cancel(); return null; }
76
+ // The fetch policy hands off a 200 at headers. Native PDF staging can
77
+ // await this body before the Reader's document timer has even started.
78
+ const timer = setTimeout(() => wholeOwner.abort(new DOMException("PDF whole body timed out", "TimeoutError")),
79
+ PDF_WHOLE_BODY_TIMEOUT_MS);
80
+ try {
81
+ active.throwIfAborted();
82
+ const bytes = await abortable(readBytes(response, limit), active);
83
+ active.throwIfAborted();
84
+ return {bytes, complete:true};
85
+ } finally { clearTimeout(timer); }
86
  }
87
  const match = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get("Content-Range") || "");
88
  if (response.status !== 206 || !match) throw invalid();
 
106
  catch (_) { /* Retaining an optional copy must never fail the document. */ }
107
  return {bytes, total, etag, complete:bytes.byteLength === total};
108
  } catch (error) {
109
+ const cancelled = response.body?.cancel().catch(() => {});
110
+ // A failed whole-body read must settle without waiting for stream cleanup.
111
+ if (!wholeOwner || response.status !== 200) await cancelled;
112
  throw error;
113
  }
114
  }
static/reader/ui/reader-bookmarks.mjs CHANGED
@@ -190,6 +190,11 @@ export function createReaderBookmarks(readerContext) {
190
  remove.setAttribute("aria-label", `删除书签:${open.textContent}`);
191
  remove.addEventListener("click", async () => {
192
  await VoiceOfMLReaderStore.removeBookmark(entry.id);
 
 
 
 
 
193
  const restoreFocus = row.contains(document.activeElement);
194
  const next = row.nextElementSibling?.querySelector("button") || row.previousElementSibling?.querySelector("button") ||
195
  readerContext.bookmarksAllButton;
@@ -282,6 +287,7 @@ export function createReaderBookmarks(readerContext) {
282
  function openBookmarkPopover(invoker = readerContext.bookmarkRibbon, entry = null) {
283
  if (!entry && readerContext.pdfDocument?._pdfInfo?.readerPageCountPending) return;
284
  if (!readerContext.bookmarkPopover.hidden) return;
 
285
  readerContext.bookmarkInvoker = invoker;
286
  readerContext.pendingBookmarkSnapshot = entry ? null : readerContext.captureBookmarkSnapshot();
287
  readerContext.updatePanelState({ editingBookmark: entry ? { ...entry } : null });
@@ -291,7 +297,9 @@ export function createReaderBookmarks(readerContext) {
291
  : `在${snapshot.label}添加书签?`;
292
  readerContext.bookmarkLabelInput.value = snapshot.label || "";
293
  readerContext.bookmarkExcerptInput.value = typeof snapshot.excerpt === "string" ? snapshot.excerpt : "";
294
- /** @type {HTMLElement} */ (document.querySelector("#bookmark-add")).textContent = entry ? "保存书签" : "添加书签";
 
 
295
  readerContext.bookmarkPopover.hidden = false;
296
  invoker.setAttribute("aria-expanded", "true");
297
  invoker.setAttribute("aria-controls", readerContext.bookmarkPopover.id);
@@ -300,6 +308,7 @@ export function createReaderBookmarks(readerContext) {
300
  }
301
 
302
  function closeBookmarkPopover() {
 
303
  readerContext.pendingBookmarkSnapshot = null;
304
  readerContext.updatePanelState({ editingBookmark: null });
305
  readerContext.bookmarkPopover.hidden = true;
 
190
  remove.setAttribute("aria-label", `删除书签:${open.textContent}`);
191
  remove.addEventListener("click", async () => {
192
  await VoiceOfMLReaderStore.removeBookmark(entry.id);
193
+ if (!readerContext.isReaderGenerationCurrent("bookmarks", generation)) {
194
+ // A scope switch or remote refresh can replace this row with a stale copy.
195
+ await renderBookmarks();
196
+ return;
197
+ }
198
  const restoreFocus = row.contains(document.activeElement);
199
  const next = row.nextElementSibling?.querySelector("button") || row.previousElementSibling?.querySelector("button") ||
200
  readerContext.bookmarksAllButton;
 
287
  function openBookmarkPopover(invoker = readerContext.bookmarkRibbon, entry = null) {
288
  if (!entry && readerContext.pdfDocument?._pdfInfo?.readerPageCountPending) return;
289
  if (!readerContext.bookmarkPopover.hidden) return;
290
+ readerContext.nextReaderGeneration("bookmark-dialog");
291
  readerContext.bookmarkInvoker = invoker;
292
  readerContext.pendingBookmarkSnapshot = entry ? null : readerContext.captureBookmarkSnapshot();
293
  readerContext.updatePanelState({ editingBookmark: entry ? { ...entry } : null });
 
297
  : `在${snapshot.label}添加书签?`;
298
  readerContext.bookmarkLabelInput.value = snapshot.label || "";
299
  readerContext.bookmarkExcerptInput.value = typeof snapshot.excerpt === "string" ? snapshot.excerpt : "";
300
+ const save = /** @type {HTMLButtonElement} */ (document.querySelector("#bookmark-add"));
301
+ save.textContent = entry ? "保存书签" : "添加书签";
302
+ save.disabled = false;
303
  readerContext.bookmarkPopover.hidden = false;
304
  invoker.setAttribute("aria-expanded", "true");
305
  invoker.setAttribute("aria-controls", readerContext.bookmarkPopover.id);
 
308
  }
309
 
310
  function closeBookmarkPopover() {
311
+ readerContext.nextReaderGeneration("bookmark-dialog");
312
  readerContext.pendingBookmarkSnapshot = null;
313
  readerContext.updatePanelState({ editingBookmark: null });
314
  readerContext.bookmarkPopover.hidden = true;
static/reader/ui/reader-progress.mjs CHANGED
@@ -1,4 +1,24 @@
1
- /** @param {import('../../../typings/reader-progress-strict').ProgressContext} readerContext */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  export function createReaderProgress(readerContext) {
3
  function scheduleSave() {
4
  if (readerContext.readerLifecycle.disposed || readerContext.readerAbortController.signal.aborted) return;
@@ -128,8 +148,8 @@ export function createReaderProgress(readerContext) {
128
  const currentEntry = (entry) => {
129
  if (
130
  readerContext.capability.mode === "epub-chapters" &&
131
- /-epub-chapters-v5\//.test(readerContext.chapterManifestUrl || readerContext.sourceUrl) &&
132
- entry?.chapterManifest !== (readerContext.chapterManifestUrl || readerContext.sourceUrl)
133
  ) return null;
134
  return entry;
135
  };
@@ -312,6 +332,10 @@ export function createReaderProgress(readerContext) {
312
  /** @param {import('../../../typings/reader-progress-strict').ProgressState | null} entry
313
  * @param {number} generation */
314
  async function applyInitialRestoration(entry, generation) {
 
 
 
 
315
  readerContext.updateDocumentState({ restoredEntry: entry });
316
  // Startup already applied the current zoom. Reapplying an identical saved
317
  // value needlessly invalidates PDF canvases and lays out every format again.
 
1
+ /** @param {number | undefined} index @param {number} count @returns {index is number} */
2
+ export function chapterIndexInRange(index, count) {
3
+ return index !== undefined && Number.isInteger(index) && index >= 1 && index <= count;
4
+ }
5
+
6
+ /** @param {string | undefined} saved @param {string} current
7
+ * @param {(url: string) => string | null} trustedManifestUrl */
8
+ export function matchesChapterManifest(saved, current, trustedManifestUrl) {
9
+ if (saved === current) return true;
10
+ // Legacy v5 required an exact identity, including for direct bookmark restores.
11
+ if (/-epub-chapters-v5\//.test(current)) return false;
12
+ // Otherwise older positions can still restore if their chapter is in range.
13
+ if (typeof saved !== "string" || !saved) return true;
14
+ const previous = trustedManifestUrl(saved), active = trustedManifestUrl(current);
15
+ // The trusted resolver fixes the bucket and endpoint. Compare non-empty object
16
+ // paths, including the version, without mistaking URL spelling for a revision.
17
+ const savedPath = previous && new URL(previous).searchParams.get("path");
18
+ return !!savedPath && !!active && savedPath === new URL(active).searchParams.get("path");
19
+ }
20
+
21
+ /** @param {import('../../../typings/reader-progress-strict').ProgressContext & Pick<import('../../../typings/reader-chapter-format-strict').ChapterFormatContext, 'trustedReaderAssetManifestUrl'>} readerContext */
22
  export function createReaderProgress(readerContext) {
23
  function scheduleSave() {
24
  if (readerContext.readerLifecycle.disposed || readerContext.readerAbortController.signal.aborted) return;
 
148
  const currentEntry = (entry) => {
149
  if (
150
  readerContext.capability.mode === "epub-chapters" &&
151
+ entry && !matchesChapterManifest(entry.chapterManifest, readerContext.chapterManifestUrl || readerContext.sourceUrl,
152
+ readerContext.trustedReaderAssetManifestUrl)
153
  ) return null;
154
  return entry;
155
  };
 
332
  /** @param {import('../../../typings/reader-progress-strict').ProgressState | null} entry
333
  * @param {number} generation */
334
  async function applyInitialRestoration(entry, generation) {
335
+ // Ignore stale indices, not failures to load a chapter that still exists.
336
+ const loader = readerContext.chapterManifestLoader, index = entry?.chapterIndex;
337
+ if (readerContext.capability.mode === "epub-chapters" && loader && Number.isInteger(index) &&
338
+ !chapterIndexInRange(index, loader.count)) entry = null;
339
  readerContext.updateDocumentState({ restoredEntry: entry });
340
  // Startup already applied the current zoom. Reapplying an identical saved
341
  // value needlessly invalidates PDF canvases and lays out every format again.
tests/gates/test_static_contract.py CHANGED
@@ -481,8 +481,10 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected');
481
  assert_source_contains(self, 'frame.setAttribute("sandbox", "allow-same-origin")', reader)
482
  self.assertIn('"script"', reader)
483
  assert_source_contains(self, 'const OFFLINE_INLINE_IMAGE = /^data:image', reader)
484
- assert_source_contains(self, 'DOMPurify.addHook("uponSanitizeAttribute", restrictOfflineUrlAttribute)', reader)
485
- assert_source_contains(self, 'DOMPurify.removeHook("uponSanitizeAttribute", restrictOfflineUrlAttribute)', reader)
 
 
486
  assert_source_contains(self, 'template.content.querySelectorAll("style")', reader)
487
  assert_source_contains(self, 'template.content.querySelectorAll("[style]")', reader)
488
  self.assertIn('/^\\/datasets\\/VoiceOfML\\/[^/]+\\/(resolve|raw)\\//.test(url.pathname)', reader)
 
481
  assert_source_contains(self, 'frame.setAttribute("sandbox", "allow-same-origin")', reader)
482
  self.assertIn('"script"', reader)
483
  assert_source_contains(self, 'const OFFLINE_INLINE_IMAGE = /^data:image', reader)
484
+ assert_source_contains(self, 'if (target.href === base.href) data.attrValue = value.slice(hashIndex)', reader)
485
+ assert_source_contains(self, 'restrictOfflineUrlAttribute(node, data);', reader)
486
+ assert_source_contains(self, 'DOMPurify.addHook("uponSanitizeAttribute", restrict)', reader)
487
+ assert_source_contains(self, 'DOMPurify.removeHook("uponSanitizeAttribute", restrict)', reader)
488
  assert_source_contains(self, 'template.content.querySelectorAll("style")', reader)
489
  assert_source_contains(self, 'template.content.querySelectorAll("[style]")', reader)
490
  self.assertIn('/^\\/datasets\\/VoiceOfML\\/[^/]+\\/(resolve|raw)\\//.test(url.pathname)', reader)
tests/proxy/test_async_proxy.py CHANGED
@@ -11,7 +11,7 @@ import unittest
11
  from collections import OrderedDict
12
  from types import SimpleNamespace
13
  from unittest.mock import AsyncMock, Mock, patch
14
- from urllib.parse import unquote, urlencode
15
 
16
  IMPORT_ERROR = None
17
  try:
@@ -2187,6 +2187,52 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
2187
  self.assertEqual(len(session.urls), 3)
2188
  self.assertEqual(state.upstream_semaphore._value, 1)
2189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2190
  async def test_reader_range_age_limits_exact_and_containing_hits(self):
2191
  url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/document.pdf"
2192
  state = app.app.state
@@ -2345,10 +2391,11 @@ class AsyncProxyTests(unittest.IsolatedAsyncioTestCase):
2345
  return candidate
2346
  # A fresh attempt fails under the restrictive redirect policy; an exact
2347
  # or contained cached response must never use the looser policy.
2348
- for requested in ("bytes=0-3", "bytes=1-2"):
 
2349
  session.responses = [FakeResponse(302, {"Location":storage})]
2350
  response = await app._stream_reader_document(
2351
- SimpleNamespace(method="GET",headers={"Range":requested}),url,url_validator=source_only)
2352
  self.assertEqual(response.status_code,502)
2353
  self.assertIn(b"storage redirect not authorized",response.body)
2354
  self.assertEqual(state.upstream_semaphore._value,1)
 
11
  from collections import OrderedDict
12
  from types import SimpleNamespace
13
  from unittest.mock import AsyncMock, Mock, patch
14
+ from urllib.parse import quote, unquote, urlencode
15
 
16
  IMPORT_ERROR = None
17
  try:
 
2187
  self.assertEqual(len(session.urls), 3)
2188
  self.assertEqual(state.upstream_semaphore._value, 1)
2189
 
2190
+ async def test_reader_reload_and_conditions_resolve_moved_hf_source(self):
2191
+ source = "https://huggingface.co/datasets/VoiceOfML/MLMRL-Hub/resolve/main/" + quote("001643/学点逻辑.pdf")
2192
+ old = "https://us.aws.cdn.hf.co/old-object?Expires=2100000000"
2193
+ new = "https://us.aws.cdn.hf.co/new-object?Expires=2100000000"
2194
+ state = app.app.state
2195
+
2196
+ async def get(url, **options):
2197
+ headers = options["headers"]
2198
+ if url == source:
2199
+ return FakeResponse(302, {"Location": target})
2200
+ if url == old:
2201
+ if any(name in headers for name in ("If-None-Match", "If-Modified-Since")):
2202
+ return FakeResponse(304, {"ETag": '"old"'}, chunks=())
2203
+ if headers.get("If-Range") == '"old"':
2204
+ return FakeResponse(206, {"ETag": '"old"', "Content-Range": "bytes 0-1/3"}, chunks=(b"ol",))
2205
+ return FakeResponse(200, {"ETag": '"old"'}, chunks=(b"old",))
2206
+ self.assertEqual(url, new)
2207
+ return FakeResponse(200, {"ETag": '"new"'}, chunks=(b"new",))
2208
+
2209
+ for headers in (
2210
+ {"Cache-Control": "no-cache"}, {"Cache-Control": "no-store"},
2211
+ {"Cache-Control": "max-age=0"}, {"Pragma": "no-cache"},
2212
+ {"If-None-Match": '"old"'}, {"If-Modified-Since": "Tue, 25 Aug 2026 00:00:00 GMT"},
2213
+ {"Range": "bytes=0-1", "If-Range": '"old"'},
2214
+ ):
2215
+ with self.subTest(headers=headers):
2216
+ upstream_http.upstream_redirect_cache.clear()
2217
+ opener = AsyncMock(side_effect=get)
2218
+ state.http_session = SimpleNamespace(get=opener)
2219
+ target = old
2220
+ for _ in range(2):
2221
+ ordinary = await app.api_reader_content(SimpleNamespace(method="GET", headers={}), source)
2222
+ self.assertEqual([chunk async for chunk in ordinary.body_iterator], [b"old"])
2223
+ cached = upstream_http.upstream_redirect_cache[("GET", source)]
2224
+ target = new
2225
+
2226
+ response = await app.api_reader_content(SimpleNamespace(method="GET", headers=headers), source)
2227
+ body = [chunk async for chunk in response.body_iterator] if hasattr(response, "body_iterator") else []
2228
+ self.assertEqual(response.status_code, 200)
2229
+ self.assertEqual(body, [b"new"])
2230
+ self.assertEqual([call.args[0] for call in opener.await_args_list], [source, old, old, source, new])
2231
+ for call in opener.await_args_list[-2:]:
2232
+ self.assertEqual(call.kwargs["headers"], {"Accept-Encoding": "identity", **headers})
2233
+ self.assertEqual(upstream_http.upstream_redirect_cache[("GET", source)], cached)
2234
+ self.assertEqual(state.upstream_semaphore._value, 1)
2235
+
2236
  async def test_reader_range_age_limits_exact_and_containing_hits(self):
2237
  url = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/document.pdf"
2238
  state = app.app.state
 
2391
  return candidate
2392
  # A fresh attempt fails under the restrictive redirect policy; an exact
2393
  # or contained cached response must never use the looser policy.
2394
+ for headers in ({"Range": "bytes=0-3"}, {"Range": "bytes=1-2"},
2395
+ {"Range": "bytes=0-3", "Cache-Control": "no-cache"}):
2396
  session.responses = [FakeResponse(302, {"Location":storage})]
2397
  response = await app._stream_reader_document(
2398
+ SimpleNamespace(method="GET", headers=headers), url, url_validator=source_only)
2399
  self.assertEqual(response.status_code,502)
2400
  self.assertIn(b"storage redirect not authorized",response.body)
2401
  self.assertEqual(state.upstream_semaphore._value,1)
tests/reader/browser/test_reader_accessibility_browser.py CHANGED
@@ -239,6 +239,71 @@ class ReaderAccessibilityTests(unittest.TestCase):
239
  self.page.wait_for_function("()=>!document.querySelector('#bookmarks-list .panel-item')")
240
  self.assertEqual(self.page.evaluate('document.activeElement.id'), 'bookmarks-all')
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  def test_failure_is_announced_without_stealing_keyboard_focus(self):
243
  self.open_book('unsupported', 'not supported')
244
  self.assertEqual(self.page.get_by_role('alert').count(), 1)
 
239
  self.page.wait_for_function("()=>!document.querySelector('#bookmarks-list .panel-item')")
240
  self.assertEqual(self.page.evaluate('document.activeElement.id'), 'bookmarks-all')
241
 
242
+ def test_pending_bookmark_delete_survives_switch_to_all_bookmarks(self):
243
+ self.open_book('txt', 'A document\n' * 200)
244
+ self.page.evaluate('''async () => {
245
+ const url = new URL(location.href).searchParams.get('url');
246
+ await VoiceOfMLReaderStore.putBookmark({id:'one', url, label:'Remove me', title:'This book'});
247
+ await VoiceOfMLReaderStore.putBookmark({id:'two', url:url+'/other', label:'Keep me', title:'Other book'});
248
+ const store = VoiceOfMLReaderStore;
249
+ window.VoiceOfMLReaderStore = {...store, async removeBookmark(id) {
250
+ await new Promise(resolve => { window.releaseBookmarkDelete = resolve; });
251
+ await store.removeBookmark(id);
252
+ window.bookmarkDeleteCompleted = true;
253
+ }};
254
+ }''')
255
+ self.page.locator('#history').press('Enter')
256
+ self.page.locator('#bookmarks-tab').press('Enter')
257
+ self.page.get_by_role('button', name='删除书签:Remove me', exact=True).click()
258
+ self.page.wait_for_function('() => typeof window.releaseBookmarkDelete === "function"')
259
+ toggle = self.page.locator('#bookmarks-all')
260
+ toggle.click()
261
+ self.page.get_by_role('button', name='Other book · Keep me', exact=True).wait_for()
262
+ self.page.evaluate('window.releaseBookmarkDelete()')
263
+ self.page.wait_for_function('() => window.bookmarkDeleteCompleted === true')
264
+ self.page.locator('#bookmarks-list [data-bookmark-id="one"]').wait_for(state='detached', timeout=2500)
265
+ self.assertTrue(self.page.get_by_role('button', name='Other book · Keep me', exact=True).is_visible())
266
+ self.assertTrue(toggle.evaluate('node => node === document.activeElement'))
267
+
268
+ def check_stale_bookmark_save(self, reject):
269
+ self.open_book('txt', 'A document\n' * 200)
270
+ self.page.evaluate('''reject => {
271
+ const store = VoiceOfMLReaderStore;
272
+ window.VoiceOfMLReaderStore = {...store, async putBookmark(entry) {
273
+ await new Promise(resolve => { window.releaseBookmarkSave = resolve; });
274
+ if (reject) throw new Error('Delayed save failure');
275
+ await store.putBookmark(entry);
276
+ }};
277
+ }''', reject)
278
+ ribbon = self.page.locator('#bookmark-ribbon')
279
+ label = self.page.locator('#bookmark-label')
280
+ ribbon.click()
281
+ label.fill('First bookmark')
282
+ self.page.locator('#bookmark-add').click()
283
+ self.page.wait_for_function('() => typeof window.releaseBookmarkSave === "function"')
284
+ self.page.locator('#bookmark-cancel').click()
285
+ ribbon.click()
286
+ label.fill('Second draft')
287
+ prompt = self.page.locator('#bookmark-prompt').text_content()
288
+ self.page.evaluate('window.releaseBookmarkSave()')
289
+ # Wait for a real write on success. On rejection, let the rejected
290
+ # promise and the original save handler drain before inspecting UI.
291
+ if not reject:
292
+ self.page.wait_for_function('''async () => (await VoiceOfMLReaderStore.listAllBookmarks())
293
+ .some(entry => entry.label === 'First bookmark')''')
294
+ self.page.evaluate('() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))')
295
+ self.assertTrue(self.page.get_by_role('dialog').is_visible())
296
+ self.assertEqual(self.page.locator('#bookmark-prompt').text_content(), prompt)
297
+ self.assertEqual(label.input_value(), 'Second draft')
298
+ self.assertTrue(label.evaluate('node => node === document.activeElement'))
299
+ self.assertTrue(self.page.locator('#bookmark-add').is_enabled())
300
+
301
+ def test_stale_bookmark_save_does_not_close_new_editor(self):
302
+ self.check_stale_bookmark_save(reject=False)
303
+
304
+ def test_stale_bookmark_save_error_does_not_change_new_editor(self):
305
+ self.check_stale_bookmark_save(reject=True)
306
+
307
  def test_failure_is_announced_without_stealing_keyboard_focus(self):
308
  self.open_book('unsupported', 'not supported')
309
  self.assertEqual(self.page.get_by_role('alert').count(), 1)
tests/reader/browser/test_reader_ebook_flow.py CHANGED
@@ -8,6 +8,75 @@ class EbookFlowTests(unittest.TestCase):
8
  setUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__)
9
  setUp = support.PdfFollowupTests.setUp
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def test_successful_toc_jump_owns_open_before_old_chapter_fails(self):
12
  source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/'
13
  + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')
 
8
  setUpClass = classmethod(support.PdfFollowupTests.setUpClass.__func__)
9
  setUp = support.PdfFollowupTests.setUp
10
 
11
+ def open_with_saved_chapter(self, index, manifest_revision, bookmark=False):
12
+ source = 'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/restore.epub'
13
+ endpoint = 'https://voiceofml-search.hf.space/api/reader-bucket-resource?'
14
+ path = 'chapters/ebook/epub/' + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json'
15
+ manifest_url = endpoint + 'path=' + path
16
+ manifest = {'version': 1, 'kind': 'epub-chapters', 'chapters': [
17
+ {'index': i, 'path': f'chapters/chapter-{i:04d}.xhtml'} for i in (1, 2)
18
+ ]}
19
+ self.page.route('**/api/reader-bucket-resource**', lambda route: route.fulfill(json=manifest)
20
+ if 'chapter-manifest.json' in route.request.url else route.fulfill(
21
+ content_type='text/html', body='<h1>Chapter</h1><p style="height:1600px">Text</p>'))
22
+ reader_url = self.origin + support.PREFIX + '/static/reader.html'
23
+ self.page.goto(reader_url)
24
+ entry = {'url': source, 'chapterIndex': index, 'chapterOffset': 180}
25
+ if manifest_revision == 'old':
26
+ entry['chapterManifest'] = endpoint + urlencode({'path': path.replace('1234567890abcdef', '0123456789abcdef')})
27
+ elif manifest_revision == 'current':
28
+ # Same object as the current URL, but with an encoded path query value.
29
+ entry['chapterManifest'] = endpoint + urlencode({'path': path})
30
+ params = dict(url=source, ext='epub-chapters', chapter_manifest=manifest_url)
31
+ if bookmark:
32
+ entry['id'] = 'chapter-regression'
33
+ params.update(bookmark=entry['id'], bookmark_source=source)
34
+ self.page.evaluate('entry => entry.id ? VoiceOfMLReaderStore.putBookmark(entry) : VoiceOfMLReaderStore.put(entry)', entry)
35
+ self.page.goto(reader_url + '?' + urlencode(params))
36
+ self.page.wait_for_function("()=>document.documentElement.dataset.readerPhase==='ready' || "
37
+ "document.querySelector('.reader-error')")
38
+ self.assertEqual(self.page.locator('html').get_attribute('data-reader-phase'), 'ready',
39
+ self.page.locator('.reader-error').all_text_contents())
40
+ self.page.unroute('**/api/reader-bucket-resource**')
41
+ return self.page.evaluate('__ebook.captureChapter()')
42
+
43
+ def test_obsolete_chapter_progress_does_not_block_opening(self):
44
+ self.expose()
45
+ for index, revision in [(9, 'old'), (9, 'current'), (9, None), (2, 'old')]:
46
+ with self.subTest(index=index, revision=revision):
47
+ self.assertEqual(self.open_with_saved_chapter(index, revision)['chapterIndex'], 1)
48
+
49
+ def test_matching_chapter_positions_keep_their_offset(self):
50
+ self.expose()
51
+ for revision, bookmark in [(None, False), ('current', True)]:
52
+ with self.subTest(revision=revision, bookmark=bookmark):
53
+ position = self.open_with_saved_chapter(2, revision, bookmark)
54
+ self.assertEqual(position['chapterIndex'], 2)
55
+ self.assertAlmostEqual(position['chapterOffset'], 180, delta=2)
56
+
57
+ def test_legacy_v5_bookmark_requires_exact_manifest(self):
58
+ self.page.goto(self.origin + support.PREFIX + '/static/reader.html')
59
+ self.assertEqual(self.page.evaluate('''async () => {
60
+ const {createReaderChapterFormat} = await import('./reader/formats/reader-chapter-format.mjs');
61
+ const {createReaderProgress, matchesChapterManifest} = await import('./reader/ui/reader-progress.mjs');
62
+ const manifest = 'https://example.test/book-epub-chapters-v5/chapter-manifest.json';
63
+ const url = 'https://example.test/book.epub', params = new URLSearchParams({bookmark:'v5', bookmark_source:url});
64
+ let loads = 0;
65
+ const context = {sourceUrl:url, chapterManifestUrl:manifest, capability:{mode:'epub-chapters'}, params,
66
+ chapterManifestLoader:Object.assign(async () => { loads++; return null; }, {count:2}),
67
+ isReaderGenerationCurrent:() => true, trustedReaderAssetManifestUrl:() => null};
68
+ const {restoreChapterPosition} = createReaderChapterFormat(context);
69
+ const {loadReaderRestoration} = createReaderProgress(context);
70
+ const rows = [];
71
+ for (const saved of [undefined, '', manifest + '?ignored=1', manifest]) {
72
+ const bookmark = {id:'v5', url, chapterIndex:2, chapterManifest:saved};
73
+ await VoiceOfMLReaderStore.putBookmark(bookmark);
74
+ rows.push([!!(await loadReaderRestoration()), await restoreChapterPosition(bookmark, 0), loads]);
75
+ }
76
+ // Not an admitted shape today; an absent object path is never an identity match.
77
+ return [rows, matchesChapterManifest('old', 'new', url => 'https://example.test/' + url)];
78
+ }'''), [[[False, False, 0], [False, False, 0], [False, False, 0], [True, False, 1]], False])
79
+
80
  def test_successful_toc_jump_owns_open_before_old_chapter_fails(self):
81
  source = ('https://voiceofml-search.hf.space/api/reader-bucket-resource?path=chapters/ebook/epub/'
82
  + 'a' * 64 + '/1234567890abcdef/chapter-manifest.json')
tests/reader/browser/test_reader_refactor.py CHANGED
@@ -2924,6 +2924,33 @@ class ReaderRefactorTest(unittest.TestCase):
2924
  self.assertEqual(result, {"policy": True, "violations": ["img-src"]})
2925
  self.assertNotIn("https://img.remote.test/a.png", remote)
2926
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2927
  def frame_host_reader(self, overlay=False, cross_origin=False):
2928
  # The Reader must decide by its real host whether parent messages are handled.
2929
  reader = self.reader_url(name="framed", path="Test/docs")
 
2924
  self.assertEqual(result, {"policy": True, "violations": ["img-src"]})
2925
  self.assertNotIn("https://img.remote.test/a.png", remote)
2926
 
2927
+ def test_offline_html_relative_same_document_links_jump_without_navigation(self):
2928
+ self.serve('''<!doctype html><body>
2929
+ <a id="relative" href="./report.html#methods">Methods (relative)</a>
2930
+ <a id="fragment" href="#methods">Methods</a>
2931
+ <a id="other-file" href="./appendix.html#methods">Appendix</a>
2932
+ <a id="same-name" href="../report.html#methods">Other report</a>
2933
+ <a id="other-query" href="./report.html?edition=2#methods">Other edition</a>
2934
+ <p style="height: 1800px">Introduction</p>
2935
+ <h2 id="methods">Methods</h2><p style="height: 1200px">Details</p>
2936
+ </body>''', "text/html")
2937
+ self.open(self.reader_url("html", "books/report"))
2938
+ frame = self.page.locator("iframe.html-frame").element_handle().content_frame()
2939
+ history_length = self.page.evaluate("history.length")
2940
+ reader_url = self.page.url
2941
+ for link_id in ("other-file", "same-name", "other-query"):
2942
+ self.assertIsNone(frame.locator(f"#{link_id}").get_attribute("href"), link_id)
2943
+ for link_id in ("relative", "fragment"):
2944
+ with self.subTest(link=link_id):
2945
+ frame.evaluate("scrollTo(0, 0)")
2946
+ link = frame.locator(f"#{link_id}")
2947
+ self.assertEqual(link.get_attribute("href"), "#methods")
2948
+ link.click()
2949
+ frame.wait_for_function("Math.abs(document.querySelector('#methods').getBoundingClientRect().top) < 2")
2950
+ self.assertEqual(frame.url, "about:srcdoc")
2951
+ self.assertEqual(self.page.url, reader_url)
2952
+ self.assertEqual(self.page.evaluate("history.length"), history_length)
2953
+
2954
  def frame_host_reader(self, overlay=False, cross_origin=False):
2955
  # The Reader must decide by its real host whether parent messages are handled.
2956
  reader = self.reader_url(name="framed", path="Test/docs")
tests/reader/pdf-network/test_reader_pdf_backpressure.mjs CHANGED
@@ -1,6 +1,6 @@
1
  import assert from 'node:assert/strict';
2
  import {mock} from 'node:test';
3
- import {createPdfFetchPolicy} from '../../../static/reader/pdf/reader-pdf-network.mjs';
4
 
5
  // Local transport fixture only: no upstream connection is made.
6
  globalThis.location = {href:'https://reader.test/'};
@@ -57,6 +57,58 @@ async function checkAdmissionDeadline(options,init,deadline) {
57
  }
58
 
59
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  // A genuine 429 triggers one bounded retry after the shared pause, then a
61
  // correctly versioned body is delivered without reopening the document.
62
  {
 
1
  import assert from 'node:assert/strict';
2
  import {mock} from 'node:test';
3
+ import {createPdfFetchPolicy, preparePdfInitialRange} from '../../../static/reader/pdf/reader-pdf-network.mjs';
4
 
5
  // Local transport fixture only: no upstream connection is made.
6
  globalThis.location = {href:'https://reader.test/'};
 
57
  }
58
 
59
  try {
60
+ // Native PDF staging awaits the bootstrap before the outer Reader timer
61
+ // exists. When the first Range gets a 200, the policy hands off the body.
62
+ for (const scenario of ['stall','close','complete']) await withClock(async advance=>{
63
+ const owner=new AbortController(), requests=[];
64
+ const closeReason=new DOMException('caller closed','AbortError'), bodyDeadline=120000;
65
+ let body, upstream, waitingForMore=false, outcome;
66
+ globalThis.fetch=async (_input,init)=>{
67
+ requests.push(new Headers(init.headers).get('Range'));
68
+ upstream=init.signal;
69
+ return new Response(new ReadableStream({
70
+ start(controller){
71
+ body=controller;
72
+ controller.enqueue(bytes.slice(0,2));
73
+ upstream.addEventListener('abort',()=>controller.error(upstream.reason),{once:true});
74
+ },
75
+ pull(){waitingForMore=true;}
76
+ },{highWaterMark:0}),{status:200});
77
+ };
78
+ const policy=createPdfFetchPolicy(opts);policy.add(['/a.pdf']);
79
+ try {
80
+ const url=new URL('/a.pdf',globalThis.location.href).href;
81
+ void preparePdfInitialRange({url,rangeChunkSize:2},{signal:owner.signal,limit:64,rangeCache:null,
82
+ readBytes:async response=>new Uint8Array(await response.arrayBuffer())})
83
+ .then(first=>{outcome={first};},error=>{outcome={error};});
84
+ await advance(0);
85
+ assert.deepEqual(requests,['bytes=0-1']);
86
+ assert.equal(waitingForMore,true,'the body has already delivered bytes and is waiting for more');
87
+ await advance(scenario==='close' ? 1 : bodyDeadline-1);
88
+ assert.equal(outcome,undefined,'the bootstrap must not settle early or publish a prefix');
89
+ assert.equal(upstream.aborted,false);
90
+ if (scenario==='stall') {
91
+ await advance(1);
92
+ assert.equal(outcome?.error?.name,'TimeoutError','the 200 body must time out before the outer Reader timer starts');
93
+ assert.equal(upstream.aborted,true);
94
+ assert.equal(upstream.reason,outcome.error);
95
+ assert.equal(owner.signal.aborted,false);
96
+ } else if (scenario==='close') {
97
+ owner.abort(closeReason);
98
+ await advance(0);
99
+ assert.equal(outcome?.error,closeReason);
100
+ assert.equal(upstream.reason,closeReason);
101
+ } else {
102
+ body.enqueue(bytes.slice(2));body.close();
103
+ await advance(0);
104
+ assert.equal(outcome?.first?.complete,true);
105
+ assert.deepEqual(outcome.first.bytes,bytes);
106
+ await advance(1);
107
+ assert.equal(upstream.aborted,false,'completion clears the body deadline');
108
+ }
109
+ assert.deepEqual(requests,['bytes=0-1'],'the bootstrap needs no second request');
110
+ } finally {owner.abort(closeReason);policy.dispose();}
111
+ });
112
  // A genuine 429 triggers one bounded retry after the shared pause, then a
113
  // correctly versioned body is delivered without reopening the document.
114
  {
tests/search/browser/test_search_session_browser.py CHANGED
@@ -1,5 +1,11 @@
1
- """Exercise the actual IndexedDB session adapter in Chromium."""
 
 
 
2
  import unittest
 
 
 
3
 
4
  from tests.reader.browser import test_reader_pdf_followup as support
5
 
@@ -219,5 +225,80 @@ class SearchSessionBrowserTests(unittest.TestCase):
219
  self.assertNotIn("voiceofml-search-state", result["databases"])
220
 
221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  if __name__ == "__main__":
223
  unittest.main()
 
1
+ """Exercise IndexedDB sessions and filter result snapshots in Chromium."""
2
+ import mimetypes
3
+ import os
4
+ from pathlib import Path
5
  import unittest
6
+ from urllib.parse import urlsplit
7
+
8
+ from playwright.sync_api import sync_playwright
9
 
10
  from tests.reader.browser import test_reader_pdf_followup as support
11
 
 
225
  self.assertNotIn("voiceofml-search-state", result["databases"])
226
 
227
 
228
+ class FilterSnapshotBrowserTests(unittest.TestCase):
229
+ def test_mirror_toggle_does_not_restore_pdf_for_txt_filter(self):
230
+ root = Path(__file__).resolve().parents[3]
231
+ origin = 'https://search-fixture.test'
232
+ prefix = ''
233
+ entry = '/?q=ownership'
234
+ requests = []
235
+ inventory = [{'name': ext, 'count': 1} for ext in ('pdf', 'txt')]
236
+ rows = [dict(Repo='VoiceOfML/Test', File='ownership', Extension=ext, Folder=[], Size=1)
237
+ for ext in ('pdf', 'txt')]
238
+
239
+ def fulfill(route):
240
+ url = urlsplit(route.request.url)
241
+ path = url.path
242
+ if path == '/api/search' and route.request.method == 'POST':
243
+ body = route.request.post_data_json
244
+ extensions = body.get('extensions', [])
245
+ requests.append(extensions)
246
+ results = [row for row in rows if not extensions or row['Extension'] in extensions]
247
+ route.fulfill(json=dict(results=results, total=len(results), page=1, page_size=body['page_size']),
248
+ headers={'Access-Control-Allow-Origin': '*'})
249
+ elif path == '/api/search' and route.request.method == 'OPTIONS':
250
+ route.fulfill(status=204, headers={'Access-Control-Allow-Origin': '*',
251
+ 'Access-Control-Allow-Headers': 'content-type'})
252
+ elif path.startswith('/api/'):
253
+ data = {'/api/extensions': inventory, '/api/repos': [],
254
+ '/api/bootstrap': {'repos': [], 'extensions': inventory}}
255
+ route.fulfill(json=data.get(path, {}), headers={'Access-Control-Allow-Origin': '*'})
256
+ elif url.hostname == 'search-fixture.test' and path == prefix + '/':
257
+ route.fulfill(path=root / 'static/index.html', content_type='text/html')
258
+ elif url.hostname == 'search-fixture.test' and path.startswith(prefix + '/static/'):
259
+ asset = root / path.removeprefix(prefix).lstrip('/')
260
+ if asset.is_file():
261
+ route.fulfill(path=asset, content_type=mimetypes.guess_type(asset)[0])
262
+ else:
263
+ route.fulfill(status=404)
264
+ else:
265
+ route.abort()
266
+
267
+ with sync_playwright() as playwright:
268
+ browser = playwright.chromium.launch(executable_path=os.getenv('CHROMIUM_PATH'),
269
+ args=['--disable-background-networking', '--host-resolver-rules=MAP * ~NOTFOUND'])
270
+ context = browser.new_context(service_workers='block', viewport={'width': 1280, 'height': 800})
271
+ context.route('**/*', fulfill)
272
+ page = context.new_page()
273
+ errors = []
274
+ page.on('pageerror', lambda error: errors.append(str(error)))
275
+ page.add_init_script("Object.defineProperty(navigator, 'onLine', {get: () => true});")
276
+ page.goto(origin + entry, wait_until='domcontentloaded')
277
+ txt = page.locator('#filter-ext-list input[value="txt"]')
278
+ txt.wait_for(state='attached', timeout=5000)
279
+ pdf_row = page.locator('.result-item[aria-label="ownership.pdf"]')
280
+ pdf_copy = pdf_row.locator('[data-action="copy"]')
281
+ self.assertIn('hf-mirror.com', pdf_copy.get_attribute('data-link', timeout=5000))
282
+
283
+ page.clock.install()
284
+ page.clock.pause_at(page.evaluate('Date.now() + 100'))
285
+ txt.evaluate('input => input.click()')
286
+ self.assertTrue(page.evaluate('filterSearchTimer !== null'))
287
+ page.locator('#mirror-links-toggle').evaluate('input => input.click()')
288
+ self.assertEqual(urlsplit(pdf_copy.get_attribute('data-link')).hostname, 'huggingface.co')
289
+ self.assertEqual(requests, [[]])
290
+
291
+ page.clock.run_for(200)
292
+ page.clock.resume()
293
+ page.wait_for_function('filterSearchTimer === null && !STATE.isLoading', timeout=5000)
294
+ self.assertEqual(
295
+ (page.locator('.result-item').evaluate_all('rows => rows.map(row => row.ariaLabel)'), requests),
296
+ (['ownership.txt'], [[], ['txt']]),
297
+ )
298
+ self.assertEqual(errors, [])
299
+ context.close()
300
+ browser.close()
301
+
302
+
303
  if __name__ == "__main__":
304
  unittest.main()