vomebook commited on
Commit ·
d101ec0
1
Parent(s): c77f9c7
Fix search and Reader history ownership and recovery
Browse filesFiles changed (17)
- scripts/search/check_reader_navigation_baseline.mjs+7-3
- static/app.js+221-64
- static/reader/core/reader-bindings.mjs+41-4
- static/search/reader-navigation.js+49-5
- static/search/search-session.js+140-54
- tests/gates/ci-test-inventory.json+20
- tests/gates/test_static_checks.py+14-2
- tests/reader/browser/test_reader_host_history_races.pyAdded+378
- tests/reader/browser/test_reader_navigation_host.py+96-8
- tests/reader/browser/test_reader_reload_search_document.pyAdded+600
- tests/reader/core/test_reader_regression.js+1-1
- tests/search/browser/test_paging_recovery.py+8-2
- tests/search/browser/test_session_transaction_browser.pyAdded+321
- tests/search/reader-navigation/test_reader_navigation_baseline.mjs+173-7
- tests/search/reader-navigation/test_search_history_races.mjsAdded+201
- tests/search/session/test_search_session_contract.jsAdded+378
- typings/reader-globals.d.ts+1
1234567820 unmodified lines29303132333435import {spawnSync} from 'node:child_process';import {hasPassingTapContracts} from '../check_tap_contracts.mjs';// Node 26/V8 scope: this single file under the synthetic URL/session contracts.// This is a baseline, not a claim that iframe/speech behavior is covered.const minimum = [31.96, 81.82, 27.27];const result = spawnSync(process.execPath, ['--test', '--test-reporter=tap', '--experimental-test-coverage',20 unmodified lines'remember still updates history when storage fails and saved rejects malformed JSON','clear removes only the matching session and selected return token','messages are rejected when no reader iframe is active','pathname and search parameter prototype overrides retain their original effects'].map(name => ({name}));if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => value < minimum[index]) ||!hasPassingTapContracts(text, required)) {1234567820 unmodified lines2930313233343536373839import {spawnSync} from 'node:child_process';import {hasPassingTapContracts} from '../check_tap_contracts.mjs';// Node 26/V8 scope: this file under synthetic URL/session and shell contracts.// Native browser traversal, rendering and speech still require browser tests.const minimum = [31.96, 81.82, 27.27];const result = spawnSync(process.execPath, ['--test', '--test-reporter=tap', '--experimental-test-coverage',20 unmodified lines'remember still updates history when storage fails and saved rejects malformed JSON','clear removes only the matching session and selected return token','messages are rejected when no reader iframe is active','pathname and search parameter prototype overrides retain their original effects','replacement revision preserves a Reader opened synchronously during disposal','ordinary replacement carries handoff and focus while releasing background ownership','close recovery validates both search routes without changing history or private handoff','recovery survives late shell load and records handoff only on native link activation'].map(name => ({name}));if (result.status !== 0 || rows.length !== 1 || rows[0].some((value, index) => value < minimum[index]) ||!hasPassingTapContracts(text, required)) {
117 unmodified lines118119120121122123254 unmodified lines378379380381382383384436 unmodified lines8218228238248258268278288298308318328338342 unmodified lines837838839840841842843844845846847595 unmodified lines144314441445144614471448144914501451145214531454157 unmodified lines1612161316141615161616171618177 unmodified lines179617971798179918001801180218031804180532 unmodified lines1838183918401841184218431844570 unmodified lines24152416241724182419242016 unmodified lines2437243824392440244124422443244424451 unmodified line2447244824492450245124522453245424552456245724582459246013 unmodified lines247424752476247724782479248024812482248316 unmodified lines25002501250225032504250511 unmodified lines251725182519252025212522252325 unmodified lines25492550255125522553255425552556255725582559321 unmodified lines28812882288328842885288684 unmodified lines2971297229732974297529762977297829792980298129822983298429858 unmodified lines299429952996299729982999300030014 unmodified lines30063007300830093010301130123013301430153016301753 unmodified lines30713072307330743075307630777 unmodified lines3085308630873088308930903091309230933094312 unmodified lines3407340834093410341134123413341434153416631 unmodified lines404840494050405140524053405440554056405732 unmodified lines40904091409240934094409540964097409840994100410127 unmodified lines4129413041314132413341344135413641374138132 unmodified lines42714272427342744275427642774278427942802 unmodified lines4283428442854286428742884289429042911396 unmodified lines56885689569056915692569311 unmodified lines57055706570757085709571057115712571357145715571657175718571957205721153 unmodified lines5875587658775878587958805881588219 unmodified lines5902590359045905590659075908117 unmodified lineslet scrollLoadTimer = null;let scrollRecoveryTimer = null;let searchComposing = false;let keepalivePending = null;let lastKeepaliveAt = 0;const KEEPALIVE_INTERVAL_MS = 45 * 1000;254 unmodified linessaveSearchViewSnapshot();const key = getSearchViewKey();if (fromStart) saveSearchPosition();cancelPositionRestore();prepareReturnPosition(key, !fromStart);if (!restorePosition) return false;setReturnPositionTarget();436 unmodified linesfunction cancelPositionRestore() {cancelSnapshotClone();positionEntryId++;if (resultWindow) resultWindow.controller.abort();resultWindow = null;updateResultWindowStatus();if (!positionRestore) return;positionRestore.controller.abort();positionRestore = null;STATE.isLoading = false;showPositionRestoreStatus("");}function tryRestoreSearchPosition(key, options = {}) {2 unmodified linesif (!validSearchPosition(position)) return false;cancelPendingSearchControls();if (!options.position && positionRestore?.key === key && !positionRestore.failed) return true;cancelPositionRestore();setReturnPositionTarget();searchAbortController?.abort();cancelSearchPrefetch();searchRequestId++;const controller = new AbortController();const task = { key, controller, position: {...position}, lookup: previous?.lookup, ready: previous?.ready || new Map(), page: 0, results: [] };positionRestore = task;595 unmodified linesfunction restoreSearchViewSnapshot(key, restoreScroll = true, preserveRestore = false) {const snapshot = searchViewSnapshots.get(key);if (!snapshot || snapshot.version !== SEARCH_VIEW_SNAPSHOT_VERSION || snapshot.loadedPage < 1) return restoreScroll && tryRestoreSearchPosition(key);if (!preserveRestore) cancelPositionRestore();cancelPendingSearchControls();if (searchAbortController) searchAbortController.abort();cancelSearchPrefetch();searchAbortController = new AbortController();searchRequestId++;const materialized = snapshot.window?.count ?? snapshot.results.length;STATE.results = materialized > 2000 && !preserveRestore? prepareSnapshotClone(snapshot, key, restoreScroll) : snapshot.results.map(cloneSearchResult);157 unmodified lines}if (params.min_size != null) body.min_size = params.min_size;if (params.max_size != null) body.max_size = params.max_size;body.sort = params.sort || DOM.sortSelect.value;if (params.search_folders === false) body.search_folders = false;if (params.exact) body.exact = true;return body;177 unmodified linesif (!data || !Array.isArray(data.results) || !canUseInitialSearchPayload()) return false;if (STATE.mode === "repo" && data.repo !== STATE.repoFull) return false;if (STATE.mode === "global" && data.mode !== "global") return false;if (searchAbortController) searchAbortController.abort();cancelSearchPrefetch();searchAbortController = new AbortController();searchRequestId++;STATE.total = data.total || 0;STATE.page = 1;STATE.results = data.results.slice();32 unmodified linesasync function searchWithInitialFallback() {saveSearchViewSnapshot();cancelPositionRestore();const key = getSearchViewKey(), entry = positionEntryId;prepareReturnPosition(key);if (searchViewSnapshots.has(key)) {570 unmodified lines]);let readerOverlay = null;let readerUiState = "base";let readerClosing = false;const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", {16 unmodified linesindex = findVirtualIndex(top);offset = top - getVirtualOffset(index);}return { route: location.href, viewKey: getSearchViewKey(), top, index, offset };}function restoreReaderReturnScroll(windowRendered = false) {const saved = readerReturnScrollState;if (!saved) return;if (saved.route && saved.route !== location.href) { readerReturnScrollState = null; return; }1 unmodified lineconst generation = ++readerReturnRestoreGeneration;let attempts = 0;const restore = () => {if (generation !== readerReturnRestoreGeneration) return;if (!DOM.resultsContainer || !STATE.results.length) {if (++attempts < 20) requestAnimationFrame(restore);return;}ensureHeightTree();const index = Math.min(saved.index, STATE.results.length - 1);const target = Math.max(0, getVirtualOffset(index) + saved.offset);const max = Math.max(0, getVirtualTotalHeight() - DOM.resultsContainer.clientHeight);readerReturnRestoreActive = true;setResultScrollTop(Math.min(target, max));13 unmodified lines}function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {if (!readerOverlay) return false;readerClosing = false;readerUiState = "base";const returnFocus = readerNavigation.unmount();readerOverlay = null;if (restoreScroll) {const saved = readerReturnScrollState;const snapshot = readerReturnSnapshot;16 unmodified lines}function openReaderOverlay(url, addHistory = true) {if (addHistory && !readerReturnScrollState) {readerReturnScrollState = captureReaderReturnScroll();readerReturnSnapshot = saveSearchViewSnapshot(readerReturnScrollState?.viewKey || getSearchViewKey());11 unmodified lines}try {const url = readerNavigation.parse(state.readerUrl);closeReaderOverlay(false, false);openReaderOverlay(url, false);} catch (_) {}}25 unmodified lines}const overlay = readerOverlay;history.back();// A traversal that never fires popstate must not leave the Reader stuck.setTimeout(() => {if (!readerClosing || readerOverlay !== overlay) return;closeReaderOverlay();history.replaceState(null, "", returnUrl);}, 1000);return;}321 unmodified linesreturn pending;}function buildSearchURLParams() {const params = new URLSearchParams();if (STATE.query) params.set("q", STATE.query);84 unmodified lineshistory.pushState(null, "", url);this.apply();},apply() {const route = this.parse();const prevMode = STATE.mode;const prevRepo = STATE.repo;const previousPath = STATE.browserPath;const previousSearchKey = routeInitialized && prevMode === "repo" ? getSearchViewKey() : null;const previousPage = STATE.page;saveSearchViewSnapshot();cancelPositionRestore();STATE.mode = route.mode;STATE.repo = route.repo;STATE.repoFull = route.repo ? `VoiceOfML/${route.repo}` : null;8 unmodified linesSTATE.folderTreeCollapsed = {};STATE.browserPath = "";API._extCache = null;syncURLToState();}this.updateUI();updateRandomTxtVisibility();if (prevMode !== STATE.mode || prevRepo !== STATE.repo) {4 unmodified linessyncStateToURL(true);}} else {syncURLToState();const routeId = ++routeRenderId;if (previousSearchKey && STATE.mode === "repo" && previousPath !== STATE.browserPath &&previousSearchKey === getSearchViewKey()) {STATE.page = previousPage;renderBrowser(STATE.browserPath || "", routeId);retainFilterRenderingForRoute(routeId);routeInitialized = true;persistSearchSession();53 unmodified linesconst path = STATE.mode === "global" ? "/" : `/${STATE.repo}`;const url = qs ? `${path}?${qs}` : path;if (replace) {history.replaceState(null, "", url);} else {history.pushState(null, "", url);}7 unmodified linesSTATE.query = Array.from(STATE.query).slice(0, 256).join("");showToast("搜索内容已限制为 256 个字符");}setSearchInputValue(STATE.query);STATE.filterRepos = params.getAll("repo").map(r => `VoiceOfML/${r}`);STATE.browserPath = params.get("path") || "";const sort = params.get("sort") || "relevance";DOM.sortSelect.value = sort;const extStr = params.get("ext");if (extStr !== null) {312 unmodified linesreturn result;}function debouncedSearch() {if (searchComposing) return;clearTimeout(searchTimer);searchTimer = setTimeout(() => {submitSearchQuery(DOM.searchInput.value.trim(), { record: true, refreshHistory: true });}, 100);}631 unmodified lines}function prepareFilterChange(clearResults) {// Merge only a pending edit; otherwise preserve exact URL-restored byte values.applyPendingSizeFilters();cancelPendingSearchControls();saveSearchViewSnapshot();STATE.page = 1;if (clearResults) STATE.results = [];}32 unmodified linesfunction scheduleFilterSearch(clearResults = false) {prepareFilterChange(clearResults);cancelPositionRestore();resetPagingRecovery();if (searchAbortController) searchAbortController.abort();cancelSearchPrefetch();searchRequestId++;searchId++;STATE.isLoading = true;setSearchVisualLoading(true);syncStateToURL(true);27 unmodified lines}function cancelSearchPrefetch() {cancelPendingSearchCacheWrites();searchPrefetchAbortController?.cacheWaits?.forEach(wait => wait.controller.abort());searchPrefetchAbortController?.abort();searchPrefetchAbortController = null;}function prefetchSearchPages(base, template) {132 unmodified linesasync function doSearch(append = false, fromStart = false, restorePosition = false) {if (append && resultWindow) { loadResultWindowPage(STATE._loadedPage + 1); return; }if (!append && !fromStart) backToTopPending = false;if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;const recoveringFirstPage = append && !STATE._loadedPage;if (recoveringFirstPage) append = false;clearTimeout(filterSearchTimer);filterSearchTimer = null;if (!append) {2 unmodified linesselectedIndices = {};lastSelectedIndex = -1;if (DOM.multiSelectToggle && DOM.multiSelectToggle.checked) updateSelectionUI();if (searchAbortController) searchAbortController.abort();cancelSearchPrefetch();searchAbortController = new AbortController();STATE._pageCache = {};STATE._loadedPage = 0;STATE._pagingAppendScrollTop = null;1396 unmodified linesif (document.visibilityState === "hidden") flushSidebarScroll();});syncSearchInputState();// Session and position databases are independent; start both without// serializing their I/O. Route handling still waits for both to settle.const positionsReady = initSearchPositions();11 unmodified lineselse if (savedMobile === "desktop") STATE.isMobile = false;else STATE.isMobile = autoDetectMobile();applyMobileMode();DOM.searchInput.addEventListener("input", () => {syncSearchInputState();debouncedSearch();});DOM.searchInput.addEventListener("compositionstart", () => {searchComposing = true;});DOM.searchInput.addEventListener("compositionend", () => {searchComposing = false;debouncedSearch();});setupSearchHistory();DOM.historyToggle.addEventListener("change", () => {STATE.recordHistory = DOM.historyToggle.checked;153 unmodified linesrestoreReaderOverlay(event.state);return;}if (closeReaderOverlay()) return;ROUTER.apply();});window.addEventListener("resize", () => {if (!readSearchPreference("mobileMode")) {19 unmodified lineswindow.addEventListener("pageshow", resumeResultRecovery);window.addEventListener("online", resumeResultRecovery);window.setInterval(() => warmConnection(), KEEPALIVE_INTERVAL_MS);ROUTER.apply();// Keep the first search paint independent of the multi-megabyte Reader sidecar.// API results already carry Reader fields; the sidecar is only enrichment for// local snapshots and directory browsing. Load it on the first real117 unmodified lines118119120121122123124125126127128129130131254 unmodified lines386387388389390391392393394436 unmodified lines8318328338348358368378388398408418428438448458468472 unmodified lines850851852853854855856857858859860595 unmodified lines14561457145814591460146114621463146414651466157 unmodified lines1624162516261627162816291630177 unmodified lines180818091810181118121813181432 unmodified lines184718481849185018511852185318541855570 unmodified lines242624272428242924302431243216 unmodified lines2449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625171 unmodified line2519252025212522252325242525252625272528252925302531253213 unmodified lines25462547254825492550255125522553255425552556255716 unmodified lines257425752576257725782579258011 unmodified lines25922593259425952596259725982599260025 unmodified lines2626262726282629263026312632263326342635321 unmodified lines2957295829592960296129622963296429652966296784 unmodified lines305230533054305530563057305830593060306130623063306430658 unmodified lines3074307530763077307830793080308130823083308430853086308730883089309030914 unmodified lines309630973098309931003101310231033104310553 unmodified lines31593160316131623163316431657 unmodified lines3173317431753176317731783179318031813182312 unmodified lines349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566631 unmodified lines41984199420042014202420342044205420642074208420932 unmodified lines4242424342444245424642474248424942504251425227 unmodified lines428042814282428342844285428642874288428942904291429242934294429542964297429842994300132 unmodified lines44334434443544364437443844394440444144424443444444452 unmodified lines4448444944504451445244531396 unmodified lines585058515852585358545855585611 unmodified lines586858695870587158725873153 unmodified lines602760286029603060316032603360346035603619 unmodified lines6056605760586059606060616062606360646065117 unmodified lineslet scrollLoadTimer = null;let scrollRecoveryTimer = null;let searchComposing = false;let searchInputGeneration = 0;let searchCompositionGeneration = 0;/** @type {string | null} */let searchCompositionViewKey = null;let searchInputReady = false;let initialSearchDraft = false;/** @type {{href: string, key: string | undefined, cancelled: boolean} | null} */let initialSearchDraftOwner = null;let keepalivePending = null;let lastKeepaliveAt = 0;const KEEPALIVE_INTERVAL_MS = 45 * 1000;254 unmodified linessaveSearchViewSnapshot();const key = getSearchViewKey();if (fromStart) saveSearchPosition();const owner = searchId;cancelPositionRestore();if (owner !== searchId) return true;prepareReturnPosition(key, !fromStart);if (!restorePosition) return false;setReturnPositionTarget();436 unmodified linesfunction cancelPositionRestore() {cancelSnapshotClone();positionEntryId++;const previousWindow = resultWindow;const previousRestore = positionRestore;resultWindow = null;positionRestore = null;updateResultWindowStatus();if (previousRestore) {STATE.isLoading = false;showPositionRestoreStatus("");}previousWindow?.controller.abort();previousRestore?.controller.abort();}function tryRestoreSearchPosition(key, options = {}) {2 unmodified linesif (!validSearchPosition(position)) return false;cancelPendingSearchControls();if (!options.position && positionRestore?.key === key && !positionRestore.failed) return true;if (!cancelActiveSearch()) return false;const owner = searchId;cancelPositionRestore();if (owner !== searchId) return false;setReturnPositionTarget();const controller = new AbortController();const task = { key, controller, position: {...position}, lookup: previous?.lookup, ready: previous?.ready || new Map(), page: 0, results: [] };positionRestore = task;595 unmodified linesfunction restoreSearchViewSnapshot(key, restoreScroll = true, preserveRestore = false) {const snapshot = searchViewSnapshots.get(key);if (!snapshot || snapshot.version !== SEARCH_VIEW_SNAPSHOT_VERSION || snapshot.loadedPage < 1) return restoreScroll && tryRestoreSearchPosition(key);if (!cancelActiveSearch()) return false;const owner = searchId;if (!preserveRestore) cancelPositionRestore();if (owner !== searchId) return false;cancelPendingSearchControls();const materialized = snapshot.window?.count ?? snapshot.results.length;STATE.results = materialized > 2000 && !preserveRestore? prepareSnapshotClone(snapshot, key, restoreScroll) : snapshot.results.map(cloneSearchResult);157 unmodified lines}if (params.min_size != null) body.min_size = params.min_size;if (params.max_size != null) body.max_size = params.max_size;body.sort = normalizeSearchSort(params.sort || DOM.sortSelect.value);if (params.search_folders === false) body.search_folders = false;if (params.exact) body.exact = true;return body;177 unmodified linesif (!data || !Array.isArray(data.results) || !canUseInitialSearchPayload()) return false;if (STATE.mode === "repo" && data.repo !== STATE.repoFull) return false;if (STATE.mode === "global" && data.mode !== "global") return false;if (!cancelActiveSearch()) return false;STATE.total = data.total || 0;STATE.page = 1;STATE.results = data.results.slice();32 unmodified linesasync function searchWithInitialFallback() {saveSearchViewSnapshot();const owner = searchId;cancelPositionRestore();if (owner !== searchId) return false;const key = getSearchViewKey(), entry = positionEntryId;prepareReturnPosition(key);if (searchViewSnapshots.has(key)) {570 unmodified lines]);let readerOverlay = null;let readerOverlayRevision = 0;let readerUiState = "base";let readerClosing = false;const readerNavigation = VoiceOfMLReaderNavigation.createNavigation("/static/reader.html", {16 unmodified linesindex = findVirtualIndex(top);offset = top - getVirtualOffset(index);}const active = document.activeElement;const focus = active instanceof HTMLElement && active.id ? { id: active.id,start: active instanceof HTMLInputElement ? active.selectionStart : null,end: active instanceof HTMLInputElement ? active.selectionEnd : null,direction: active instanceof HTMLInputElement ? active.selectionDirection : null } : null;return { route: location.href, viewKey: getSearchViewKey(), top, index, offset, focus };}function readerSearchHandoffReady(saved) {// A preview has already restored usable rows and geometry while validation// may still be fetching adjacent pages. Keep that validation running.if (STATE.isLoading || !STATE._loadedPage || !STATE.results.length) return false;if (positionRestore && (!positionRestore.preview || positionRestore.key !== saved.viewKey)) return false;const index = Math.min(saved.index, Math.max(0, STATE.total - 1));return !!STATE.results[index];}function restoreReaderSearchHandoff() {let saved;try {const handoff = JSON.parse(sessionStorage.getItem("reader-navigation-restore") || "null");sessionStorage.removeItem("reader-navigation-restore");if (!handoff || handoff.returnUrl !== location.href) return;const current = /** @type {{readerUrl?: string; returnScroll?: ReturnType<typeof captureReaderReturnScroll>} | null} */ (readerNavigation.saved());if (!current || current.readerUrl !== handoff.readerUrl) return;const url = readerNavigation.parse(handoff.readerUrl);const token = url.searchParams.get("nav");if (!token || sessionStorage.getItem("reader-return:" + token) !== location.href) return;saved = current.returnScroll;if (!saved || saved.route !== location.href || saved.viewKey !== getSearchViewKey() ||!Number.isInteger(saved.index) || saved.index < 0 || !Number.isFinite(saved.offset) || !Number.isFinite(saved.top)) return;} catch (_) { return; }const route = location.href;let cancelled = false;const cancel = () => { cancelled = true; cleanup(); };const cleanup = () => {for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])document.removeEventListener(type, cancel, true);};for (const type of ["pointerdown", "keydown", "focusin", "input", "compositionstart", "wheel", "touchstart"])document.addEventListener(type, cancel, true);const routeRevision = routeRenderId;const deadline = Date.now() + 30000;const restore = () => {if (cancelled || routeRevision !== routeRenderId || location.href !== route || saved.viewKey !== getSearchViewKey() || Date.now() > deadline) {cleanup(); return;}if (!readerSearchHandoffReady(saved)) { requestAnimationFrame(restore); return; }cleanup();readerReturnScrollState = saved;restoreReaderReturnScroll(false, true);const focus = saved.focus;const element = focus && document.getElementById(focus.id);if (!element || (document.activeElement !== document.body && document.activeElement !== element)) return;element.focus({ preventScroll: true });if (element instanceof HTMLInputElement && Number.isInteger(focus.start) && Number.isInteger(focus.end) &&["forward", "backward", "none"].includes(focus.direction)) {try { element.setSelectionRange(focus.start, focus.end, focus.direction); } catch (_) {}}};requestAnimationFrame(restore);}function restoreReaderReturnScroll(windowRendered = false, restoreTop = false) {const saved = readerReturnScrollState;if (!saved) return;if (saved.route && saved.route !== location.href) { readerReturnScrollState = null; return; }1 unmodified lineconst generation = ++readerReturnRestoreGeneration;let attempts = 0;const restore = () => {if (generation !== readerReturnRestoreGeneration || saved.viewKey !== getSearchViewKey() || saved.route !== location.href) return;if (!DOM.resultsContainer || !STATE.results.length) {if (++attempts < 20) requestAnimationFrame(restore);return;}ensureHeightTree();const index = Math.min(saved.index, STATE.results.length - 1);const target = Math.max(0, restoreTop ? saved.top : getVirtualOffset(index) + saved.offset);const max = Math.max(0, getVirtualTotalHeight() - DOM.resultsContainer.clientHeight);readerReturnRestoreActive = true;setResultScrollTop(Math.min(target, max));13 unmodified lines}function closeReaderOverlay(restoreFocus = true, restoreScroll = true) {if (!readerOverlay) return false;readerOverlayRevision++;readerClosing = false;readerUiState = "base";readerOverlay = null;const returnFocus = readerNavigation.unmount();if (readerOverlay) return true;if (restoreScroll) {const saved = readerReturnScrollState;const snapshot = readerReturnSnapshot;16 unmodified lines}function openReaderOverlay(url, addHistory = true) {readerOverlayRevision++;if (addHistory && !readerReturnScrollState) {readerReturnScrollState = captureReaderReturnScroll();readerReturnSnapshot = saveSearchViewSnapshot(readerReturnScrollState?.viewKey || getSearchViewKey());11 unmodified lines}try {const url = readerNavigation.parse(state.readerUrl);const revision = readerOverlayRevision + (readerOverlay ? 1 : 0);closeReaderOverlay(false, false);if (readerOverlayRevision !== revision) return;openReaderOverlay(url, false);} catch (_) {}}25 unmodified lines}const overlay = readerOverlay;history.back();// Back may still arrive: keep its Reader entry intact for Forward.setTimeout(() => {if (!readerClosing || readerOverlay !== overlay) return;readerNavigation.showCloseRecovery(returnUrl);}, 1000);return;}321 unmodified linesreturn pending;}/** @param {unknown} value */function normalizeSearchSort(value) {return value === "name" || value === "size" ? value : "relevance";}function buildSearchURLParams() {const params = new URLSearchParams();if (STATE.query) params.set("q", STATE.query);84 unmodified lineshistory.pushState(null, "", url);this.apply();},apply(preserveSameView = false) {const route = this.parse();const prevMode = STATE.mode;const prevRepo = STATE.repo;const previousPath = STATE.browserPath;const previousSearchKey = routeInitialized ? getSearchViewKey() : null;const previousPage = STATE.page;saveSearchViewSnapshot();STATE.mode = route.mode;STATE.repo = route.repo;STATE.repoFull = route.repo ? `VoiceOfML/${route.repo}` : null;8 unmodified linesSTATE.folderTreeCollapsed = {};STATE.browserPath = "";API._extCache = null;}syncURLToState();const sameSearchView = previousSearchKey === getSearchViewKey();if (!sameSearchView) {if (routeInitialized) searchInputGeneration++;cancelPendingSearchControls();readerReturnRestoreGeneration++;if (!cancelActiveSearch()) return;}const owner = searchId;if (!sameSearchView || (!preserveSameView && previousPath === STATE.browserPath)) cancelPositionRestore();if (owner !== searchId) return;this.updateUI();updateRandomTxtVisibility();if (prevMode !== STATE.mode || prevRepo !== STATE.repo) {4 unmodified linessyncStateToURL(true);}} else {const routeId = ++routeRenderId;if (sameSearchView && (preserveSameView || (STATE.mode === "repo" && previousPath !== STATE.browserPath))) {STATE.page = previousPage;if (STATE.mode === "repo" && previousPath !== STATE.browserPath) renderBrowser(STATE.browserPath || "", routeId);retainFilterRenderingForRoute(routeId);routeInitialized = true;persistSearchSession();53 unmodified linesconst path = STATE.mode === "global" ? "/" : `/${STATE.repo}`;const url = qs ? `${path}?${qs}` : path;if (replace) {history.replaceState(history.state, "", url);} else {history.pushState(null, "", url);}7 unmodified linesSTATE.query = Array.from(STATE.query).slice(0, 256).join("");showToast("搜索内容已限制为 256 个字符");}if (!searchComposing && !initialSearchDraft) setSearchInputValue(STATE.query);STATE.filterRepos = params.getAll("repo").map(r => `VoiceOfML/${r}`);STATE.browserPath = params.get("path") || "";const sort = normalizeSearchSort(params.get("sort"));DOM.sortSelect.value = sort;const extStr = params.get("ext");if (extStr !== null) {312 unmodified linesreturn result;}function currentSearchEntryKey() {return /** @type {Window & {navigation?: {currentEntry?: {key?: string} | null}}} */ (window).navigation?.currentEntry?.key;}function captureInitialSearchDraft(renew = false) {if (searchInputReady) return;initialSearchDraft = true;if (renew || !initialSearchDraftOwner) initialSearchDraftOwner = {href: location.href, key: currentSearchEntryKey(), cancelled: false};}function cancelInitialSearchDraft() {if (initialSearchDraftOwner) initialSearchDraftOwner.cancelled = true;}function initialSearchDraftIsCurrent() {const owner = initialSearchDraftOwner;return !owner || (!owner.cancelled && owner.href === location.href &&(owner.key === undefined || owner.key === currentSearchEntryKey()));}function finishInitialSearchInput(current) {for (const type of ["popstate", "hashchange", "pagehide"]) window.removeEventListener(type, cancelInitialSearchDraft, true);searchInputReady = true;if (!current) searchInputGeneration++;if (initialSearchDraft) {initialSearchDraft = false;if (current) debouncedSearch();}initialSearchDraftOwner = null;}function setupSearchInput() {for (const type of ["popstate", "hashchange", "pagehide"]) window.addEventListener(type, cancelInitialSearchDraft, true);DOM.searchInput.addEventListener("input", event => {const compositionInput = event.isComposing || event.inputType === "insertCompositionText" || event.inputType === "insertFromComposition";captureInitialSearchDraft(!searchComposing && !compositionInput);syncSearchInputState();if (compositionInput) return;debouncedSearch();});DOM.searchInput.addEventListener("compositionstart", () => {captureInitialSearchDraft(true);clearTimeout(searchTimer);searchTimer = null;searchComposing = true;searchCompositionGeneration = searchInputGeneration;searchCompositionViewKey = routeInitialized ? getSearchViewKey() : null;});DOM.searchInput.addEventListener("compositionend", () => {searchComposing = false;// Keep the visible draft, but an old view's completion cannot submit in B.if (searchCompositionGeneration !== searchInputGeneration ||(searchCompositionViewKey !== null && searchCompositionViewKey !== getSearchViewKey())) return;debouncedSearch();});}function debouncedSearch() {if (searchComposing || !searchInputReady) return;clearTimeout(searchTimer);const generation = searchInputGeneration;searchTimer = setTimeout(() => {searchTimer = null;if (searchComposing || generation !== searchInputGeneration) return;submitSearchQuery(DOM.searchInput.value.trim(), { record: true, refreshHistory: true });}, 100);}631 unmodified lines}function prepareFilterChange(clearResults) {// Merge completed query drafts too; a filter click must not discard typing.const query = searchTimer !== null && !searchComposing ? DOM.searchInput.value.trim() : null;applyPendingSizeFilters();cancelPendingSearchControls();saveSearchViewSnapshot();if (query !== null && Array.from(query).length <= 256) STATE.query = query;STATE.page = 1;if (clearResults) STATE.results = [];}32 unmodified linesfunction scheduleFilterSearch(clearResults = false) {prepareFilterChange(clearResults);if (!cancelActiveSearch()) return;const owner = searchId;cancelPositionRestore();if (owner !== searchId) return;resetPagingRecovery();STATE.isLoading = true;setSearchVisualLoading(true);syncStateToURL(true);27 unmodified lines}function cancelSearchPrefetch() {const previous = searchPrefetchAbortController;searchPrefetchAbortController = null;cancelPendingSearchCacheWrites();previous?.cacheWaits?.forEach(wait => wait.controller.abort());previous?.abort();}function cancelActiveSearch() {const id = ++searchId;searchRequestId++;const previous = searchAbortController;searchAbortController = new AbortController();cancelSearchPrefetch();previous?.abort();return id === searchId;}function prefetchSearchPages(base, template) {132 unmodified linesasync function doSearch(append = false, fromStart = false, restorePosition = false) {if (append && resultWindow) { loadResultWindowPage(STATE._loadedPage + 1); return; }const recoveringFirstPage = append && !STATE._loadedPage;if (recoveringFirstPage) append = false;if (!append && !fromStart) backToTopPending = false;if (!append && !cancelActiveSearch()) return;const owner = searchId;if (!append && prepareSearchPositionNavigation({ fromStart, restorePosition })) return;if (owner !== searchId) return;clearTimeout(filterSearchTimer);filterSearchTimer = null;if (!append) {2 unmodified linesselectedIndices = {};lastSelectedIndex = -1;if (DOM.multiSelectToggle && DOM.multiSelectToggle.checked) updateSelectionUI();STATE._pageCache = {};STATE._loadedPage = 0;STATE._pagingAppendScrollTop = null;1396 unmodified linesif (document.visibilityState === "hidden") flushSidebarScroll();});syncSearchInputState();setupSearchInput();// Session and position databases are independent; start both without// serializing their I/O. Route handling still waits for both to settle.const positionsReady = initSearchPositions();11 unmodified lineselse if (savedMobile === "desktop") STATE.isMobile = false;else STATE.isMobile = autoDetectMobile();applyMobileMode();setupSearchHistory();DOM.historyToggle.addEventListener("change", () => {STATE.recordHistory = DOM.historyToggle.checked;153 unmodified linesrestoreReaderOverlay(event.state);return;}// Apply the destination and retire A before Reader disposal or async B restoration.const overlay = readerOverlay;ROUTER.apply(!!overlay);if (readerOverlay === overlay) closeReaderOverlay();});window.addEventListener("resize", () => {if (!readSearchPreference("mobileMode")) {19 unmodified lineswindow.addEventListener("pageshow", resumeResultRecovery);window.addEventListener("online", resumeResultRecovery);window.setInterval(() => warmConnection(), KEEPALIVE_INTERVAL_MS);const initialDraftCurrent = initialSearchDraftIsCurrent();ROUTER.apply();finishInitialSearchInput(initialDraftCurrent);restoreReaderSearchHandoff();// Keep the first search paint independent of the multi-megabyte Reader sidecar.// API results already carry Reader fields; the sidecar is only enrichment for// local snapshots and directory browsing. Load it on the first real
424 unmodified lines425426427428429430431432433434424 unmodified lines}function bindReaderUiHistory() {// System back always leaves the Reader, exactly like its Back button. Do not// add a guard entry or re-push one from popstate: entries created without a// user activation make Chromium skip this document on the next back gesture,// landing on an older repository/book instead of the page that opened it.}function bindPanelBookmarkAndLifecycleControls() {424 unmodified lines425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471424 unmodified lines}function bindReaderUiHistory() {if (window !== window.top) return;const readerUrl = location.href;let loadingSearch = false;const restoreSearchDocument = (event) => {if (!event.isTrusted || loadingSearch || readerContext.readerLifecycle.disposed) return;// Reloading an overlay URL creates a standalone Reader document which can// still own the preceding same-document search entries. Back changes the// URL/state first; load THAT document without another traversal or rewrite.// Match the app's root / single-segment repository search routes.// Asset, API and Reader documents must never trigger search restoration.const parts = location.pathname.split("/").filter(Boolean);if (parts.length > 1 || ["static", "api", "reader", "reader.html"].includes(parts[0])) return;loadingSearch = true;try {sessionStorage.removeItem("reader-navigation-restore");const saved = JSON.parse(sessionStorage.getItem("reader-navigation-current") || "null");if (saved?.shareUrl === readerUrl && saved.readerUrl) {const source = new URL(saved.readerUrl, location.origin);const returnUrl = source.searchParams.get("return");const token = source.searchParams.get("nav");if (source.origin === location.origin && returnUrl === location.href && token &&sessionStorage.getItem(`reader-return:${token}`) === returnUrl) {// The host saves focus/scroll before mounting. The app consumes this// handoff after loading results; it is not a history-entry identity.sessionStorage.setItem("reader-navigation-restore", JSON.stringify({readerUrl: saved.readerUrl, returnUrl}));}}} catch (_) {}location.reload();};const resume = (event) => { if (event.persisted) loadingSearch = false; };window.addEventListener("popstate", restoreSearchDocument);window.addEventListener("pageshow", resume);// A failed book load stops book work but leaves this document's error UI// alive. Keep browser navigation until the document/runtime is disposed.readerContext.readerRuntime.track(() => {window.removeEventListener("popstate", restoreSearchDocument);window.removeEventListener("pageshow", resume);});}function bindPanelBookmarkAndLifecycleControls() {
43 unmodified lines444546474849226 unmodified lines27627727827928028148 unmodified lines33033133233333433533622 unmodified lines3593603613623633643653663674 unmodified lines3723733743753763773783793803817 unmodified lines3893903913923933944 unmodified lines39940040140240340440568 unmodified lines47447547647747847943 unmodified lines}/** @type {HTMLIFrameElement | null} */let frame = null;/** @type {HTMLElement | null} */let returnFocus = null;/** @type {{element: Element; inert: boolean; ariaHidden: string | null}[]} */226 unmodified lines}/** @param {URL} url */function mount(url) {const key = bookKey(url.href);if (parked && key && parked.key === key) {// The same book: show the Reader that kept reading, at its reading position.48 unmodified linesstatus.textContent = "正在打开阅读器...";opening.append(back, status);const reveal = () => {if (frame !== next || !opening) return;next.classList.remove("reader-overlay-pending");opening?.remove();opening = null;22 unmodified linesshade(next);return next;}function dismiss() {// Visually return immediately; history and resource cleanup still own// the actual close, including the stalled-history fallback.titleDismissed = true;restoreTitle();for (const target of [frame, opening]) if (target) {4 unmodified lines// `keepSpeech` parks a Reader that is reading aloud instead of disposing it.function unmount(keepSpeech = true) {if (!frame) return null;titleDismissed = true;restoreTitle();if (keepSpeech && opening === null && speech(frame)?.active) park(frame);else dispose(frame);frame = null;opening?.remove();opening = null;7 unmodified linesdocument.body.classList.remove("reader-overlay-open");const focus = returnFocus;returnFocus = null;return focus;}/** @param {string} raw @param {object} returnScroll @returns {HTMLIFrameElement | null} */4 unmodified linesif (!next.searchParams.get(key) && current.searchParams.get(key))next.searchParams.set(key, /** @type {string} */ (current.searchParams.get(key)));remember(next, returnScroll, true);const focus = unmount(bookKey(next.href) !== bookKey(current.href));mount(next);returnFocus = focus;return frame;68 unmodified linesremember,mount,dismiss,unmount,persistProgress,replace,43 unmodified lines44454647484950226 unmodified lines27727827928028128228348 unmodified lines33233333433533633733822 unmodified lines3613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044 unmodified lines4094104114124134144154164174184194207 unmodified lines4284294304314324334344354 unmodified lines44044144244344444544644744868 unmodified lines51751851952052152252343 unmodified lines}/** @type {HTMLIFrameElement | null} */let frame = null;let revision = 0;/** @type {HTMLElement | null} */let returnFocus = null;/** @type {{element: Element; inert: boolean; ariaHidden: string | null}[]} */226 unmodified lines}/** @param {URL} url */function mount(url) {revision++;const key = bookKey(url.href);if (parked && key && parked.key === key) {// The same book: show the Reader that kept reading, at its reading position.48 unmodified linesstatus.textContent = "正在打开阅读器...";opening.append(back, status);const reveal = () => {if (frame !== next || !opening || titleDismissed) return;next.classList.remove("reader-overlay-pending");opening?.remove();opening = null;22 unmodified linesshade(next);return next;}/** @param {string} raw */function showCloseRecovery(raw) {if (!frame || !titleDismissed) return;const searchPath = readerPath.slice(0, -"static/reader.html".length) || "/";let target = new URL(searchPath, location.origin);try {const candidate = new URL(raw, location.origin);if (candidate.origin === location.origin && !candidate.username && !candidate.password &&(searchPath === "/" ? candidate.pathname.split("/").filter(Boolean).length <= 1 : candidate.pathname === searchPath))target = candidate;} catch (_) {}if (!opening) {opening = document.createElement("div");opening.className = "reader-overlay-opening";document.body.append(opening);}const status = document.createElement("span");status.setAttribute("role", "status");status.textContent = "仍在等待返回搜索,可直接打开搜索页。";const link = document.createElement("a");link.textContent = "直接打开搜索页";link.href = target.href;link.addEventListener("click", () => {// Native navigation is an explicit recovery choice, not cancellation// of the outstanding Back. Reuse the validated focus/scroll handoff.try {sessionStorage.setItem("reader-navigation-restore", JSON.stringify({readerUrl: frame?.src, returnUrl: target.href}));} catch (_) {}});opening.replaceChildren(status, link);opening.style.removeProperty("opacity");opening.style.removeProperty("pointer-events");link.focus();}function dismiss() {// Visually return immediately; popstate still owns the actual close.titleDismissed = true;restoreTitle();for (const target of [frame, opening]) if (target) {4 unmodified lines// `keepSpeech` parks a Reader that is reading aloud instead of disposing it.function unmount(keepSpeech = true) {if (!frame) return null;revision++;titleDismissed = true;restoreTitle();const target = frame;const keep = keepSpeech && !target.classList.contains("reader-overlay-pending") && speech(target)?.active;// Release ownership before lifecycle callbacks can synchronously reenter.frame = null;opening?.remove();opening = null;7 unmodified linesdocument.body.classList.remove("reader-overlay-open");const focus = returnFocus;returnFocus = null;if (keep) park(target);else dispose(target);return focus;}/** @param {string} raw @param {object} returnScroll @returns {HTMLIFrameElement | null} */4 unmodified linesif (!next.searchParams.get(key) && current.searchParams.get(key))next.searchParams.set(key, /** @type {string} */ (current.searchParams.get(key)));remember(next, returnScroll, true);const expected = revision + 1;const focus = unmount(bookKey(next.href) !== bookKey(current.href));if (revision !== expected) return frame;mount(next);returnFocus = focus;return frame;68 unmodified linesremember,mount,dismiss,showCloseRecovery,unmount,persistProgress,replace,
3 unmodified lines45678910111213148 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101113 unmodified linesconst DB_NAME = "voiceofml-search-state";const SESSION_TIMEOUT_MS = 1500;/** @returns {Promise<IDBDatabase>} */function openSearchSessionDB() {return new Promise((resolve, reject) => {if (!window.indexedDB) return reject(new Error("IndexedDB unavailable"));const request = indexedDB.open(DB_NAME, 1);let settled = false;const timer = setTimeout(() => fail(new Error("IndexedDB open timed out")), SESSION_TIMEOUT_MS);/** @param {unknown} error */8 unmodified lines};request.onsuccess = () => {const db = request.result;if (settled) { db.close(); return; }settled = true;clearTimeout(timer);db.onversionchange = () => db.close();resolve(db);};request.onerror = () => fail(request.error);request.onblocked = () => fail(new Error("IndexedDB open blocked"));});}/** @template T @param {IDBRequest<T>} request @param {IDBTransaction} transaction @returns {Promise<T>} */function readSessionValue(request, transaction) {return new Promise((resolve, reject) => {let settled = false;const timer = setTimeout(() => {if (settled) return;settled = true;try { transaction.abort(); } catch (_) {}reject(new Error("IndexedDB read timed out"));}, SESSION_TIMEOUT_MS);request.onsuccess = () => {if (settled) return;settled = true; clearTimeout(timer); resolve(request.result);};request.onerror = () => {if (settled) return;settled = true; clearTimeout(timer); reject(request.error);};});}/** @param {IDBTransaction} transaction @returns {Promise<void>} */function waitForTransaction(transaction) {return new Promise((resolve, reject) => {const timer = setTimeout(() => {try { transaction.abort(); } catch (_) {}reject(new Error("IndexedDB transaction timed out"));}, SESSION_TIMEOUT_MS);transaction.oncomplete = () => { clearTimeout(timer); resolve(); };transaction.onerror = transaction.onabort = () => { clearTimeout(timer); reject(transaction.error); };});}/** @param {{canPersist: () => boolean, canRestore: (target?: URL) => boolean}} options */function createSearchSession({ canPersist, canRestore }) {async function persistSearchSession() {if (!canPersist()) return;let db;try {db = await openSearchSessionDB();const transaction = db.transaction("session", "readwrite");transaction.objectStore("session").put({ version: 1, url: location.href, updatedAt: Date.now() },"last-search");await waitForTransaction(transaction);} catch (_) {// Session persistence is best effort and must never block search.} finally {if (db) db.close();}}async function restoreSearchSession() {if (!canRestore()) return false;let db;try {db = await openSearchSessionDB();const transaction = db.transaction("session", "readonly");const request = transaction.objectStore("session").get("last-search");/** @type {unknown} */const saved = await readSessionValue(request, transaction);if (!saved || typeof saved !== "object" || !("version" in saved) || saved.version !== 1 ||!("url" in saved) || typeof saved.url !== "string") return false;const target = new URL(saved.url);// A user may have navigated while IndexedDB was opening or reading.if (!canRestore() || !canRestore(target)) return false;history.replaceState(null, "", target.href);return true;} catch (_) {return false;} finally {if (db) db.close();}}3 unmodified lines456789101112131415161718192021222324252627288 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961973 unmodified linesconst DB_NAME = "voiceofml-search-state";const SESSION_TIMEOUT_MS = 1500;// A deadline settles the caller, but only a native terminal event retires// the operation. In particular, blocked opens cannot be cancelled.function startSessionOpen() {/** @type {() => void} */let finish = () => {};/** @type {Promise<void>} */const finished = new Promise(resolve => { finish = resolve; });/** @type {Promise<IDBDatabase>} */const result = new Promise((resolve, reject) => {/** @type {IDBOpenDBRequest} */let request;try {if (!window.indexedDB) throw new Error("IndexedDB unavailable");request = indexedDB.open(DB_NAME, 1);} catch (error) {finish();reject(error);return;}let settled = false;const timer = setTimeout(() => fail(new Error("IndexedDB open timed out")), SESSION_TIMEOUT_MS);/** @param {unknown} error */8 unmodified lines};request.onsuccess = () => {const db = request.result;finish();if (settled) { db.close(); return; }settled = true;clearTimeout(timer);db.onversionchange = () => db.close();resolve(db);};request.onerror = () => { finish(); fail(request.error); };request.onblocked = () => fail(new Error("IndexedDB open blocked"));});return { result, finished };}/** @returns {Promise<IDBDatabase>} */function openSearchSessionDB() {return startSessionOpen().result;}/** @param {IDBTransaction} transaction */function watchTransaction(transaction) {/** @type {(success: boolean) => void} */let settle = () => {};/** @type {() => void} */let finish = () => {};/** @type {Promise<boolean>} */const result = new Promise(resolve => { settle = resolve; });/** @type {Promise<void>} */const finished = new Promise(resolve => { finish = resolve; });let failed = false;function fail() {if (failed) return;failed = true;clearTimeout(timer);settle(false);// abort() may throw or return before onabort. Neither releases a writer.try { transaction.abort(); } catch (_) {}}const timer = setTimeout(fail, SESSION_TIMEOUT_MS);transaction.onerror = fail;transaction.onabort = () => { clearTimeout(timer); settle(false); finish(); };transaction.oncomplete = () => { clearTimeout(timer); settle(!failed); finish(); };return { result, finished, fail };}/** @typedef {{version: number, url: string, updatedAt: number}} SessionSnapshot *//** @typedef {{snapshot: SessionSnapshot, result: Promise<void>, settle: () => void}} SaveBatch */// Shared by adapters in this document: one active operation and one latest// pending snapshot, with a shared (bounded) wait for every pending caller./** @type {SaveBatch | null} */let pendingSave = null;let saving = false;/** @param {SessionSnapshot} snapshot @returns {SaveBatch} */function createSaveBatch(snapshot) {/** @type {() => void} */let settle = () => {};/** @type {Promise<void>} */const result = new Promise(resolve => {const timer = setTimeout(resolve, SESSION_TIMEOUT_MS);settle = () => { clearTimeout(timer); resolve(); };});return { snapshot, result, settle };}async function drainSaves() {saving = true;try {while (pendingSave) {const batch = pendingSave;pendingSave = null;const opening = startSessionOpen();/** @type {IDBDatabase | undefined} */let db;/** @type {ReturnType<typeof watchTransaction> | undefined} */let completion;try {db = await opening.result;const transaction = db.transaction("session", "readwrite");completion = watchTransaction(transaction);try {transaction.objectStore("session").put(batch.snapshot, "last-search");} catch (_) {completion.fail();}await completion.result;} catch (_) {// Persistence is best effort. A failed open/transaction must not// leak a rejection into the search UI.} finally {if (db) db.close();batch.settle();}// A permanently stalled native operation parks this single worker.// New saves replace the one pending snapshot; no promise chain grows.await opening.finished;if (completion) await completion.finished;}} finally {saving = false;}}/** @param {{canPersist: () => boolean, canRestore: (target?: URL) => boolean}} options */function createSearchSession({ canPersist, canRestore }) {function persistSearchSession() {if (!canPersist()) return Promise.resolve();// Capture eligibility and the immutable value together, before any await.const snapshot = { version: 1, url: location.href, updatedAt: Date.now() };if (pendingSave) pendingSave.snapshot = snapshot;else pendingSave = createSaveBatch(snapshot);const result = pendingSave.result;if (!saving) void drainSaves();return result;}async function restoreSearchSession() {if (!canRestore()) return false;const startingHref = location.href;// Navigation entry identity is independent of classic history.state.const navigation = /** @type {Window & {navigation?: {currentEntry?: {key?: string} | null}}} */ (window).navigation;const startingKey = navigation?.currentEntry?.key;let cancelled = false;const cancel = () => { cancelled = true; };const events = ["popstate", "hashchange", "pagehide", "input", "compositionstart", "compositionupdate", "compositionend"];let db;try {for (const type of events) window.addEventListener(type, cancel, true);db = await openSearchSessionDB();const transaction = db.transaction("session", "readonly");const completion = watchTransaction(transaction);/** @type {unknown} */let saved;try {const request = transaction.objectStore("session").get("last-search");request.onsuccess = () => { saved = request.result; };request.onerror = completion.fail;} catch (_) {completion.fail();}// Request success is provisional: an abort later in the same// transaction must never publish a saved URL.if (!await completion.result) return false;if (!saved || typeof saved !== "object" || !("version" in saved) || saved.version !== 1 ||!("url" in saved) || typeof saved.url !== "string") return false;const target = new URL(saved.url);// A user may have navigated while IndexedDB was opening or reading.if (cancelled || location.href !== startingHref ||(startingKey !== undefined && navigation?.currentEntry?.key !== startingKey) ||!canRestore() || !canRestore(target)) return false;history.replaceState(history.state, "", target.href);return true;} catch (_) {return false;} finally {for (const type of events) window.removeEventListener(type, cancel, true);if (db) db.close();}}
932 unmodified lines933934935936937938932 unmodified lines"tests/service_worker/test_service_worker_pruning.js": {"kind": "direct","source": "@reader-workflow"}}}932 unmodified lines933934935936937938939940941942943944945946947948949950951952953954955956957958932 unmodified lines"tests/service_worker/test_service_worker_pruning.js": {"kind": "direct","source": "@reader-workflow"},"tests/search/session/test_search_session_contract.js": {"kind": "direct","source": "@reader-workflow"},"tests/search/reader-navigation/test_search_history_races.mjs": {"kind": "direct","source": "@reader-workflow"},"tests/search/browser/test_session_transaction_browser.py": {"kind": "direct","source": "@reader-workflow"},"tests/reader/browser/test_reader_reload_search_document.py": {"kind": "direct","source": "@reader-workflow"},"tests/reader/browser/test_reader_host_history_races.py": {"kind": "direct","source": "@reader-workflow"}}}
2141 unmodified lines21422143214421452146214721482149215033 unmodified lines21842185218621872188218921902141 unmodified linestarget.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(ROOT / path, target)check = ["node", paths[1]]self.assert_check(self.run_check(*check), True, "# pass 11")test = self.root / paths[2]source = test.read_text()name = 'remember stores a private reader URL but exposes a sanitized history URL'anchor = "test('" + name + "'"self.assertEqual(source.count(anchor), 1)33 unmodified linesgate.write_text(original.replace('const required = [', 'const duplicateRows = rows.concat(rows);\nconst required = [').replace('rows.length !== 1', 'duplicateRows.length !== 1'))self.assert_check(self.run_check(*check), False, 'one source row above each minimum')for thresholds in ('[35.86, 81.82, 27.27]', '[31.96, 84.10, 27.27]', '[31.96, 81.82, 27.28]'):self.assertIn('[31.96, 81.82, 27.27]', original)gate.write_text(original.replace('[31.96, 81.82, 27.27]', thresholds))self.assert_check(self.run_check(*check), False, 'one source row above each minimum')2141 unmodified lines214221432144214521462147214821492150215121522153215421552156215721582159216033 unmodified lines2194219521962197219821992200220122022141 unmodified linestarget.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(ROOT / path, target)check = ["node", paths[1]]self.assert_check(self.run_check(*check), True, "# pass 15")test = self.root / paths[2]source = test.read_text()for new_name in ('replacement revision preserves a Reader opened synchronously during disposal','ordinary replacement carries handoff and focus while releasing background ownership','close recovery validates both search routes without changing history or private handoff','recovery survives late shell load and records handoff only on native link activation',):new_anchor = "test('" + new_name + "'"self.assertEqual(source.count(new_anchor), 1)test.write_text(source.replace(new_anchor, "test('missing new contract'"))self.assert_check(self.run_check(*check), False, "all named baseline contracts")name = 'remember stores a private reader URL but exposes a sanitized history URL'anchor = "test('" + name + "'"self.assertEqual(source.count(anchor), 1)33 unmodified linesgate.write_text(original.replace('const required = [', 'const duplicateRows = rows.concat(rows);\nconst required = [').replace('rows.length !== 1', 'duplicateRows.length !== 1'))self.assert_check(self.run_check(*check), False, 'one source row above each minimum')# Independent impossible thresholds keep these negative controls valid# when additional meaningful contracts improve actual coverage.for thresholds in ('[100.01, 81.82, 27.27]', '[31.96, 100.01, 27.27]', '[31.96, 81.82, 100.01]'):self.assertIn('[31.96, 81.82, 27.27]', original)gate.write_text(original.replace('[31.96, 81.82, 27.27]', thresholds))self.assert_check(self.run_check(*check), False, 'one source row above each minimum')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378"""Current search/Reader traversal and deterministic input ownership regressions."""import unittestfrom tests.search.browser import test_paging_recovery as paging
class ReaderHostHistoryRaceTests(unittest.TestCase): @classmethod def setUpClass(cls): paging.PagingRecoveryTests.setUpClass()
@classmethod def tearDownClass(cls): paging.PagingRecoveryTests.tearDownClass()
def setUp(self): self.fixture = paging.PagingRecoveryTests() self.fixture.setUp() self.page = self.fixture.page self.page.route('**/static/reader.html?**', lambda route: route.fulfill( content_type='text/html', body='<body>reader</body>')) self.page.evaluate('''() => { window.historySearchUrl = (query, extra = '') => location.pathname.startsWith('/search/') ? '/search/#/?q=' + query + '&local=0' + extra : '/?q=' + query + extra; window.historyReaderUrl = () => location.pathname.startsWith('/search/') ? '/search/static/reader.html?ext=txt' : '/static/reader.html?ext=txt'; }''')
def tearDown(self): errors = list(self.fixture.errors) self.fixture.tearDown() self.assertEqual(errors, [])
def test_product_automatically_saves_and_restores_search_session(self): self.page.locator('#search-input').fill('paging-auto-session') self.page.wait_for_function("STATE.query === 'paging-auto-session' && !STATE.isLoading && STATE._loadedPage === 1") saved_url = self.page.url self.page.wait_for_function('''expected => new Promise(resolve => { const request = indexedDB.open('voiceofml-search-state', 1); request.onerror = () => resolve(false); request.onsuccess = () => { const db = request.result; const tx = db.transaction('session', 'readonly'); const read = tx.objectStore('session').get('last-search'); let saved; read.onsuccess = () => { saved = read.result; }; tx.oncomplete = () => { db.close(); resolve(saved?.url === expected); }; tx.onabort = tx.onerror = () => { db.close(); resolve(false); }; }; })''', arg=saved_url) bare = '/search/' if '/search/' in saved_url else '/' self.page.goto(self.fixture.origin + bare, wait_until='domcontentloaded') self.page.wait_for_function("STATE.query === 'paging-auto-session' && !STATE.isLoading && STATE._loadedPage === 1") self.assertEqual(self.page.url, saved_url) self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-auto-session') self.assertGreater(self.page.locator('#results-list .result-item').count(), 0)
def test_go_minus_two_applies_destination_before_dispose_and_held_restoration(self): self.page.evaluate('''() => { history.replaceState({foreign:'B'}, '', historySearchUrl('paging-B', '&sort=size')); ROUTER.apply(); }''') self.page.wait_for_function("STATE.query === 'paging-B' && !STATE.isLoading && STATE._loadedPage === 1") self.page.evaluate('''() => { history.pushState({foreign:'A'}, '', historySearchUrl('paging-A', '&sort=name')); ROUTER.apply(); }''') self.page.wait_for_function("STATE.query === 'paging-A' && !STATE.isLoading && STATE._loadedPage === 1") self.page.evaluate('''() => { // Force B through asynchronous viewport restoration, while A still has // a live prefetch consumer. No test-only session save is involved. searchViewSnapshots.clear(); const oldRead = readSearchViewport; readSearchViewport = key => JSON.parse(key).query === 'paging-B' ? new Promise(resolve => { window.releaseBViewport = () => resolve(null); }) : oldRead(key); const oldTarget = getReturnPositionTarget; getReturnPositionTarget = key => key && JSON.parse(key).query === 'paging-B' ? {version:1,key,index:1,offset:0,loadedPage:1,savedAt:Date.now()} : oldTarget(key); DOM.searchInput.focus(); navigateToReader(historyReaderUrl()); window.oldSearchId = searchRequestId; }''') self.page.wait_for_function("readerOverlay && readerOverlay.contentDocument?.body?.textContent === 'reader'") self.page.evaluate('''() => { readerOverlay.contentWindow.addEventListener('voice-reader-dispose', () => { window.atDispose = {query:STATE.query,sort:DOM.sortSelect.value, retired:searchRequestId > oldSearchId,overlayReleased:readerOverlay === null}; // Reentrant close must be harmless. closeReaderOverlay(); window.releaseStalePage(); }); history.go(-2); }''') self.page.wait_for_function('!!window.atDispose && typeof window.releaseBViewport === "function"') self.assertEqual(self.page.evaluate('atDispose'), dict(query='paging-B', sort='size', retired=True, overlayReleased=True)) self.page.evaluate('releaseBViewport()') self.page.wait_for_function("STATE.query === 'paging-B' && !STATE.isLoading && STATE._loadedPage === 1") self.assertFalse(self.page.evaluate("STATE.results.some(r => r.File.startsWith('stale-'))")) self.assertTrue(self.page.evaluate("document.activeElement === DOM.searchInput")) self.assertIn('q=paging-B', self.page.url)
def test_same_view_route_keeps_pending_filter_debounce(self): self.page.evaluate('''() => { STATE.filterExtensions = ['txt']; scheduleFilterSearch(true); window.pendingFilter = filterSearchTimer; ROUTER.apply(true); window.filterPreserved = filterSearchTimer === pendingFilter && filterSearchTimer !== null; }''') self.assertTrue(self.page.evaluate('filterPreserved')) self.page.wait_for_function('!STATE.isLoading && STATE._loadedPage === 1 && filterSearchTimer === null') self.assertEqual(self.page.evaluate('STATE.filterExtensions'), ['txt'])
def test_replace_and_restore_yield_to_reader_opened_during_dispose(self): for action in ('replace', 'restore'): result = self.page.evaluate('''action => { const path = new URL(historyReaderUrl(), location.origin).pathname; navigateToReader(path + '?ext=txt&id=A'); const first = readerOverlay; first.contentWindow.addEventListener('voice-reader-dispose', () => { navigateToReader(path + '?ext=txt&id=C'); }); if (action === 'replace') handleReaderMessage({origin:location.origin,source:first.contentWindow, data:{type:'voice-reader-open',url:path+'?ext=txt&id=B'}}); else restoreReaderOverlay({voiceReaderOverlay:true,readerUrl:path+'?ext=txt&id=B'}); const result = {id:new URL(readerOverlay.src).searchParams.get('id'), connected:readerOverlay.isConnected,count:document.querySelectorAll('iframe.reader-overlay').length}; closeReaderOverlay(false,false); history.replaceState(null,'',historySearchUrl('paging')); return result; }''', action) self.assertEqual(result, dict(id='C', connected=True, count=1))
def test_dispose_reentry_mounts_new_reader_without_outer_cleanup(self): result = self.page.evaluate('''() => { const path = new URL(historyReaderUrl(), location.origin).pathname; const nav = VoiceOfMLReaderNavigation.createNavigation(path); const first = nav.mount(new URL(path + '?ext=txt&id=first', location.origin)); let second; first.contentWindow.addEventListener('voice-reader-dispose', () => { nav.unmount(false); second = nav.mount(new URL(path + '?ext=txt&id=second', location.origin)); }); nav.unmount(false); const result = {firstRemoved:!first.isConnected,secondConnected:second.isConnected, accepted:nav.accepts({origin:location.origin,source:second.contentWindow}), shaded:document.body.classList.contains('reader-overlay-open')}; nav.unmount(false); return result; }''') self.assertTrue(all(result.values()), result)
def test_same_view_reader_back_retains_flight_scroll_and_focus(self): self.page.evaluate('''() => { DOM.searchInput.focus(); setResultScrollTop(900); // Keep a live foreground subscriber to the held page-2 prefetch. // Capture after this scroll's append request acquires its request ID. STATE.page = 2; doSearch(true); window.beforeReader = {top:getResultScrollTop(), request:searchRequestId, controller:searchAbortController}; navigateToReader(historyReaderUrl()); history.back(); }''') self.page.wait_for_function('!readerOverlay') self.assertTrue(self.page.evaluate('searchRequestId === beforeReader.request && searchAbortController === beforeReader.controller')) self.assertTrue(self.page.evaluate('STATE.isLoading && STATE._pendingPage === 2 && !searchAbortController.signal.aborted')) self.assertEqual(self.page.evaluate('pagingRequests.filter(page => page === 2).length'), 1) self.assertTrue(self.page.evaluate('document.activeElement === DOM.searchInput')) self.assertLessEqual(abs(self.page.evaluate('getResultScrollTop() - beforeReader.top')), 1)
def test_compositionstart_cancels_preexisting_debounce(self): self.page.evaluate('''() => { DOM.searchInput.value = 'paging-draft'; DOM.searchInput.dispatchEvent(new Event('input', {bubbles:true})); DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart', {data:'中'})); DOM.searchInput.value = 'paging-中'; }''') self.page.wait_for_timeout(180) self.assertEqual(self.page.evaluate('STATE.query'), 'paging') self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend', {data:'中'}))") self.page.wait_for_function("STATE.query === 'paging-中' && !STATE.isLoading")
def test_initial_storage_wait_preserves_draft_and_composition(self): self.check_initial_storage_draft(False)
def test_initial_storage_navigation_keeps_old_draft_without_submitting_in_b(self): self.check_initial_storage_draft(True)
def test_initial_storage_navigation_accepts_new_edit_and_composition_in_b(self): self.check_initial_storage_draft(True, renew=True)
def check_initial_storage_draft(self, navigate, renew=False): self.page.add_init_script('''(() => { const open = indexedDB.open.bind(indexedDB); window.releaseInitialStorage = []; window.holdInitialStorage = true; indexedDB.open = (...args) => { const request = open(...args); return new Proxy(request, { get: (target, key) => target[key], set(target, key, value) { target[key] = key === 'onsuccess' ? event => { if (window.holdInitialStorage) releaseInitialStorage.push(() => value(event)); else value(event); } : value; return true; } }); }; })();''') for composing in (False, True): with self.subTest(composing=composing): self.page.reload(wait_until='domcontentloaded') self.page.wait_for_function('window.releaseInitialStorage?.length > 0') self.assertFalse(self.page.evaluate('routeInitialized')) if navigate: self.page.evaluate('''() => { const original = location.href; const target = location.pathname.startsWith('/search/') ? '/search/#/?q=paging-startup-B&local=0' : '/?q=paging-startup-B'; history.replaceState(null, '', target); history.pushState(null, '', original); }''') self.page.evaluate('''composing => { DOM.searchInput.focus(); if (composing) DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart')); DOM.searchInput.value = composing ? 'paging-early-composing' : 'paging-early'; DOM.searchInput.setSelectionRange(3, 7); DOM.searchInput.dispatchEvent(new InputEvent('input', {bubbles:true, isComposing:composing})); window.initialRouteQuery = new URLSearchParams(location.search || location.hash.split('?')[1]).get('q'); }''', composing) if navigate: self.page.evaluate('''() => new Promise(resolve => { window.addEventListener('popstate', resolve, {once:true}); history.back(); })''') if renew: self.page.evaluate('''composing => { if (composing) { DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend')); DOM.searchInput.dispatchEvent(new InputEvent('input', { bubbles:true, inputType:'insertCompositionText' })); } }''', composing) self.assertFalse(self.page.evaluate('initialSearchDraftIsCurrent()')) self.page.evaluate('''composing => { if (composing) DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart')); DOM.searchInput.value = composing ? 'paging-early-composing' : 'paging-early'; DOM.searchInput.setSelectionRange(3, 7); DOM.searchInput.dispatchEvent(new InputEvent('input', { bubbles:true, isComposing:composing, inputType:composing ? 'insertCompositionText' : 'insertText' })); window.initialRouteQuery = 'paging-startup-B'; }''', composing) self.assertTrue(self.page.evaluate('initialSearchDraftIsCurrent()')) self.page.evaluate('''() => { window.holdInitialStorage = false; releaseInitialStorage.splice(0).forEach(release => release()); }''') self.page.wait_for_function('routeInitialized') if navigate and not renew: self.page.wait_for_timeout(180) self.assertEqual(self.page.evaluate('STATE.query'), 'paging-startup-B') draft = 'paging-early-composing' if composing else 'paging-early' self.assertEqual(self.page.locator('#search-input').input_value(), draft) if composing: self.assertTrue(self.page.evaluate('searchComposing')) self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))") self.page.wait_for_timeout(180) self.assertEqual(self.page.evaluate('STATE.query'), 'paging-startup-B') self.page.locator('#search-input').fill('paging-new-startup-edit') self.page.wait_for_function("STATE.query === 'paging-new-startup-edit' && !STATE.isLoading") continue if composing: self.assertTrue(self.page.evaluate('searchComposing')) self.assertEqual(self.page.evaluate('STATE.query'), self.page.evaluate('initialRouteQuery')) self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-early-composing') self.assertEqual(self.page.evaluate('[DOM.searchInput.selectionStart, DOM.searchInput.selectionEnd]'), [3, 7]) self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))") expected = 'paging-early-composing' if composing else 'paging-early' self.page.wait_for_function('query => STATE.query === query && !STATE.isLoading', arg=expected) self.assertEqual(self.page.locator('#search-input').input_value(), expected)
def test_long_composition_waits_for_real_completion(self): self.page.evaluate('''() => { DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart')); DOM.searchInput.value = 'paging-long-composition'; DOM.searchInput.dispatchEvent(new InputEvent('input', {bubbles:true, isComposing:true})); }''') self.page.wait_for_timeout(5200) self.assertEqual(self.page.evaluate('STATE.query'), 'paging') self.assertTrue(self.page.evaluate('searchComposing')) self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))") self.page.wait_for_function("STATE.query === 'paging-long-composition' && !STATE.isLoading")
def test_composition_from_previous_view_cannot_submit_but_new_input_can(self): self.page.evaluate('''() => { DOM.searchInput.focus(); DOM.searchInput.dispatchEvent(new CompositionEvent('compositionstart')); DOM.searchInput.value = 'paging-composing-A'; history.pushState(null, '', historySearchUrl('paging-B')); ROUTER.apply(); }''') self.page.wait_for_function("STATE.query === 'paging-B' && !STATE.isLoading") self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-composing-A') self.page.evaluate("DOM.searchInput.dispatchEvent(new CompositionEvent('compositionend'))") self.page.wait_for_timeout(180) self.assertEqual(self.page.evaluate('STATE.query'), 'paging-B') input_type = self.page.evaluate('''() => { // Use a recognized type: an unsupported constructor value can become // an empty string, which is indistinguishable from ordinary input. const tail = new InputEvent('input', {bubbles:true, inputType:'insertCompositionText'}); DOM.searchInput.dispatchEvent(tail); return tail.inputType; }''') self.assertEqual(input_type, 'insertCompositionText') self.page.wait_for_timeout(180) self.assertEqual(self.page.evaluate('STATE.query'), 'paging-B') self.page.locator('#search-input').press('Enter') self.page.wait_for_function("STATE.query === 'paging-composing-A' && !STATE.isLoading") self.page.locator('#search-input').fill('paging-deliberate-edit') self.page.wait_for_function("STATE.query === 'paging-deliberate-edit' && !STATE.isLoading")
def test_query_debounce_is_retired_by_a_different_view(self): self.page.evaluate('''() => { DOM.searchInput.value = 'paging-obsolete-draft'; DOM.searchInput.dispatchEvent(new Event('input', {bubbles:true})); history.pushState(null, '', historySearchUrl('paging-B')); ROUTER.apply(); }''') self.page.wait_for_timeout(180) self.assertEqual(self.page.evaluate('STATE.query'), 'paging-B') self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-B')
def test_pending_query_and_filter_are_submitted_together(self): self.page.evaluate('''() => { DOM.searchInput.value = 'paging-filter-draft'; DOM.searchInput.dispatchEvent(new Event('input', {bubbles:true})); DOM.sortSelect.value = 'size'; DOM.sortSelect.dispatchEvent(new Event('change', {bubbles:true})); }''') self.page.wait_for_function("STATE.query === 'paging-filter-draft' && !STATE.isLoading") self.assertEqual(self.page.evaluate('DOM.searchInput.value'), 'paging-filter-draft') self.assertEqual(self.page.evaluate('DOM.sortSelect.value'), 'size') self.assertIn('q=paging-filter-draft', self.page.url) self.assertIn('sort=size', self.page.url)
def test_abort_reentry_new_query_owns_request_and_result(self): self.page.evaluate('''() => { searchAbortController.signal.addEventListener('abort', () => { submitSearchQuery('paging-reentrant', {updateInput:true}); }, {once:true}); submitSearchQuery('paging-superseded', {updateInput:true}); }''') self.page.wait_for_function("STATE.query === 'paging-reentrant' && !STATE.isLoading && STATE._loadedPage === 1") self.assertEqual(self.page.evaluate('DOM.searchInput.value'), 'paging-reentrant') self.assertIn('q=paging-reentrant', self.page.url) self.assertTrue(self.page.evaluate('!searchAbortController.signal.aborted'))
def test_invalid_history_sort_uses_backend_whitelist(self): self.page.evaluate('''() => { const previous = window.fetch; window.seenSort = []; window.fetch = (input, options) => { const body = JSON.parse(options?.body || '{}'); if (String(input).includes('/api/search') && body.q === 'paging-invalid-sort') { window.seenSort.push(body.sort); if (!['relevance','name','size'].includes(body.sort)) return Promise.resolve(new Response('{}',{status:422})); } return previous(input, options); }; history.pushState(null, '', historySearchUrl('paging-invalid-sort', '&sort=invalid')); ROUTER.apply(); }''') self.page.wait_for_function("STATE.query === 'paging-invalid-sort' && !STATE.isLoading && STATE._loadedPage === 1") self.assertEqual(self.page.evaluate('DOM.sortSelect.value'), 'relevance') self.assertTrue(self.page.evaluate("seenSort.length > 0 && seenSort.every(sort => sort === 'relevance')"))389 unmodified lines39039139239339439539639739839940040154 unmodified lines456457458459460461462463464465466467361 unmodified lines829830831389 unmodified linesdef test_back_tap_recovers_when_history_traversal_never_arrives(self):self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')self.page.frame_locator('.reader-overlay').locator('body').wait_for()self.page.evaluate("""() => {const back = history.back; history.back = () => {};handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});history.back = back;}""")self.page.locator('.reader-overlay').wait_for(state='detached', timeout=3000)self.assertFalse(self.page.evaluate('readerClosing'))self.assertFalse(self.page.evaluate('!!history.state?.voiceReaderOverlay'))self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')54 unmodified linesnavigateToReader('/static/reader.html?ext=txt');const button=document.querySelector('.reader-overlay-opening button');button?.click();return !!button;}''')self.assertTrue(present)self.page.wait_for_function('() => !readerClosing', timeout=3000)self.page.locator('.reader-overlay-opening').wait_for(state='detached', timeout=3000)self.assertFalse(self.page.evaluate('readerClosing'))self.page.evaluate('() => {history.back=window.__nativeBack;}')for route in held:route.fulfill(content_type='text/html', body='<body>cancelled</body>')def test_closing_a_speech_reader_does_not_leave_the_reopened_frame_hidden(self):self.page.evaluate('navigateToReader("/static/reader.html?id=speech-resume&ext=txt")')361 unmodified lines} finally {Storage.prototype.setItem=original;}}''')self.assertTrue(result)389 unmodified lines39039139239339439539639739839940040140240340440540640740840941041141241341454 unmodified lines469470471472473474475476477478479480481482483484485486487488489490361 unmodified lines852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919389 unmodified linesdef test_back_tap_recovers_when_history_traversal_never_arrives(self):self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')self.page.frame_locator('.reader-overlay').locator('body').wait_for()target = self.page.evaluate('new URL(readerOverlay.src).searchParams.get("return")')self.page.evaluate("""() => {window.__backCalls = 0;history.back = () => { __backCalls++; };handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});}""")# Automatic replacement destroyed the Reader entry when Back was late.# The stalled contract now requires a visible, usable explicit recovery.recovery = self.page.get_by_role('link', name='直接打开搜索页')recovery.wait_for(state='visible', timeout=3000)self.assertEqual(recovery.get_attribute('href'), target)self.assertFalse(recovery.evaluate('link => !!link.closest("[inert]")'))self.assertEqual(self.page.evaluate('__backCalls'), 1)self.assertTrue(self.page.evaluate('readerClosing && history.state.voiceReaderOverlay'))with self.page.expect_navigation(wait_until='domcontentloaded'):recovery.click()self.assertEqual(self.page.url, target)self.page.wait_for_function('STATE.results.length > 0 && !STATE.isLoading')self.assertEqual(self.page.locator('.reader-overlay').count(), 0)self.assertFalse(self.page.evaluate('readerClosing'))self.assertFalse(self.page.evaluate('!!history.state?.voiceReaderOverlay'))self.page.evaluate('navigateToReader("/static/reader.html?ext=txt")')54 unmodified linesnavigateToReader('/static/reader.html?ext=txt');const button=document.querySelector('.reader-overlay-opening button');button?.click();return !!button;}''')self.assertTrue(present)recovery = self.page.get_by_role('link', name='直接打开搜索页')recovery.wait_for(state='visible', timeout=3000)self.assertFalse(recovery.evaluate('link => !!link.closest("[inert]")'))self.assertTrue(held)for route in held:route.fulfill(content_type='text/html', body='<body>late reader shell</body>')self.page.frame_locator('.reader-overlay').locator('body').wait_for()self.page.frame_locator('.reader-overlay').locator('body').evaluate('() => window.parent.postMessage({type:"voice-reader-shell"},location.origin)')self.assertTrue(recovery.is_visible(), 'late load must not dismiss the recovery shell')with self.page.expect_navigation(wait_until='domcontentloaded'):recovery.click()self.page.wait_for_function('STATE.results.length > 0 && !STATE.isLoading')self.assertEqual(self.page.locator('.reader-overlay-opening').count(), 0)self.assertEqual(self.page.locator('.reader-overlay').count(), 0)self.assertFalse(self.page.evaluate('readerClosing'))def test_closing_a_speech_reader_does_not_leave_the_reopened_frame_hidden(self):self.page.evaluate('navigateToReader("/static/reader.html?id=speech-resume&ext=txt")')361 unmodified lines} finally {Storage.prototype.setItem=original;}}''')self.assertTrue(result)def test_watchdog_late_back_preserves_reader_forward_and_foreign_state(self):self.page.locator('#search-input').focus()before = self.page.evaluate('''() => {history.replaceState({...history.state, foreignSearch:{keep:1}}, '', location.href);return {url:location.href, state:history.state, rows:STATE.results.map(getResultStableId)};}''')opened = self.page.evaluate('''() => {const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html');navigateToReader(path+'?ext=txt&title=Delayed');history.replaceState({...history.state, foreignReader:{keep:2}}, '', location.href);return {url:location.href, state:history.state, length:history.length};}''')self.page.frame_locator('.reader-overlay').locator('body').wait_for()self.page.evaluate('''() => {const back=history.back.bind(history);window.__releaseBack=()=>{history.back=back;back();};window.__backCalls=0; window.__historyWrites=0;history.back=()=>{__backCalls++;};for (const name of ['pushState','replaceState']) {const original=history[name].bind(history);history[name]=(...args)=>{__historyWrites++;return original(...args);};}window.__returnSnapshot=readerReturnSnapshot;handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});}''')recovery = self.page.get_by_role('link', name='直接打开搜索页')recovery.wait_for(state='visible', timeout=3000)self.assertEqual(self.page.evaluate('({url:location.href,state:history.state,length:history.length})'), opened)self.assertEqual(self.page.evaluate('[__backCalls,__historyWrites]'), [1, 0])self.assertTrue(self.page.evaluate('readerClosing && readerReturnSnapshot === __returnSnapshot'))# Release the sole requested traversal only after the watchdog has run.self.page.evaluate('__releaseBack()')self.page.locator('.reader-overlay').wait_for(state='detached')self.assertEqual(self.page.url, before['url'])self.assertEqual(self.page.evaluate('history.state'), before['state'])self.assertEqual(self.page.evaluate('STATE.results.map(getResultStableId)'), before['rows'])self.assertEqual(self.page.evaluate('document.activeElement.id'), 'search-input')self.assertEqual(self.page.locator('.reader-overlay-opening').count(), 0)self.page.evaluate('history.forward()')self.page.frame_locator('.reader-overlay').locator('body').wait_for()self.assertEqual(self.page.evaluate('({url:location.href,state:history.state,length:history.length})'), opened)self.assertEqual(self.page.evaluate('readerOverlay.src'), opened['state']['readerUrl'])self.assertFalse(self.page.evaluate('readerClosing'))self.assertEqual(self.page.locator('.reader-overlay-opening a').count(), 0)def test_watchdog_recovery_rejects_foreign_and_non_search_targets(self):self.page.evaluate('''() => {const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html');navigateToReader(path+'?ext=txt');}''')self.page.frame_locator('.reader-overlay').locator('body').wait_for()self.page.evaluate('''() => {history.back=()=>{};handleReaderMessage({origin:location.origin,source:readerOverlay.contentWindow,data:{type:'voice-reader-close'}});}''')recovery = self.page.get_by_role('link', name='直接打开搜索页')recovery.wait_for(state='visible', timeout=3000)safe = self.page.evaluate('new URL(new URL(readerOverlay.src).pathname.startsWith("/search/")?"/search/":"/",location.origin).href')for target in ('https://invalid.example/', 'javascript:alert(1)', '/static/reader.html', '/elsewhere/page', 'http://['):self.page.evaluate('target => readerNavigation.showCloseRecovery(target)', target)self.assertEqual(recovery.get_attribute('href'), safe)self.assertFalse(recovery.evaluate('link => !!link.closest("[inert]")'))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600"""Real Reader reload -> Back -> search DOM, focus/scroll and Forward.
Serve the repository's actual documents/modules. Only search API data and thetext book are synthetic; no replacement Reader shell or extra search reload.Both engines are required. Run through the task's namespace runner."""import contextlibimport functoolsimport http.serverfrom pathlib import Pathimport threadingimport timeimport unittestfrom urllib.parse import urlencode, urlsplit
from playwright.sync_api import sync_playwrightfrom tests.search.browser.test_paging_recovery import FETCH_SCRIPT
ROOT = Path(__file__).resolve().parents[3]PREFIX = "/search" if '/search/static/' in (ROOT / "static/reader.html").read_text() else ""TEXT = "Reader history forward content.\n" * 80SOURCE = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/history.txt"
@contextlib.contextmanagerdef source_server(): control = {"failures": set(), "failed_requests": [], "failure_seen": threading.Event()}
class Handler(http.server.SimpleHTTPRequestHandler): def translate_path(self, path): clean = urlsplit(path).path if PREFIX and clean.startswith(PREFIX + "/"): clean = clean[len(PREFIX):] # Production's SPA fallback serves known repository routes with # the search shell; static/API paths keep their own handlers. if (clean in ("/", "/index.html") or clean.strip('/').split('/')[0] in ('Teachers', 'VOMEBOOK')): clean = "/static/index.html" elif clean in ('/sw.js', '/manifest.json') or clean.startswith('/icons/'): clean = '/static' + clean return super().translate_path(clean)
def do_GET(self): path = urlsplit(self.path).path if path in control['failures']: control['failed_requests'].append(path) control['failure_seen'].set() self.send_error(503, 'Controlled cache fallback') return # SW install fetches bypass Playwright page routes. Supply only the # synthetic corpus manifests/data; production SW/assets stay intact. if path.startswith(PREFIX + '/data/') and path.endswith('.json'): body, content_type = b'{}', 'application/json' elif path.startswith(('/api/reader-content', '/api/reader-resource')): body, content_type = TEXT.encode(), 'text/plain; charset=utf-8' else: return super().do_GET() self.send_response(200) self.send_header('Content-Type', content_type) self.send_header('Content-Length', str(len(body))) self.end_headers() self.wfile.write(body)
def guess_type(self, path): if path.endswith((".mjs", ".js")): return "text/javascript" return super().guess_type(path)
def log_message(self, *_args): pass
server = http.server.ThreadingHTTPServer( ("127.0.0.1", 0), functools.partial(Handler, directory=str(ROOT))) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: yield f"http://127.0.0.1:{server.server_port}", control finally: server.shutdown() server.server_close() thread.join(timeout=5)
class ReaderReloadSearchDocumentCases: engine = None
@classmethod def setUpClass(cls): stack = contextlib.ExitStack() cls.addClassCleanup(stack.close) cls.origin, cls.server_control = stack.enter_context(source_server()) playwright = stack.enter_context(sync_playwright()) cls.browser = getattr(playwright, cls.engine).launch( headless=True, **({"args": ["--no-sandbox"]} if cls.engine == "chromium" else {})) stack.callback(cls.browser.close)
def setUp(self): self.server_control['failures'].clear() self.server_control['failed_requests'].clear() self.server_control['failure_seen'].clear() self.addCleanup(self.server_control['failures'].clear) self.context = self.browser.new_context( service_workers=('allow' if self._testMethodName == 'test_controlled_worker_cache_fallback_preserves_reader_back' else 'block'), viewport={"width": 1280, "height": 800}) self.addCleanup(self.context.close) self.page = self.context.new_page() self.page.set_default_timeout(5000) self.page.set_default_navigation_timeout(5000) self.page.add_init_script(FETCH_SCRIPT + """ // Hold a real app search consumer's response only on the return load. // Keep the synthetic API payload unchanged and deliberately ignore abort. if (window === window.top && sessionStorage.getItem('test-hold-return') && !location.pathname.endsWith('reader.html')) { sessionStorage.removeItem('test-hold-return'); const fetchSearch = window.fetch; window.fetch = (input, options) => { let body = {}; try { body = JSON.parse(options?.body || '{}'); } catch (_) {} const response = fetchSearch(input, options); if (String(input).includes('/api/search') && body.q === 'paging' && body.page === 1) { window.__returnHeld = true; return new Promise(resolve => { window.__releaseReturn = () => Promise.resolve(response).then(value => { window.__returnReleased = true; resolve(value); }); }); } return response; }; } """) # Observation only: capture the handoff before app startup consumes it, # and record whether the traversal was a real browser popstate. self.page.add_init_script("""(() => { if (window !== window.top) return; window.__arrivalHandoff = sessionStorage.getItem('reader-navigation-restore'); addEventListener('popstate', event => { sessionStorage.setItem('test-reader-popstate', JSON.stringify({ trusted: event.isTrusted, url: location.href })); }); })();""") self.page.route('**/api/**', lambda route: route.fulfill( content_type='application/json', body='[]' if route.request.url.endswith(('/repos', '/extensions')) else '{}')) self.page.route('https://vomebook-hitokoto.hf.space/**', lambda route: route.fulfill(body='{}')) for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE): self.page.route(pattern, lambda route: route.fulfill( content_type='text/plain; charset=utf-8', body=TEXT, headers={'Access-Control-Allow-Origin': '*'})) self.page.goto(self.search_url('paging'), wait_until='domcontentloaded') self.wait_search('paging')
def search_url(self, query): route = '/search/#/?' if PREFIX else '/?' return self.origin + route + urlencode({'q': query, **({'local': '0'} if PREFIX else {})})
def wait_search(self, query): self.page.locator('#search-input').wait_for(state='visible') self.page.wait_for_function('''query => typeof STATE !== 'undefined' && STATE.query === query && !STATE.isLoading && STATE.results.length >= 100''', arg=query) self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0) self.assertEqual(self.page.locator('.reader-text').count(), 0)
def open_and_reload(self): target = PREFIX + '/static/reader.html?' + urlencode({ 'ext': 'txt', 'url': SOURCE, 'title': 'History book'}) self.assertTrue(self.page.evaluate('target => navigateToReader(target)', target)) self.page.frame_locator('iframe.reader-overlay').locator('.reader-text').wait_for(state='visible') reader_url = self.page.url self.page.reload(wait_until='domcontentloaded') # The one user Reader reload. self.page.locator('.reader-text').wait_for(state='visible') self.assertIn('Reader history forward content.', self.page.locator('.reader-text').inner_text()) self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0) return reader_url
def test_back_restores_search_focus_scroll_and_forward_book(self): self.page.locator('#search-input').focus() before = self.page.evaluate('''async () => { history.replaceState({...history.state, foreign: {keep: 'search-entry'}}, '', location.href); DOM.searchInput.setSelectionRange(1, 4, 'backward'); setResultScrollTop(520); renderVisible(); await new Promise(resolve => requestAnimationFrame(resolve)); return {url: location.href, top: getResultScrollTop(), length: history.length}; }''') reader_url = self.open_and_reload() self.assertEqual(self.page.evaluate('history.length'), before['length'] + 1) self.page.go_back(wait_until='domcontentloaded') # There is deliberately no page.reload() here: product popstate must load search. self.wait_search('paging') self.assertEqual(self.page.url, before['url']) self.page.wait_for_function('''top => document.activeElement === DOM.searchInput && Math.abs(getResultScrollTop() - top) <= 2''', arg=before['top']) self.assertEqual(self.page.evaluate('history.state.foreign'), {'keep': 'search-entry'}) self.assertEqual(self.page.evaluate('history.length'), before['length'] + 1) self.assertEqual(self.page.evaluate('''[DOM.searchInput.selectionStart, DOM.searchInput.selectionEnd, DOM.searchInput.selectionDirection]'''), [1, 4, 'backward']) self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('test-reader-popstate'))"), {'trusted': True, 'url': before['url']}) self.page.go_forward(wait_until='domcontentloaded') self.assertEqual(self.page.url, reader_url) # Depending on document reuse, Forward can restore the standalone Reader # or the host overlay; both must render the actual book. self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible') content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text') if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text')) content.wait_for(state='visible') self.assertIn('Reader history forward content.', content.inner_text()) self.assertEqual(self.page.evaluate('history.length'), before['length'] + 1) self.page.go_back(wait_until='domcontentloaded') self.wait_search('paging') self.assertEqual(self.page.url, before['url'])
def test_back_then_forward_renders_book_without_consuming_forward_entry(self): search_url = self.page.url reader_url = self.open_and_reload() length = self.page.evaluate('history.length') self.page.go_back(wait_until='domcontentloaded') self.wait_search('paging') self.assertEqual(self.page.url, search_url) self.page.go_forward(wait_until='domcontentloaded') self.assertEqual(self.page.url, reader_url) self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible') content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text') if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text')) content.wait_for(state='visible') self.assertIn('Reader history forward content.', content.inner_text()) self.assertEqual(self.page.evaluate('history.length'), length)
def test_repo_search_reload_back_restores_dom_query_repo_and_forward_book(self): search_url = self.origin + '/Teachers?' + urlencode({'q': 'paging-repo'}) self.page.goto(search_url, wait_until='domcontentloaded') self.wait_search('paging-repo') self.assertEqual(self.page.evaluate('[STATE.mode, STATE.repo, STATE.repoFull]'), ['repo', 'Teachers', 'VoiceOfML/Teachers']) reader_url = self.open_and_reload() length = self.page.evaluate('history.length') self.page.go_back(wait_until='domcontentloaded') # Product popstate must load the repository's actual search document. self.wait_search('paging-repo') self.assertEqual(self.page.url, search_url) self.assertEqual(self.page.locator('#search-input').input_value(), 'paging-repo') self.assertEqual(self.page.evaluate('[STATE.mode, STATE.repo, STATE.repoFull]'), ['repo', 'Teachers', 'VoiceOfML/Teachers']) self.assertTrue(self.page.locator('.result-item').first.is_visible()) self.assertEqual(self.page.evaluate('JSON.parse(window.__arrivalHandoff).returnUrl'), search_url) self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('test-reader-popstate'))"), {'trusted': True, 'url': search_url}) self.assertEqual(self.page.evaluate('history.length'), length) self.page.go_forward(wait_until='domcontentloaded') self.assertEqual(self.page.url, reader_url) self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible') content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text') if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text')) content.wait_for(state='visible') self.assertIn('Reader history forward content.', content.inner_text()) self.assertEqual(self.page.evaluate('history.length'), length)
def test_two_step_back_loads_arrived_query_without_old_return_handoff(self): self.page.evaluate("history.replaceState({...history.state, foreign: 'older'}, '', location.href)") older_url = self.page.url # Search edits replace their current entry. Model a third-party-created # entry explicitly so go(-2) really lands on the older search document. self.page.evaluate("history.pushState({foreign: 'newer'}, '', location.href)") self.page.locator('#search-input').fill('paging-next') self.page.locator('#search-input').press('Enter') self.wait_search('paging-next') newer_url = self.page.url self.assertNotEqual(older_url, newer_url) self.open_and_reload() length = self.page.evaluate('history.length') self.page.evaluate('setTimeout(() => history.go(-2), 0)') self.wait_search('paging') self.assertEqual(self.page.url, older_url) self.assertEqual(self.page.evaluate('history.state.foreign'), 'older') self.assertIsNone(self.page.evaluate('window.__arrivalHandoff')) self.assertEqual(self.page.evaluate('history.length'), length) self.page.go_forward(wait_until='domcontentloaded') self.wait_search('paging-next') self.assertEqual(self.page.url, newer_url)
def test_missing_return_session_still_loads_actual_arrived_document(self): expected_url = self.page.url self.open_and_reload() self.page.evaluate("sessionStorage.removeItem('reader-navigation-current')") length = self.page.evaluate('history.length') self.page.go_back(wait_until='domcontentloaded') self.wait_search('paging') self.assertEqual(self.page.url, expected_url) self.assertIsNone(self.page.evaluate('window.__arrivalHandoff')) self.assertEqual(self.page.evaluate('history.length'), length)
def test_failed_reader_reload_back_restores_search_document(self): search_url = self.page.url target = PREFIX + '/static/reader.html?' + urlencode({ 'ext': 'txt', 'url': SOURCE, 'title': 'Failed history book'}) self.assertTrue(self.page.evaluate('target => navigateToReader(target)', target)) self.page.frame_locator('iframe.reader-overlay').locator('.reader-text').wait_for(state='visible') length = self.page.evaluate('history.length') # Fail the actual content transport on the user reload. Production # fail() cancels book work but leaves the Reader error document alive. for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE): self.page.route(pattern, lambda route: route.fulfill( status=404, content_type='text/plain', body='Book unavailable', headers={'Access-Control-Allow-Origin': '*'})) self.page.reload(wait_until='domcontentloaded') self.page.locator('.reader-error').wait_for(state='visible') self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0) self.assertEqual(self.page.locator('.reader-text').count(), 0) self.page.go_back(wait_until='domcontentloaded') # No fixture reload or direct fail() call: the error screen must keep # its real popstate listener until the document/runtime is disposed. self.page.locator('#search-input').wait_for(state='visible', timeout=5000) self.wait_search('paging') self.assertEqual(self.page.url, search_url) self.assertEqual(self.page.locator('.reader-error').count(), 0) self.assertEqual(self.page.evaluate('history.length'), length) self.assertEqual(self.page.evaluate("JSON.parse(sessionStorage.getItem('test-reader-popstate'))"), {'trusted': True, 'url': search_url})
def test_return_response_does_not_steal_new_user_focus(self): self.page.locator('#search-input').focus() # Stay at the top: scrolling saves a usable viewport preview, allowing # restoration to finish before the held validation response arrives. self.page.evaluate("DOM.searchInput.setSelectionRange(1, 4, 'backward')") self.open_and_reload() self.page.evaluate("sessionStorage.setItem('test-hold-return', '1')") self.page.go_back(wait_until='domcontentloaded') self.page.locator('#search-input').wait_for(state='visible') self.page.wait_for_function('window.__returnHeld === true && STATE.isLoading') self.assertIsNotNone(self.page.evaluate('window.__arrivalHandoff')) # Move focus with real keyboard input while keeping the route/view # unchanged: route invalidation must not hide a focus cancellation bug. search = self.page.locator('#search-input') search.click() search.press('Tab') self.assertEqual(self.page.evaluate('document.activeElement.id'), 'settings-btn') expected_url = self.page.url self.page.evaluate('window.__releaseReturn()') self.page.wait_for_function('window.__returnReleased === true') self.wait_search('paging') self.page.evaluate('''() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))''') self.assertEqual(search.input_value(), 'paging') self.assertEqual(self.page.url, expected_url) self.assertEqual(self.page.evaluate('STATE.query'), 'paging') self.assertEqual(self.page.evaluate('document.activeElement.id'), 'settings-btn') self.assertEqual(self.page.locator('iframe.reader-overlay').count(), 0)
def test_controlled_worker_cache_fallback_preserves_reader_back(self): self.page.wait_for_function('navigator.serviceWorker.controller !== null') controller = self.page.evaluate('navigator.serviceWorker.controller.scriptURL') self.assertEqual(controller, self.origin + PREFIX + '/sw.js') search_url = self.page.url self.page.locator('#search-input').click() search_length = self.page.evaluate('history.length') cdp = self.context.new_cdp_session(self.page) if self.engine == 'chromium' else None target = PREFIX + '/static/reader.html?' + urlencode({ 'ext': 'txt', 'url': SOURCE, 'title': 'Cached history book'}) self.assertTrue(self.page.evaluate('target => navigateToReader(target)', target)) self.page.frame_locator('iframe.reader-overlay').locator('.reader-text').wait_for(state='visible') reader_url = self.page.url # Chromium's renderer can report a stale history.length after the SW # controlled iframe opens. Inspect real entries, then verify standalone # length and traversal; never accept an extra entry from Reader reload. entries_before = cdp.send('Page.getNavigationHistory') if cdp else None if entries_before: self.assertEqual(len(entries_before['entries']), search_length + 1) self.assertEqual(entries_before['entries'][-2]['url'], search_url) self.assertEqual(entries_before['entries'][-1]['url'], reader_url) shell = PREFIX + '/static/reader.html' self.page.wait_for_function('''async shell => { const cached = await caches.match(shell); return !!cached && cached.ok && (await cached.text()).includes('reader.js'); }''', arg=shell) self.server_control['failures'].add(shell) responses = [] self.page.on('response', lambda response: responses.append(response) if urlsplit(response.url).path == shell else None) self.page.reload(wait_until='domcontentloaded') self.page.locator('.reader-text').wait_for(state='visible') length = self.page.evaluate('history.length') self.assertEqual(length, search_length + 1) if cdp: entries_after = cdp.send('Page.getNavigationHistory') self.assertEqual(entries_after['currentIndex'], entries_before['currentIndex']) self.assertEqual([(entry['id'], entry['url']) for entry in entries_after['entries']], [(entry['id'], entry['url']) for entry in entries_before['entries']]) self.assertTrue(any(response.status == 200 and response.from_service_worker for response in responses), 'Reader shell must come through the actual worker') # Worker cache-first still revalidates. Observe the server 503 as well as # the browser's cached 200, not merely an allow flag or CacheStorage key. self.assertTrue(self.page.evaluate('navigator.serviceWorker.controller !== null')) self.assertTrue(self.server_control['failure_seen'].wait(timeout=5), 'The worker must actually revalidate against the failing server') self.assertIn(shell, self.server_control['failed_requests']) self.page.go_back(wait_until='domcontentloaded') self.wait_search('paging') self.assertEqual(self.page.url, search_url) if PREFIX: self.assertEqual(self.page.evaluate('navigator.serviceWorker.controller.scriptURL'), controller) else: # Space intentionally bypasses search navigations. Firefox can load # that search document uncontrolled while registration stays active. active = self.page.evaluate('''async () => { const registration = await navigator.serviceWorker.getRegistration(); return registration?.active?.scriptURL; }''') self.assertEqual(active, controller) self.assertEqual(self.page.evaluate('history.length'), length) if cdp: arrived = cdp.send('Page.getNavigationHistory') self.assertEqual(arrived['currentIndex'], entries_before['currentIndex'] - 1) self.assertEqual([(entry['id'], entry['url']) for entry in arrived['entries']], [(entry['id'], entry['url']) for entry in entries_before['entries']]) self.page.go_forward(wait_until='domcontentloaded') self.assertEqual(self.page.url, reader_url) self.page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible') content = (self.page.frame_locator('iframe.reader-overlay').locator('.reader-text') if self.page.locator('iframe.reader-overlay').count() else self.page.locator('.reader-text')) content.wait_for(state='visible') self.assertIn('Reader history forward content.', content.inner_text()) # Forward may mount Reader in the uncontrolled Space search host. Check # the document rendering the book, not the parent host's controller. self.assertEqual(content.evaluate('() => navigator.serviceWorker.controller?.scriptURL'), controller) self.assertEqual(self.page.evaluate('history.length'), length)
def test_reader_hash_traversal_keeps_live_reader_document(self): reader_url = self.open_and_reload() self.page.evaluate("window.__sameReader = true; location.hash = 'chapter-test'") self.page.go_back(wait_until='domcontentloaded') self.assertEqual(self.page.url, reader_url) self.assertTrue(self.page.evaluate('window.__sameReader')) self.assertIn('Reader history forward content.', self.page.locator('.reader-text').inner_text())
class ReaderReloadSearchDocumentChromium(ReaderReloadSearchDocumentCases, unittest.TestCase): engine = 'chromium'
class ReaderReloadSearchDocumentFirefox(ReaderReloadSearchDocumentCases, unittest.TestCase): engine = 'firefox'
class ReaderTrueOfflineCases: """Space intentionally bypasses search navigations and API/book requests.
A fresh offline search document cannot load, even after an online visit. Assert that browser limitation explicitly, not fictitious offline search success or a blank product document. Recovery reloads search after the network returns, then follows the preserved Forward entry to the book. Pages covers native corpus recovery. """
setUpClass = classmethod(ReaderReloadSearchDocumentCases.setUpClass.__func__)
def test_true_offline_reader_reload_back_forward(self): from playwright.sync_api import Error as PlaywrightError
# A fresh context has neither FETCH_SCRIPT's fetch shim nor its forced # navigator.onLine value. Book bytes are synthetic only while online. context = self.browser.new_context(service_workers='allow') self.addCleanup(context.close) page = context.new_page() page.set_default_timeout(15000) page.set_default_navigation_timeout(15000) for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE): page.route(pattern, lambda route: route.fulfill( content_type='text/plain; charset=utf-8', body=TEXT, headers={'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store'})) responses, failed = [], [] page.on('response', lambda response: responses.append(response)) page.on('requestfailed', lambda request: failed.append(request)) search_url = self.origin + '/?q=offline-history' page.goto(search_url, wait_until='domcontentloaded') page.locator('#search-input').wait_for(state='visible') page.wait_for_function('navigator.serviceWorker.controller !== null') self.assertEqual(page.evaluate('navigator.serviceWorker.controller.scriptURL'), self.origin + '/sw.js') target = '/static/reader.html?' + urlencode({ 'ext': 'txt', 'url': SOURCE, 'title': 'Offline history book'}) self.assertTrue(page.evaluate('target => navigateToReader(target)', target)) content = page.frame_locator('iframe.reader-overlay').locator('.reader-text') content.wait_for(state='visible') self.assertIn('Reader history forward content.', content.inner_text()) reader_url = page.url # Await real SW persistence of loaded assets, never seed CacheStorage. assets = page.evaluate('''() => { const frame = document.querySelector('iframe.reader-overlay'); return [...new Set([performance, frame.contentWindow.performance].flatMap(p => p.getEntriesByType('resource').map(entry => entry.name)).filter(url => url.startsWith(location.origin + '/') && /\\.(?:m?js|css)(?:[?]|$)/.test(url)))]; }''') page.evaluate('''async urls => { await Promise.all(urls.map(async url => { const response = await fetch(url); if (!response.ok) throw Error('Warm failed: ' + url); await response.arrayBuffer(); })); }''', assets) page.wait_for_function('''async urls => (await Promise.all(urls.map(url => caches.match(url)))).every(r => r?.ok) ''', arg=['/static/reader.html', *assets]) self.assertFalse(page.evaluate('''async () => !!await caches.match('/')''')) page.unroute_all(behavior='wait') context.set_offline(True) failed.clear() response = page.reload(wait_until='domcontentloaded') self.assertEqual(response.status, 200) self.assertTrue(response.from_service_worker)
def assert_reader_error(): error = page.locator('.reader-error') error.wait_for(state='visible') # Current text transport exposes the browser error; Back remains # available. There is no text-book Retry control to invent here. self.assertRegex(error.inner_text(), 'Failed to fetch|NetworkError|网络|重试|下载') self.assertEqual(page.locator('.reader-text, iframe.reader-overlay').count(), 0) self.assertTrue(page.locator('#back').is_visible()) self.assertTrue(page.locator('#back').is_enabled()) self.assertFalse(page.evaluate('navigator.onLine'))
assert_reader_error() self.assertTrue(any('/api/reader-content' in request.url or request.url == SOURCE for request in failed), 'Book transport must actually fail offline') length = page.evaluate('history.length') responses.clear() # Require an actual failed document request: BFCache reuse alone cannot # establish the contract of the SW's deliberately uncached search shell. with page.expect_event('requestfailed', predicate=lambda request: request.is_navigation_request() and request.frame == page.main_frame and urlsplit(request.url).path == '/') as failure: try: page.go_back(wait_until='domcontentloaded') except PlaywrightError as error: self.assertRegex(str(error), 'ERR_INTERNET_DISCONNECTED|NS_ERROR_OFFLINE|NS_ERROR_NET_RESET') self.assertEqual(failure.value.url, search_url) self.assertTrue(failure.value.failure) self.assertFalse(any(response.request.is_navigation_request() and urlsplit(response.url).path == '/' and response.status == 200 for response in responses)) # requestfailed precedes the browser error document's commit. Wait for # that document to settle before touching history again; Chromium can # temporarily detach its page target during this transition. The error # document belongs to the browser, not to the search application. error_ready = False deadline = time.monotonic() + 5 while time.monotonic() < deadline: try: error_ready = page.evaluate('''() => !document.querySelector('#search-input, .reader-error, .reader-text') && (document.documentURI.startsWith('about:neterror?e=netOffline') || (document.readyState === 'complete' && document.documentURI.startsWith('chrome-error://')))''') except PlaywrightError: # The browser can replace the error document's execution context. error_ready = False if error_ready: break page.wait_for_timeout(50) self.assertTrue(error_ready, 'Expected the browser network error document') context.set_offline(False) # Restore the same online-only book fixture after reconnecting. No # route or fetch shim supplies any response during the offline phase. for pattern in ('**/api/reader-content**', '**/api/reader-resource**', SOURCE): page.route(pattern, lambda route: route.fulfill( content_type='text/plain; charset=utf-8', body=TEXT, headers={'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-store'})) # Retry the failed search entry in place. goto(search_url) would create # a new entry and discard Forward, hiding irreversible history loss. response = page.reload(wait_until='domcontentloaded') self.assertEqual(response.status, 200) self.assertEqual(page.url, search_url) page.locator('#search-input').wait_for(state='visible') page.wait_for_function('''typeof STATE !== 'undefined' && STATE.query === 'offline-history' ''') self.assertEqual(page.locator('.reader-error, .reader-text, iframe.reader-overlay').count(), 0) self.assertEqual(page.evaluate('history.length'), length) page.go_forward(wait_until='domcontentloaded') page.wait_for_url(reader_url, wait_until='domcontentloaded') page.locator('.reader-text, iframe.reader-overlay').wait_for(state='visible') document = (page.frame_locator('iframe.reader-overlay') if page.locator('iframe.reader-overlay').count() else page) content = document.locator('.reader-text') content.wait_for(state='visible') self.assertIn('Reader history forward content.', content.inner_text()) self.assertEqual(document.locator('.reader-error').count(), 0) self.assertEqual(page.url, reader_url) self.assertEqual(page.evaluate('history.length'), length)
class ReaderTrueOfflineChromium(ReaderTrueOfflineCases, unittest.TestCase): engine = 'chromium'
class ReaderTrueOfflineFirefox(ReaderTrueOfflineCases, unittest.TestCase): engine = 'firefox'367 unmodified lines368369370371372373374367 unmodified linesassert.ok(defaultReaderUrl.startsWith('/static/reader.html?'))assert.strictEqual(JSON.stringify(immutableRecord), immutableBefore)assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1)assertCode(reader, 'const previousList = document.querySelector("#toc-list")')assertCode(reader, 'previousList.cloneNode(false)')assertCode(reader, 'previousList.replaceWith(list)')assert.strictEqual((reader.match(/function activateFoliateTocEntry\(/g) || []).length, 1)367 unmodified lines368369370371372373374367 unmodified linesassert.ok(defaultReaderUrl.startsWith('/static/reader.html?'))assert.strictEqual(JSON.stringify(immutableRecord), immutableBefore)assert.strictEqual((reader.match(/function setToc\(/g) || []).length, 1)assertCode(reader, 'const previousList = /** @type {HTMLElement} */ (document.querySelector("#toc-list"))')assertCode(reader, 'previousList.cloneNode(false)')assertCode(reader, 'previousList.replaceWith(list)')assert.strictEqual((reader.match(/function activateFoliateTocEntry\(/g) || []).length, 1)
12341 unmodified line6789101126 unmodified lines383940414243441 unmodified line46474849505152"""Focused browser regressions for resumed and stalled result pagination."""import unittestfrom tests.support.real_server import get_shared_server1 unmodified lineFETCH_SCRIPT = r"""(() => {const nativeFetch = window.fetch.bind(window);window.pagingMode = 'stall';window.pagingTotal = 301;26 unmodified linesdef setUpClass(cls):cls.origin = get_shared_server().base_urlcls.playwright = sync_playwright().start()cls.browser = cls.playwright.chromium.launch(headless=True, args=['--no-sandbox'])@classmethoddef tearDownClass(cls):1 unmodified linecls.playwright.stop()def setUp(self):self.context = self.browser.new_context(viewport={'width': 1280, 'height': 800})self.page = self.context.new_page()self.errors = []self.page.on('pageerror', lambda error: self.errors.append(str(error)))123451 unmodified line78910111213141526 unmodified lines4243444546474849501 unmodified line52535455565758"""Focused browser regressions for resumed and stalled result pagination."""import osimport unittestfrom tests.support.real_server import get_shared_server1 unmodified lineFETCH_SCRIPT = r"""(() => {// This fixture serves an online API through fetch interception. A loopback-only// test namespace can report offline despite those responses being available.Object.defineProperty(navigator, 'onLine', {configurable: true, get: () => true});const nativeFetch = window.fetch.bind(window);window.pagingMode = 'stall';window.pagingTotal = 301;26 unmodified linesdef setUpClass(cls):cls.origin = get_shared_server().base_urlcls.playwright = sync_playwright().start()engine = os.environ.get('SEARCH_POSITION_BROWSER', 'chromium')cls.browser = getattr(cls.playwright, engine).launch(headless=True, **({'args': ['--no-sandbox']} if engine == 'chromium' else {}))@classmethoddef tearDownClass(cls):1 unmodified linecls.playwright.stop()def setUp(self):self.context = self.browser.new_context(service_workers='block', viewport={'width': 1280, 'height': 800})self.page = self.context.new_page()self.errors = []self.page.on('pageerror', lambda error: self.errors.append(str(error)))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321"""Session-only native IndexedDB regressions; select Chromium or Firefox explicitly."""import contextlibimport functoolsimport http.serverimport osfrom pathlib import Pathimport threadingimport unittest
from playwright.sync_api import sync_playwright
ROOT = Path(__file__).resolve().parents[3]
class SessionTransactionBrowserTests(unittest.TestCase): @classmethod def setUpClass(cls): stack = contextlib.ExitStack() cls.addClassCleanup(stack.close)
class Handler(http.server.SimpleHTTPRequestHandler): def log_message(self, *_args): pass
server = http.server.ThreadingHTTPServer( ('127.0.0.1', 0), functools.partial(Handler, directory=str(ROOT))) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() cls.addClassCleanup(lambda: (server.shutdown(), server.server_close(), thread.join(3))) cls.origin = f'http://127.0.0.1:{server.server_port}' playwright = stack.enter_context(sync_playwright()) engine = os.environ.get('SEARCH_SESSION_BROWSER', 'chromium') if engine not in ('chromium', 'firefox'): raise ValueError('SEARCH_SESSION_BROWSER must be chromium or firefox') cls.browser = getattr(playwright, engine).launch(headless=True) cls.addClassCleanup(cls.browser.close)
def setUp(self): self.context = self.browser.new_context(service_workers='block') self.addCleanup(self.context.close) self.context.route('**/*', lambda route: route.continue_() if route.request.url.startswith(self.origin + '/') else route.abort()) self.page = self.context.new_page() self.page.set_default_timeout(8000) errors = [] self.page.on('pageerror', lambda error: errors.append(str(error))) self.addCleanup(lambda: self.assertEqual(errors, [])) self.page.route('**/session-fixture*', lambda route: route.fulfill( content_type='text/html', body='<!doctype html><title>Session transaction</title>')) self.page.goto(self.origin + '/session-fixture?q=first') self.page.add_script_tag(url=self.origin + '/static/search/search-session.js') self.page.evaluate('''() => { window.session = VoiceOfMLSearchSession.createSearchSession({ canPersist: () => true, canRestore: target => !target || target.origin === location.origin }); window.until = async predicate => { const deadline = performance.now() + 5000; while (!predicate()) { if (performance.now() > deadline) throw new Error('session checkpoint timed out'); await new Promise(resolve => setTimeout(resolve, 5)); } }; window.readSaved = async () => { const db = await session.openSearchSessionDB(); try { const tx = db.transaction('session', 'readonly'); const get = tx.objectStore('session').get('last-search'); await new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onabort = () => reject(tx.error); }); return get.result; } finally { db.close(); } }; }''')
def test_delayed_open_captures_url_and_coalesces_the_latest_save(self): result = self.page.evaluate('''async () => { const open = indexedDB.open.bind(indexedDB), put = IDBObjectStore.prototype.put; let release, opens = 0; const writes = []; IDBObjectStore.prototype.put = function(value, ...args) { writes.push(value.url); return put.call(this, value, ...args); }; indexedDB.open = (...args) => { opens++; const request = open(...args); if (opens !== 1) return request; return new Proxy(request, { get: (target, key) => target[key], set(target, key, value) { target[key] = key === 'onsuccess' ? event => { release = () => value(event); } : value; return true; } }); }; try { const original = location.href; const first = session.persistSearchSession(); await until(() => !!release); history.replaceState(null, '', '?q=second'); const pending = session.persistSearchSession(); let shared = true; for (let i = 0; i < 2000; i++) { // Only the final URL matters to persistence; avoid browser history rate limits. shared = shared && session.persistSearchSession() === pending; } history.replaceState(null, '', '?q=latest'); shared = shared && session.persistSearchSession() === pending; const latest = location.href, beforeRelease = opens; release(); await Promise.all([first, pending]); const saved = await readSaved(); return {original, latest, beforeRelease, shared, writes, saved: saved.url}; } finally { indexedDB.open = open; IDBObjectStore.prototype.put = put; } }''') self.assertEqual(result['beforeRelease'], 1) self.assertTrue(result['shared']) self.assertEqual(result['writes'], [result['original'], result['latest']]) self.assertEqual(result['saved'], result['latest'])
def test_read_success_followed_by_native_abort_does_not_restore(self): result = self.page.evaluate('''async () => { await session.persistSearchSession(); history.replaceState({foreign: 7}, '', '?q=current'); const get = IDBObjectStore.prototype.get; let succeeded = false, aborted = false; IDBObjectStore.prototype.get = function(...args) { const request = get.apply(this, args), tx = this.transaction; request.addEventListener('success', () => { succeeded = true; tx.abort(); }); tx.addEventListener('abort', () => { aborted = true; }); return request; }; try { const restored = await session.restoreSearchSession(); await until(() => aborted); return {restored, succeeded, aborted, search: location.search, state: history.state}; } finally { IDBObjectStore.prototype.get = get; } }''') self.assertEqual(result, dict(restored=False, succeeded=True, aborted=True, search='?q=current', state={'foreign': 7}))
def test_restore_waits_for_native_completion_and_keeps_foreign_state(self): result = self.page.evaluate('''async () => { await session.persistSearchSession(); history.replaceState({foreign: ['keep', 42]}, '', '?q=current'); const transaction = IDBDatabase.prototype.transaction; let release, nativeComplete = false; IDBDatabase.prototype.transaction = function(...args) { const tx = transaction.apply(this, args); tx.addEventListener('complete', () => { nativeComplete = true; }); return new Proxy(tx, { get(target, key) { const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; }, set(target, key, value) { target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value; return true; } }); }; try { const pending = session.restoreSearchSession(); await until(() => !!release); const beforeRelease = location.search; release(); return {beforeRelease, nativeComplete, restored: await pending, search: location.search, state: history.state}; } finally { IDBDatabase.prototype.transaction = transaction; } }''') self.assertEqual(result, dict(beforeRelease='?q=current', nativeComplete=True, restored=True, search='?q=first', state={'foreign': ['keep', 42]}))
def test_pending_restore_cancels_on_observed_navigation_and_input(self): for action in ('href', 'popstate', 'hashchange', 'pagehide', 'input', 'compositionstart', 'compositionupdate', 'compositionend', 'entry', 'traversal'): with self.subTest(action=action): result = self.page.evaluate('''async action => { history.replaceState(null, '', '?q=saved'); await session.persistSearchSession(); history.replaceState({foreign:42}, '', '/session-fixture'); if (action === 'traversal') history.pushState(history.state, '', location.href); const transaction = IDBDatabase.prototype.transaction; let release; IDBDatabase.prototype.transaction = function(...args) { const tx = transaction.apply(this, args); return new Proxy(tx, { get(target, key) { const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; }, set(target, key, value) { target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value; return true; } }); }; try { const pending = session.restoreSearchSession(); await until(() => !!release); const hasKey = !!window.navigation?.currentEntry?.key; if (action === 'href') history.replaceState(history.state, '', '/session-fixture-other'); else if (action === 'traversal') { await new Promise(resolve => { window.addEventListener('popstate', resolve, {once:true}); history.back(); }); } else if (action === 'entry') { history.pushState(history.state, '', location.href); // Engines without entry keys rely on observable traversal. if (!hasKey) window.dispatchEvent(new PopStateEvent('popstate')); } else window.dispatchEvent(new Event(action)); const expected = location.href; release(); const restored = await pending; return {restored, unchanged:location.href === expected, state:history.state}; } finally { IDBDatabase.prototype.transaction = transaction; } }''', action) self.assertEqual(result, dict(restored=False, unchanged=True, state={'foreign': 42}))
def test_restore_cancellation_listeners_are_removed_after_every_attempt(self): result = self.page.evaluate('''async () => { await session.persistSearchSession(); const add = window.addEventListener, remove = window.removeEventListener; const live = new Map(); window.addEventListener = function(type, listener, options) { if (options === true) live.set(type, listener); return add.call(this, type, listener, options); }; window.removeEventListener = function(type, listener, options) { if (live.get(type) === listener) live.delete(type); return remove.call(this, type, listener, options); }; try { const first = await session.restoreSearchSession(); const afterSuccess = live.size; window.dispatchEvent(new Event('input')); const second = await session.restoreSearchSession(); const open = indexedDB.open; indexedDB.open = () => { throw new Error('unavailable'); }; let failed; try { failed = await session.restoreSearchSession(); } finally { indexedDB.open = open; } return {first, second, failed, afterSuccess, afterFailure:live.size}; } finally { window.addEventListener = add; window.removeEventListener = remove; } }''') self.assertEqual(result, dict(first=True, second=True, failed=False, afterSuccess=0, afterFailure=0))
def test_error_and_timeout_wait_for_native_abort_before_reopening(self): for failure in ('request-error', 'timeout'): with self.subTest(failure=failure): result = self.page.evaluate('''async failure => { await session.persistSearchSession(); const transaction = IDBDatabase.prototype.transaction; const open = indexedDB.open.bind(indexedDB); let opens = 0, captured = false, release, nativeAbort = false, opensAtAbort; indexedDB.open = (...args) => { opens++; return open(...args); }; IDBDatabase.prototype.transaction = function(...args) { const tx = transaction.apply(this, args); if (captured || tx.mode !== 'readwrite') return tx; captured = true; tx.addEventListener('abort', () => { nativeAbort = true; opensAtAbort = opens; }); const store = tx.objectStore('session'); if (failure === 'timeout') { // Keep a native transaction active until the adapter's real deadline aborts it. const keepAlive = () => { store.get('keep-alive').onsuccess = keepAlive; }; keepAlive(); } return new Proxy(tx, { get(target, key) { if (key === 'objectStore') return name => { const current = target.objectStore(name); if (failure === 'request-error') current.put = current.add.bind(current); return current; }; const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; }, set(target, key, value) { target[key] = key === 'onabort' ? event => { release = () => value(event); } : value; return true; } }); }; try { const first = session.persistSearchSession(); await until(() => captured); history.replaceState(null, '', '?q=' + failure); const next = session.persistSearchSession(); // Callers must settle while the adapter's native terminal // handler is still held. Releasing it first hides deadlocks. let deadline; const callersSettledBeforeRelease = await Promise.race([ Promise.all([first, next]).then(() => true), new Promise(resolve => { deadline = setTimeout(() => resolve(false), 3000); }) ]).finally(() => clearTimeout(deadline)); if (!callersSettledBeforeRelease) { throw new Error('save callers did not settle within 3s while abort delivery was held'); } await until(() => !!release); const opensBeforeRelease = opens; if (opensBeforeRelease !== 1) { throw new Error('write queue reopened before held abort delivery'); } release(); await until(() => opens === 2); const saved = await readSaved(); return {nativeAbort, opensAtAbort, opensBeforeRelease, callersSettledBeforeRelease, saved: new URL(saved.url).search}; } finally { indexedDB.open = open; IDBDatabase.prototype.transaction = transaction; } }''', failure) self.assertEqual(result, dict(nativeAbort=True, opensAtAbort=1, opensBeforeRelease=1, callersSettledBeforeRelease=True, saved='?q=' + failure))
if __name__ == '__main__': unittest.main()123455 unmodified lines111213141516171 unmodified line19202122232425261 unmodified line282930313233343536373839404142// Synthetic contracts for the existing search-host navigation module. These// cover URL and session behavior, not iframe, speech, or whole-file coverage.import assert from 'node:assert/strict';import fs from 'node:fs';import path from 'node:path';5 unmodified linesconst origin = 'https://search.example';const readerPath = '/search/static/reader.html';function fixture() {const data = new Map();const calls = [];const storage = {1 unmodified linesetItem(key, value) { data.set(key, String(value)); },removeItem(key) { data.delete(key); }};const root = {addEventListener() {}};const document = {readyState: 'loading', addEventListener() {}};const crypto = {randomUUID: () => 'fixed-token'};const history = {pushState(...args) { calls.push(['push', ...args]); },1 unmodified line};// Supply location and storage through the global as in browsers. Unrelated// DOM and asynchronous Reader services remain intentionally unstubbed.const context = vm.createContext({self: root, document, sessionStorage: storage,localStorage: storage, location: new URL(origin + '/search/#/'), URL, URLSearchParams,crypto, history, console});vm.runInContext(source, context, {filename});return {nav: root.VoiceOfMLReaderNavigation.createNavigation(readerPath), data, storage, crypto, calls, context};}const json = value => JSON.parse(JSON.stringify(value));test('parse accepts only the same-origin reader pathname', () => {const {nav} = fixture();assert.equal(nav.parse(readerPath + '?title=a%20b#part').href,1234565 unmodified lines121314151617181 unmodified line202122232425261 unmodified line282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208// Synthetic contracts for the existing search-host navigation module. These// cover URL/session rules and DOM ownership with a synthetic shell. Real browser// traversal, layout, speech and native navigation remain browser-test contracts.import assert from 'node:assert/strict';import fs from 'node:fs';import path from 'node:path';5 unmodified linesconst origin = 'https://search.example';const readerPath = '/search/static/reader.html';function fixture(readerDestination = readerPath, document = {readyState: 'loading', addEventListener() {}}) {const data = new Map();const calls = [];const storage = {1 unmodified linesetItem(key, value) { data.set(key, String(value)); },removeItem(key) { data.delete(key); }};const root = new EventTarget();const crypto = {randomUUID: () => 'fixed-token'};const history = {pushState(...args) { calls.push(['push', ...args]); },1 unmodified line};// Supply location and storage through the global as in browsers. Unrelated// DOM and asynchronous Reader services remain intentionally unstubbed.const context = vm.createContext({self: root, window: root, document, sessionStorage: storage,localStorage: storage, location: new URL(origin + '/search/#/'), URL, URLSearchParams,crypto, history, console, HTMLElement: ShellElement, Event});vm.runInContext(source, context, {filename});return {nav: root.VoiceOfMLReaderNavigation.createNavigation(readerDestination), data, storage, crypto, calls, context};}const json = value => JSON.parse(JSON.stringify(value));// Deliberately small DOM double: events run synchronously so dispose reentry is// observable. It does not simulate layout, iframe loading or browser history.class ShellElement extends EventTarget {constructor(document, tagName) {super();this.document = document;this.tagName = tagName;this.children = [];this.attributes = new Map();this.styles = new Map();this.style = {setProperty: (key, value) => this.styles.set(key, value),removeProperty: key => this.styles.delete(key)};const classes = new Set();this.classList = {add: value => classes.add(value), remove: value => classes.delete(value),contains: value => classes.has(value)};if (tagName === 'iframe') {this.contentWindow = new EventTarget();this.contentWindow.postMessage = () => {};this.contentDocument = {title: 'VoiceOfML Reader', URL: 'about:blank'};}}append(...children) {for (const child of children) { child.parent = this; this.children.push(child); }}replaceChildren(...children) {for (const child of [...this.children]) child.remove();this.append(...children);}remove() {if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);this.parent = null;}focus() { this.document.activeElement = this; }setAttribute(key, value) { this.attributes.set(key, value); }getAttribute(key) { return this.attributes.get(key) ?? null; }hasAttribute(key) { return this.attributes.has(key); }removeAttribute(key) { this.attributes.delete(key); }}function shellFixture(destination = readerPath) {const document = {readyState: 'loading', title: 'Search', addEventListener() {}};document.createElement = tag => new ShellElement(document, tag);document.body = document.createElement('body');const input = document.createElement('input');document.body.append(input);input.focus();const state = fixture(destination, document);return {...state, document, input,shell: () => document.body.children.find(child => child.className === 'reader-overlay-opening')};}test('replacement revision preserves a Reader opened synchronously during disposal', () => {const {nav, document, input} = shellFixture();const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));assert.equal(nav.returnFocus, input);assert.equal(nav.backgroundReader, null);let newest;first.contentWindow.addEventListener('voice-reader-dispose', () => {newest = nav.mount(new URL(origin + readerPath + '?id=newest'));});const result = nav.replace(readerPath + '?id=stale', {top: 50});assert.equal(result, newest, 'outer replacement must yield to the reentrant mount');assert.equal(first.parent, null);assert.equal(first.src, 'about:blank');assert.equal(document.body.children.filter(child => child.tagName === 'iframe').length, 1);assert.equal(nav.accepts({origin, source: newest.contentWindow}), true);assert.equal(nav.accepts({origin: 'https://other.example', source: newest.contentWindow}), false);assert.equal(nav.accepts({origin, source: {frameElement: newest}}), true);assert.equal(nav.accepts({origin, source: null}), false);assert.equal(nav.accepts({origin, source: {get frameElement() { throw new Error('cross-origin'); }}}), false);assert.equal(nav.accepts({origin, source: first.contentWindow}), false);nav.unmount(false);assert.equal(nav.returnFocus, null);assert.equal(nav.unmount(), null);});test('ordinary replacement carries handoff and focus while releasing background ownership', () => {const {nav, document, input, data} = shellFixture();const hidden = document.createElement('aside');hidden.setAttribute('inert', '');hidden.setAttribute('aria-hidden', 'false');document.body.append(hidden);const first = nav.mount(new URL(origin + readerPath + '?id=first&nav=token&return=%2Fsearch%2F'));const next = nav.replace(readerPath + '?id=next', {top: 50});assert.notEqual(next, first);assert.equal(new URL(next.src).searchParams.get('nav'), 'token');assert.equal(new URL(next.src).searchParams.get('return'), '/search/');assert.equal(JSON.parse(data.get('reader-navigation-current')).readerUrl, next.src);assert.equal(nav.returnFocus, input);assert.equal(nav.unmount(false), input);assert.equal(input.hasAttribute('inert'), false);assert.equal(input.hasAttribute('aria-hidden'), false);assert.equal(hidden.hasAttribute('inert'), true);assert.equal(hidden.getAttribute('aria-hidden'), 'false');});test('close recovery validates both search routes without changing history or private handoff', () => {for (const destination of [readerPath, '/static/reader.html']) {const {nav, document, input, shell, data, calls} = shellFixture(destination);const search = destination === readerPath ? '/search/' : '/';nav.showCloseRecovery(search);assert.equal(shell(), undefined, 'no recovery without an active Reader');const url = nav.prepare(destination + '?id=book&title=Book', origin + search);nav.mount(url);nav.remember(url, {top: 50});const saved = data.get('reader-navigation-current');nav.showCloseRecovery(search);assert.equal(shell().children.some(child => child.tagName === 'a'), false, 'no recovery before close');nav.dismiss();assert.equal(document.title, 'Search');const valid = destination === readerPath ? '/search/#/Repo?q=book' : '/Repo?q=book';for (const [raw, expected] of [[valid, valid], ['https://other.example/', search], ['javascript:alert(1)', search],['/static/reader.html', search], ['/elsewhere/page', search], ['http://[', search],['https://user:password@search.example' + search, search]]) {nav.showCloseRecovery(raw);const link = shell().children.find(child => child.tagName === 'a');assert.equal(link.href, origin + expected);assert.equal(shell().parent, document.body);assert.equal(shell().hasAttribute('inert'), false);assert.equal(shell().styles.has('opacity'), false);assert.equal(shell().styles.has('pointer-events'), false);assert.equal(document.activeElement, link);assert.equal(input.hasAttribute('inert'), true);}assert.equal(calls.length, 1, 'recovery must not push or replace history');assert.equal(data.get('reader-navigation-current'), saved);assert.equal(data.has('reader-navigation-restore'), false, 'handoff waits for explicit activation');assert.equal(nav.returnFocus, input);nav.unmount(false);assert.equal(shell(), undefined);}});test('recovery survives late shell load and records handoff only on native link activation', () => {const {nav, document, shell, data, calls, storage} = shellFixture();const target = origin + '/search/#/?q=book';const url = nav.prepare(readerPath + '?id=book', target);const frame = nav.mount(url);frame.contentDocument.URL = frame.src;frame.dispatchEvent(new Event('load'));assert.equal(shell(), undefined);nav.dismiss();nav.showCloseRecovery(target);const recovery = shell();const link = recovery.children.find(child => child.tagName === 'a');frame.dispatchEvent(new Event('load'));assert.equal(shell(), recovery);assert.equal(document.activeElement, link);const click = new Event('click', {cancelable: true});link.dispatchEvent(click);assert.equal(click.defaultPrevented, false, 'native href remains the navigation action');assert.deepEqual(JSON.parse(data.get('reader-navigation-restore')), {readerUrl: url.href, returnUrl: target});storage.setItem = () => { throw new Error('quota'); };assert.doesNotThrow(() => link.dispatchEvent(new Event('click')));assert.deepEqual(calls, []);assert.equal(nav.unmount(false).tagName, 'input');nav.showCloseRecovery(target);assert.equal(shell(), undefined);});test('parse accepts only the same-origin reader pathname', () => {const {nav} = fixture();assert.equal(nav.parse(readerPath + '?title=a%20b#part').href,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201// Focused host contracts. Browser traversal and DOM ownership are covered in// test_reader_navigation_host.py; these isolate synchronous abort/input edges.import assert from 'node:assert/strict';import fs from 'node:fs';import vm from 'node:vm';import test from 'node:test';
const source = fs.readFileSync('static/app.js', 'utf8');function fixture(names, values = {}) { const context = vm.createContext({AbortController, ...values}); for (const name of names) { const match = source.match(new RegExp('^function ' + name + '\\([^]*?^}', 'm')); assert.ok(match, name); vm.runInContext(match[0], context); } return context;}
test('reader handoff waits for usable target rows but not preview validation of adjacent pages', () => { const saved = {viewKey:'B',index:1}; const c = fixture(['readerSearchHandoffReady'], {STATE:{isLoading:true,_loadedPage:0,total:3,results:[]},positionRestore:null}); assert.equal(c.readerSearchHandoffReady(saved), false); c.STATE = {isLoading:false,_loadedPage:1,total:3,results:[{},{}]}; c.positionRestore = {key:'B',preview:false}; assert.equal(c.readerSearchHandoffReady(saved), false); c.positionRestore.preview = true; assert.equal(c.readerSearchHandoffReady(saved), true); assert.equal(c.positionRestore.preview, true, 'validation remains owned and active'); c.positionRestore.key = 'A'; assert.equal(c.readerSearchHandoffReady(saved), false); c.positionRestore.key = 'B'; delete c.STATE.results[1]; assert.equal(c.readerSearchHandoffReady(saved), false, 'sparse geometry alone is not a usable target'); c.positionRestore = null; c.STATE.results[1] = {}; assert.equal(c.readerSearchHandoffReady(saved), true);});
test('sort normalization uses the real backend whitelist, including empty and unknown URL values', () => { const c = fixture(['normalizeSearchSort']); for (const input of ['', null, undefined, 'custom', 'NAME', ' relevance ']) assert.equal(c.normalizeSearchSort(input), 'relevance'); for (const input of ['relevance', 'name', 'size']) assert.equal(c.normalizeSearchSort(input), input);});
test('abort synchronously starting another search retains its controller and retires the outer owner', () => { const old = new AbortController(); const c = fixture(['cancelActiveSearch'], {searchId: 4, searchRequestId: 8, searchAbortController: old, cancelSearchPrefetch() {}}); let newer; old.signal.addEventListener('abort', () => { assert.equal(c.searchId, 5); assert.equal(c.searchRequestId, 9); assert.notEqual(c.searchAbortController, old); assert.equal(c.cancelActiveSearch(), true); newer = c.searchAbortController; }); assert.equal(c.cancelActiveSearch(), false); assert.equal(c.searchAbortController, newer); assert.equal(newer.signal.aborted, false);});
test('prefetch abort reentry cannot clear the replacement group', () => { const old = new AbortController(), newer = new AbortController(); const c = fixture(['cancelSearchPrefetch'], {searchPrefetchAbortController: old, cancelPendingSearchCacheWrites() {}}); old.signal.addEventListener('abort', () => { c.searchPrefetchAbortController = newer; }); c.cancelSearchPrefetch(); assert.equal(c.searchPrefetchAbortController, newer);});
test('online first page prefetch starts pages two and three and path-only reuses the group', () => { const requests = []; const c = fixture(['prefetchSearchPages'], {searchPrefetchAbortController:null, STATE:{_loadedPage:1,total:301,pageSize:100,_pageCache:{},results:[{}]}, document:{hidden:false},navigator:{onLine:true},searchPageMetadata:new WeakMap(), getSearchViewKey:() => 'same-view',stableSearchStringify:JSON.stringify, getCachedSearchResponse:() => null, fetchSearchPage(key, base, body, signal) { requests.push({page:body.page,signal}); return new Promise(() => {}); }, APPEND_REQUEST_TIMEOUT:10000}); c.prefetchSearchPages('/api/search',{q:'paging',page:1,page_size:100}); assert.deepEqual(requests.map(r => r.page), [2,3]); const group = c.searchPrefetchAbortController; c.STATE.browserPath = 'path-only'; c.prefetchSearchPages('/api/search',{q:'paging',page:1,page_size:100}); assert.equal(c.searchPrefetchAbortController, group); assert.equal(requests.length, 2); assert.equal(group.signal.aborted, false);});
test('position abort reentry retains the replacement window and restoration', () => { const old = new AbortController(), newer = {controller: new AbortController()}; const c = fixture(['cancelPositionRestore'], {positionEntryId: 0, resultWindow: {controller: old}, positionRestore: {controller: new AbortController()}, STATE: {isLoading: true}, cancelSnapshotClone() {}, updateResultWindowStatus() {}, showPositionRestoreStatus() {}}); old.signal.addEventListener('abort', () => { c.resultWindow = newer; c.positionRestore = newer; }); c.cancelPositionRestore(); assert.equal(c.resultWindow, newer); assert.equal(c.positionRestore, newer); assert.equal(newer.controller.signal.aborted, false);});
test('filter change incorporates the pending completed query before cancelling debounce', () => { const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: false, DOM: {searchInput: {value: ' current draft '}}, STATE: {query: 'old', page: 3, results: [1]}, applyPendingSizeFilters() {}, cancelPendingSearchControls() { c.searchTimer = null; }, saveSearchViewSnapshot() { assert.equal(c.STATE.query, 'old'); }}); c.prepareFilterChange(true); assert.equal(c.STATE.query, 'current draft'); assert.equal(c.STATE.page, 1); assert.equal(c.STATE.results.length, 0);});
test('filter change preserves composing and overlong drafts without submitting them', () => { for (const [composing, value] of [[true, 'composition'], [false, 'x'.repeat(257)]]) { const c = fixture(['prepareFilterChange'], {searchTimer: 1, searchComposing: composing, DOM: {searchInput: {value}}, STATE: {query: 'old'}, applyPendingSizeFilters() {}, cancelPendingSearchControls() {}, saveSearchViewSnapshot() {}}); c.prepareFilterChange(false); assert.equal(c.STATE.query, 'old'); assert.equal(c.DOM.searchInput.value, value); }});
test('composition completion checks both visit generation and search view ownership', () => { for (const change of ['generation', 'view', 'neither']) { const handlers = new Map(); let scheduled = 0, key = 'A'; const c = fixture(['setupSearchInput'], { DOM: {searchInput: {addEventListener(type, handler) { handlers.set(type, handler); }}}, searchInputReady: true, initialSearchDraft: false, searchTimer: null, searchComposing: false, searchInputGeneration: 0, searchCompositionGeneration: 0, searchCompositionViewKey: null, routeInitialized: true, getSearchViewKey: () => key, clearTimeout() {}, syncSearchInputState() {}, window: {addEventListener() {}}, cancelInitialSearchDraft() {}, captureInitialSearchDraft() {}, debouncedSearch() { scheduled++; } }); c.setupSearchInput(); handlers.get('compositionstart')(); if (change === 'generation') c.searchInputGeneration++; if (change === 'view') key = 'B'; handlers.get('compositionend')(); assert.equal(c.searchComposing, false); assert.equal(scheduled, change === 'neither' ? 1 : 0, change); const before = scheduled; handlers.get('input')({isComposing: false, inputType: 'insertCompositionText'}); assert.equal(scheduled, before); handlers.get('input')({isComposing: false, inputType: 'insertText'}); assert.equal(scheduled, before + 1, 'a deliberate edit remains usable'); }});
test('startup drafts require their original URL, entry and uninterrupted visit', () => { for (const change of ['href', 'entry', 'event', 'none']) { let key = 'entry-A', submits = 0; const c = fixture(['captureInitialSearchDraft', 'cancelInitialSearchDraft', 'initialSearchDraftIsCurrent', 'finishInitialSearchInput'], { location: {href: 'https://example.test/A'}, currentSearchEntryKey: () => key, initialSearchDraftOwner: null, initialSearchDraft: false, searchInputReady: false, searchInputGeneration: 0, window: {removeEventListener() {}}, debouncedSearch() { submits++; } }); c.captureInitialSearchDraft(); if (change === 'href') c.location.href = 'https://example.test/B'; if (change === 'entry') key = 'entry-B'; if (change === 'event') c.cancelInitialSearchDraft(); c.finishInitialSearchInput(c.initialSearchDraftIsCurrent()); assert.equal(submits, change === 'none' ? 1 : 0, change); assert.equal(c.searchInputGeneration, change === 'none' ? 0 : 1, change); assert.equal(c.searchInputReady, true); assert.equal(c.initialSearchDraftOwner, null); }});
test('a queued debounce cannot submit after its search view changes', () => { let callback, submits = 0; const c = fixture(['debouncedSearch'], {searchTimer: null, searchComposing: false, searchInputReady: true, searchInputGeneration: 0, DOM: {searchInput: {value: 'old draft'}}, clearTimeout() {}, setTimeout(fn) { callback = fn; return 1; }, submitSearchQuery() { submits++; }}); c.debouncedSearch(); c.searchInputGeneration++; callback(); assert.equal(submits, 0); c.debouncedSearch(); callback(); assert.equal(submits, 1);});
test('a queued debounce cannot submit after composition starts', () => { let callback, submits = 0; const c = fixture(['debouncedSearch'], {searchTimer: null, searchComposing: false, searchInputReady: true, searchInputGeneration: 0, DOM: {searchInput: {value: 'intermediate'}}, clearTimeout() {}, setTimeout(fn) { callback = fn; return 1; }, submitSearchQuery() { submits++; }}); c.debouncedSearch(); c.searchComposing = true; callback(); assert.equal(submits, 0); assert.equal(c.searchTimer, null);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378const assert = require('node:assert/strict');const fs = require('node:fs');const path = require('node:path');const test = require('node:test');const vm = require('node:vm');const {IDBFactory} = require('fake-indexeddb');
const filename = path.join(__dirname, '../../../static/search/search-session.js');const source = fs.readFileSync(filename, 'utf8');const turn = () => new Promise(resolve => setImmediate(resolve));async function until(predicate) { for (let i = 0; i < 200; i++) { if (predicate()) return; await turn(); } assert.fail('IndexedDB checkpoint was not reached');}
function fixture() { const factory = new IDBFactory(); const timers = new Map(); let nextTimer = 0; const h = {opens: 0, closes: 0, writes: [], terminals: [], openHook: null, transactionHook: null, openError: null}; const location = {href: 'https://example.test/search/?q=first'}; const history = { state: {foreign: {value: 7}}, replacements: [], replaceState(state, title, url) { this.state = state; this.replacements.push(url); location.href = url; } }; const indexedDB = { open(...args) { h.opens++; if (h.openError) throw h.openError; const request = factory.open(...args); request.addEventListener('success', () => { const db = request.result; const close = db.close.bind(db); db.close = () => { h.closes++; close(); }; const transaction = db.transaction.bind(db); db.transaction = (...txArgs) => { const tx = transaction(...txArgs); tx.addEventListener('complete', () => h.terminals.push('complete')); tx.addEventListener('abort', () => h.terminals.push('abort')); if (tx.mode === 'readwrite') { const objectStore = tx.objectStore.bind(tx); const instrumented = new WeakSet(); tx.objectStore = name => { const store = objectStore(name); if (!instrumented.has(store)) { instrumented.add(store); const put = store.put.bind(store); store.put = (value, key) => { h.writes.push(value.url); return put(value, key); }; } return store; }; } return h.transactionHook ? h.transactionHook(tx) : tx; }; }); return h.openHook ? h.openHook(request) : request; } }; const context = vm.createContext({ indexedDB, window: Object.assign(new EventTarget(), {indexedDB}), location, history, URL, setTimeout(callback) { const id = ++nextTimer; timers.set(id, callback); return id; }, clearTimeout(id) { timers.delete(id); } }); vm.runInContext(source, context, {filename}); h.create = (options = {}) => context.VoiceOfMLSearchSession.createSearchSession({ canPersist: () => true, canRestore: () => true, ...options }); h.session = h.create(); h.location = location; h.history = history; h.timers = timers; h.expire = () => { for (const [id, callback] of [...timers]) { if (timers.delete(id)) callback(); } }; h.saved = async () => { const request = factory.open('voiceofml-search-state', 1); const db = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); }); try { const tx = db.transaction('session', 'readonly'); const get = tx.objectStore('session').get('last-search'); await new Promise((resolve, reject) => { tx.oncomplete = resolve; tx.onabort = () => reject(tx.error); }); return get.result; } finally { db.close(); } }; return h;}
// Delay delivery, not the fake IndexedDB backend: inspect final committed data too.function holdOpen(h) { let release; h.openHook = request => new Proxy(request, { set(target, key, value) { if (key === 'onsuccess') target.onsuccess = event => { release = () => value(event); }; else target[key] = value; return true; }, get(target, key) { return target[key]; } }); return {ready: () => !!release, release: () => { h.openHook = null; release(); }};}
function holdTerminal(h, {abortThrows = false, failPut = false, requestError = false, preventError = false} = {}) { let release; let captured = false; let aborts = 0; h.transactionHook = tx => { if (captured || tx.mode !== 'readwrite') return tx; captured = true; let requestErrorEvent; tx.addEventListener('error', event => { requestErrorEvent = event; if (preventError) event.preventDefault(); }); return new Proxy(tx, { set(target, key, value) { if (key === 'oncomplete' || key === 'onabort') { target[key] = event => { release = () => value(event); }; } else target[key] = value; return true; }, get(target, key) { if (key === 'abort') return () => { aborts++; if (abortThrows) throw new Error('injected abort failure'); target.abort(); // fake-indexeddb 6.2.7 repeats the default abort even when an error // listener already aborted the transaction, then removes it twice. // Suppress only that redundant default after a successful explicit // abort; still require the real abort event and committed-data checks. requestErrorEvent?.preventDefault(); }; if (key === 'objectStore') return name => { const store = target.objectStore(name); if (failPut) store.put = () => { throw new Error('injected synchronous put failure'); }; if (requestError) store.put = (value, entry) => store.add(value, entry); return store; }; const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; } }); }; return {ready: () => !!release, release: () => release(), aborts: () => aborts};}
const options = {timeout: 5000};
test('save captures its URL before the database opens', options, async () => { const h = fixture(), held = holdOpen(h); const before = h.location.href; const pending = h.session.persistSearchSession(); await until(held.ready); h.location.href = 'https://example.test/reader/?book=next'; held.release(); await pending; assert.equal((await h.saved()).url, before); assert.deepEqual(h.writes, [before]);});
test('delayed open serializes adapters and coalesces pending saves to the newest URL', options, async () => { const h = fixture(), held = holdOpen(h); const first = h.session.persistSearchSession(); await until(held.ready); const other = h.create(); h.location.href = 'https://example.test/search/?q=second'; const pending = other.persistSearchSession(); for (let i = 0; i < 2000; i++) { h.location.href = `https://example.test/search/?q=${i}`; assert.equal(h.session.persistSearchSession(), pending, 'one shared pending promise'); } assert.equal(h.opens, 1); const latest = h.location.href; held.release(); await Promise.all([first, pending]); assert.equal((await h.saved()).url, latest); assert.deepEqual(h.writes, ['https://example.test/search/?q=first', latest]);});
test('timed out opens stay bounded, close late connections and resume only after native success', options, async () => { const h = fixture(), held = holdOpen(h); const first = h.session.persistSearchSession(); await until(held.ready); h.expire(); await first; h.location.href = 'https://example.test/search/?q=latest'; const pending = h.session.persistSearchSession(); h.expire(); await pending; for (let i = 0; i < 2000; i++) assert.equal(h.session.persistSearchSession(), pending); assert.equal(h.opens, 1); assert.equal(h.timers.size, 0); assert.deepEqual(h.writes, []); held.release(); await until(() => h.writes.length === 1 && h.terminals.length === 1); assert.equal((await h.saved()).url, h.location.href); assert.equal(h.closes, 2, 'late abandoned connection and successful writer both close');});
for (const fault of [ {name: 'timeout with throwing abort', abortThrows: true}, {name: 'synchronous put failure', failPut: true}, {name: 'request error', requestError: true}, {name: 'cancelled request error with throwing abort', requestError: true, abortThrows: true, preventError: true}]) { test(`${fault.name} cannot release a writer before native complete or abort delivery`, options, async () => { const h = fixture(); if (fault.requestError) await h.session.persistSearchSession(); const opens = h.opens; const held = holdTerminal(h, fault); const first = h.session.persistSearchSession(); await until(held.ready); h.location.href = 'https://example.test/search/?q=newer'; const pending = h.session.persistSearchSession(); h.expire(); await Promise.all([first, pending]); assert.equal(held.aborts(), 1); for (let i = 0; i < 2000; i++) assert.equal(h.session.persistSearchSession(), pending); assert.equal(h.opens, opens + 1, 'no replacement open before terminal delivery'); assert.equal(h.timers.size, 0, 'stalled worker retains no growing timeout list'); const terminalCount = h.terminals.length; held.release(); await until(() => h.terminals.length > terminalCount); assert.equal((await h.saved()).url, h.location.href); });}
test('timeout abort returning is not native abort completion', options, async t => { const h = fixture(); let release; let aborts = 0; let heldTransaction; t.after(() => { // A failed checkpoint must not leave the emulator's keep-alive loop running. try { heldTransaction?.abort(); } catch (_) {} }); h.transactionHook = tx => { h.transactionHook = null; heldTransaction = tx; // Hold a real transaction live with successive requests until abort(). const store = tx.objectStore('session'); function keepAlive() { store.get('keep-alive').onsuccess = keepAlive; } keepAlive(); return new Proxy(tx, { set(target, key, value) { target[key] = key === 'onabort' ? event => { release = () => value(event); } : value; return true; }, get(target, key) { if (key === 'abort') return () => { aborts++; target.abort(); }; const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; } }); }; const first = h.session.persistSearchSession(); await until(() => h.writes.length === 1); h.location.href = 'https://example.test/search/?q=after-abort'; const pending = h.session.persistSearchSession(); h.expire(); await Promise.all([first, pending]); assert.equal(aborts, 1); assert.equal(h.opens, 1); await until(() => !!release); assert.equal(h.opens, 1); release(); await until(() => h.writes.length === 2 && h.terminals.includes('complete')); assert.equal((await h.saved()).url, h.location.href);});
test('read success followed by abort never restores a provisional URL', options, async () => { const h = fixture(); await h.session.persistSearchSession(); h.location.href = 'https://example.test/search/'; h.transactionHook = tx => { const objectStore = tx.objectStore.bind(tx); tx.objectStore = name => { const store = objectStore(name), get = store.get.bind(store); store.get = key => { const request = get(key); request.addEventListener('success', () => tx.abort()); return request; }; return store; }; return tx; }; assert.equal(await h.session.restoreSearchSession(), false); assert.deepEqual(h.history.replacements, []); assert.equal(h.location.href, 'https://example.test/search/');});
test('restore waits for completion, rechecks policy and preserves current foreign history state', options, async () => { const h = fixture(); const saved = h.location.href; await h.session.persistSearchSession(); let release; h.transactionHook = tx => new Proxy(tx, { set(target, key, value) { target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value; return true; }, get(target, key) { const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; } }); h.location.href = 'https://example.test/search/'; const pending = h.session.restoreSearchSession(); await until(() => !!release); assert.deepEqual(h.history.replacements, []); const state = {foreign: ['updated', 42]}; h.history.state = state; release(); assert.equal(await pending, true); assert.equal(h.history.state, state); assert.equal(h.location.href, saved);
release = null; let allowed = true; const guarded = h.create({canRestore: () => allowed}); const stale = guarded.restoreSearchSession(); await until(() => !!release); allowed = false; release(); assert.equal(await stale, false); assert.equal(h.history.replacements.length, 1);});
test('a read deadline prevents later completion from publishing', options, async () => { const h = fixture(); await h.session.persistSearchSession(); let release; h.transactionHook = tx => new Proxy(tx, { set(target, key, value) { target[key] = key === 'oncomplete' ? event => { release = () => value(event); } : value; return true; }, get(target, key) { if (key === 'abort') return () => { throw new Error('already completing'); }; const value = target[key]; return typeof value === 'function' ? value.bind(target) : value; } }); const pending = h.session.restoreSearchSession(); await until(() => !!release); h.expire(); assert.equal(await pending, false); release(); await turn(); assert.deepEqual(h.history.replacements, []);});
test('unavailable storage and disabled policy settle without leaking work', options, async () => { const h = fixture(); const disabled = h.create({canPersist: () => false, canRestore: () => false}); await disabled.persistSearchSession(); assert.equal(await disabled.restoreSearchSession(), false); assert.equal(h.opens, 0); h.openError = new Error('storage unavailable'); await h.session.persistSearchSession(); await h.session.persistSearchSession(); assert.equal(await h.session.restoreSearchSession(), false);});361 unmodified lines362363364365366367361 unmodified linesmount(url: URL): HTMLIFrameElement;unmount(keepSpeech?: boolean): HTMLElement | null;dismiss(): void;replace(raw: string, returnScroll: object): HTMLIFrameElement | null;accepts(event: MessageEvent): boolean;persistProgress(progress: {url?: unknown; closeTime?: unknown} | null | undefined): void;361 unmodified lines362363364365366367368361 unmodified linesmount(url: URL): HTMLIFrameElement;unmount(keepSpeech?: boolean): HTMLElement | null;dismiss(): void;showCloseRecovery(raw: string): void;replace(raw: string, returnScroll: object): HTMLIFrameElement | null;accepts(event: MessageEvent): boolean;persistProgress(progress: {url?: unknown; closeTime?: unknown} | null | undefined): void;
scripts/search/check_reader_navigation_baseline.mjs+7-3
static/app.js+221-64
static/reader/core/reader-bindings.mjs+41-4
static/search/reader-navigation.js+49-5
static/search/search-session.js+140-54
tests/gates/ci-test-inventory.json+20
tests/gates/test_static_checks.py+14-2
tests/reader/browser/test_reader_host_history_races.pyAdded+378
tests/reader/browser/test_reader_navigation_host.py+96-8
tests/reader/browser/test_reader_reload_search_document.pyAdded+600
tests/reader/core/test_reader_regression.js+1-1
tests/search/browser/test_paging_recovery.py+8-2
tests/search/browser/test_session_transaction_browser.pyAdded+321
tests/search/reader-navigation/test_reader_navigation_baseline.mjs+173-7
tests/search/reader-navigation/test_search_history_races.mjsAdded+201
tests/search/session/test_search_session_contract.jsAdded+378
typings/reader-globals.d.ts+1