From 54b58b5cf7f9913cb9e16c9d31958f1c870310b5 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 02:08:20 -0400 Subject: [PATCH 001/273] fix(epub): reject missing section sources without moving the reader --- apps/web/src/lib/foliate-epub/paginator.js | 7 ++++++ tests/browser/test_foliate_slide.py | 29 ++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/apps/web/src/lib/foliate-epub/paginator.js b/apps/web/src/lib/foliate-epub/paginator.js index 867289bbf4..9b67101690 100644 --- a/apps/web/src/lib/foliate-epub/paginator.js +++ b/apps/web/src/lib/foliate-epub/paginator.js @@ -1204,6 +1204,13 @@ export class Paginator extends HTMLElement { this.dispatchEvent(new CustomEvent('navigationerror', { detail: error })) return false } + if (typeof src !== 'string' || !src) { + if (!this.#destroyed && generation === this.#navigationGeneration) + this.dispatchEvent(new CustomEvent('navigationerror', { + detail: new Error('EPUB section did not provide a renderable source'), + })) + return false + } await this.#display({ index, src, anchor, onLoad, select }, generation) } return !this.#destroyed && generation === this.#navigationGeneration && this.#index === index diff --git a/tests/browser/test_foliate_slide.py b/tests/browser/test_foliate_slide.py index 1d7d4c9e82..bc9950443a 100644 --- a/tests/browser/test_foliate_slide.py +++ b/tests/browser/test_foliate_slide.py @@ -445,6 +445,35 @@ def test_pending_navigation_blocks_turns_and_supersedes_stale_loads(self): }}""") self.assertEqual(result, {'navigated': False, 'invalid': [False, False], 'unchanged': True, 'recovered': True, 'errors': 1}) + def test_missing_section_source_fails_without_moving_visible_reader(self): + self.open_numbered_book() + result = self.page.evaluate(f"""async () => {{ + const p={P}, section=p.sections[1], load=section.load; + let errors=0; + p.addEventListener('navigationerror',()=>errors++); + const before={{index:p.getContents()[0].index,page:p.page, + text:p.getContents()[0].doc.body.textContent}}; + section.load=async()=>null; + const navigated=await p.goTo({{index:1}}); + const after={{index:p.getContents()[0].index,page:p.page, + text:p.getContents()[0].doc.body.textContent}}; + section.load=load; + const retry=await p.goTo({{index:1}}); + return {{ + navigated,retry,errors, + unchanged:before.index===after.index && before.page===after.page && before.text===after.text, + index:p.getContents()[0].index, + text:p.getContents()[0].doc.body.textContent + }}; + }}""") + self.assertFalse(result['navigated']) + self.assertTrue(result['unchanged']) + self.assertEqual(1, result['errors']) + self.assertTrue(result['retry']) + self.assertEqual(1, result['index']) + self.assertIn('Chapter 2', result['text']) + self.assertEqual([], self.errors) + def test_cross_chapter_iframe_load_is_staged_and_supersedable(self): self.open_numbered_book() result = self.page.evaluate(f"""async () => {{ From c934517929bc928c5bba1cd7de993ab52b6efc24 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 02:15:41 -0400 Subject: [PATCH 002/273] fix(epub): preserve invalid-source exceptions while rejecting missing sources --- apps/web/src/lib/foliate-epub/paginator.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/lib/foliate-epub/paginator.js b/apps/web/src/lib/foliate-epub/paginator.js index 9b67101690..77b0ac6b65 100644 --- a/apps/web/src/lib/foliate-epub/paginator.js +++ b/apps/web/src/lib/foliate-epub/paginator.js @@ -1204,7 +1204,7 @@ export class Paginator extends HTMLElement { this.dispatchEvent(new CustomEvent('navigationerror', { detail: error })) return false } - if (typeof src !== 'string' || !src) { + if (src == null || src === '') { if (!this.#destroyed && generation === this.#navigationGeneration) this.dispatchEvent(new CustomEvent('navigationerror', { detail: new Error('EPUB section did not provide a renderable source'), From a830c218ceab758ca19ac9fc2122bfae77104af2 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 03:01:32 -0400 Subject: [PATCH 003/273] fix(storage): commit local reader identity atomically --- apps/web/src/lib/reader-identity.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/apps/web/src/lib/reader-identity.ts b/apps/web/src/lib/reader-identity.ts index 15cda76ac3..5a75c7943f 100644 --- a/apps/web/src/lib/reader-identity.ts +++ b/apps/web/src/lib/reader-identity.ts @@ -5,6 +5,7 @@ */ import { database } from '$lib/data/store'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; /** Legacy imports without original-byte hashes keep a stable, local-only identity. */ export async function readerBookKeyFor(bookId: number, contentHash?: string): Promise { @@ -12,12 +13,14 @@ export async function readerBookKeyFor(bookId: number, contentHash?: string): Pr return `content:${contentHash.toLowerCase()}`; const db = await database.db; const tx = db.transaction('readerLocalIdentity', 'readwrite'); - const store = tx.objectStore('readerLocalIdentity'); - let identity = await store.get(bookId); - if (!identity) { - identity = { bookId, uuid: crypto.randomUUID() }; - await store.put(identity); - } - await tx.done; + const identity = await commitTransaction(tx, async () => { + const store = tx.objectStore('readerLocalIdentity'); + let value = await store.get(bookId); + if (!value) { + value = { bookId, uuid: crypto.randomUUID() }; + await store.put(value); + } + return value; + }); return `local:${identity.uuid}`; } From f8d977bc29c219f064f492d9826d66eeefdbd1f8 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 03:01:58 -0400 Subject: [PATCH 004/273] fix(storage): drain imported-note transactions from first request --- apps/web/src/lib/manabi/imported-notes.ts | 29 +++++------------------ 1 file changed, 6 insertions(+), 23 deletions(-) diff --git a/apps/web/src/lib/manabi/imported-notes.ts b/apps/web/src/lib/manabi/imported-notes.ts index 2246e4054c..76f0b56b2c 100644 --- a/apps/web/src/lib/manabi/imported-notes.ts +++ b/apps/web/src/lib/manabi/imported-notes.ts @@ -5,6 +5,7 @@ */ import { database } from '$lib/data/store'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import { localProfileUser } from './client'; import { canonical, MigrationConflict } from './ttu-migration-format'; import type { ReaderImportRecord } from '$lib/data/database/books-db/versions/v10/books-db-v10'; @@ -85,7 +86,7 @@ export async function editImportedNote( if (body.length > 65536 || label.length > 512) throw new Error('The note is too large.'); const db = await database.db; const tx = db.transaction('readerImportRecord', 'readwrite'); - try { + await commitTransaction(tx, async () => { const value = await tx.store.get(expected.id); checkOwner(owner); if (!value || (value.accountId !== null && value.accountId !== owner)) @@ -104,16 +105,7 @@ export async function editImportedNote( modifiedAt, deletedAt: deleted ? modifiedAt : undefined }); - await tx.done; - } catch (error) { - try { - tx.abort(); - } catch { - /* Already committed or aborted. */ - } - await tx.done.catch(() => undefined); - throw error; - } + }); } export async function exportImportedNotes(bookId: number, bookKey: string) { const owner = localProfileUser()?.id ?? null, @@ -165,8 +157,8 @@ export async function restoreImportedNotes( ['data', 'readerImportRecord', 'readerBookScope', 'readerAnnotation', 'readerAnnotationScope'], 'readwrite' ); - let changed = 0; - try { + return commitTransaction(tx, async () => { + let changed = 0; const book = (await tx.objectStore('data').get(bookId)) as | { contentHash?: string; manabiTtuImport?: { content: string } } | undefined; @@ -214,15 +206,6 @@ export async function restoreImportedNotes( changed++; } checkOwner(owner); - await tx.done; return changed; - } catch (error) { - try { - tx.abort(); - } catch { - /* Already committed or aborted. */ - } - await tx.done.catch(() => undefined); - throw error; - } + }); } From 0430b27d885cf6eaaf0fd0e6e3a74a812bc12421 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 03:02:14 -0400 Subject: [PATCH 005/273] fix(storage): drain cloud-series receipt transactions --- apps/web/src/lib/library/cloud-series.ts | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/apps/web/src/lib/library/cloud-series.ts b/apps/web/src/lib/library/cloud-series.ts index 37a9ae5088..2e09be538b 100644 --- a/apps/web/src/lib/library/cloud-series.ts +++ b/apps/web/src/lib/library/cloud-series.ts @@ -6,6 +6,7 @@ import { currentUser, request } from '$lib/manabi/client'; import { integrationDB, metadata, setMetadata } from '$lib/manabi/persistence'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import { sourceKey } from './organization'; import type { SourceDescriptor } from './catalog'; @@ -162,7 +163,7 @@ export async function applyCloudSeriesReceipts(source: SourceDescriptor, plan: C if (plan.root !== source.root) throw new Error('Receipt root changed.'); const db = await integrationDB(); const tx = db.transaction('metadata', 'readwrite'); - try { + return commitTransaction(tx, async () => { let changed = false; for (const receipt of plan.receipts) { if (receipt.connection_id !== source.id || receipt.root !== source.root) @@ -174,15 +175,6 @@ export async function applyCloudSeriesReceipts(source: SourceDescriptor, plan: C } } if (changed) await tx.store.delete(`library-catalog:${sourceKey(source)}`); - await tx.done; return changed; - } catch (error) { - try { - tx.abort(); - } catch { - /* already settled */ - } - await tx.done.catch(() => undefined); - throw error; - } + }); } From d6ef3f98be6599cdcff49764c52e9661526bb78f Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 03:02:40 -0400 Subject: [PATCH 006/273] fix(storage): drain WebDAV authority transactions --- apps/web/src/lib/webdav/source.ts | 82 +++++++++++-------------------- 1 file changed, 29 insertions(+), 53 deletions(-) diff --git a/apps/web/src/lib/webdav/source.ts b/apps/web/src/lib/webdav/source.ts index 783136358b..28cddb1ad7 100644 --- a/apps/web/src/lib/webdav/source.ts +++ b/apps/web/src/lib/webdav/source.ts @@ -5,6 +5,7 @@ */ import { integrationDB, exclusive, equal, type BookLink } from '$lib/manabi/persistence'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import type { LibrarySource, LibraryEntry, StateCopy } from '$lib/manabi/sources'; import { withLibraryOperation } from '$lib/manabi/operation-scope'; import { verifySelectedBook } from '$lib/library/book-download'; @@ -70,37 +71,30 @@ export async function configureDav( }; signal?.addEventListener('abort', cancel, { once: true }); try { - const previous = (await tx.objectStore('metadata').get(prefix + config.id)) as - | DavConfiguration - | undefined; - // Compare the editor's original snapshot, not a fresh read taken after its - // network test. A stale editor must not recreate or reauthorize a source. - if (!equal(previous ?? null, expected)) - throw new DavError( - 'conflict', - 'This WebDAV connection changed or was disconnected. Reload WebDAV connections before saving again.' - ); - if (previous && (previous.url !== value.url || previous.username !== value.username)) - throw new DavError( - 'reconnect', - 'Add a new WebDAV connection to change the folder or username. Existing books and sync settings were kept.' - ); - await tx.objectStore('metadata').put(value, prefix + config.id); - if (!value.writable) { - for (const link of await tx.objectStore('books').getAll()) - if (link.sourceId === config.id && link.syncEnabled) - await tx.objectStore('books').put({ ...link, syncEnabled: false }); - } - signal?.throwIfAborted(); - await tx.done; - } catch (error) { - try { - tx.abort(); - } catch { - /* Already settled. */ - } - await tx.done.catch(() => undefined); - throw error; + await commitTransaction(tx, async () => { + const previous = (await tx.objectStore('metadata').get(prefix + config.id)) as + | DavConfiguration + | undefined; + // Compare the editor's original snapshot, not a fresh read taken after its + // network test. A stale editor must not recreate or reauthorize a source. + if (!equal(previous ?? null, expected)) + throw new DavError( + 'conflict', + 'This WebDAV connection changed or was disconnected. Reload WebDAV connections before saving again.' + ); + if (previous && (previous.url !== value.url || previous.username !== value.username)) + throw new DavError( + 'reconnect', + 'Add a new WebDAV connection to change the folder or username. Existing books and sync settings were kept.' + ); + await tx.objectStore('metadata').put(value, prefix + config.id); + if (!value.writable) { + for (const link of await tx.objectStore('books').getAll()) + if (link.sourceId === config.id && link.syncEnabled) + await tx.objectStore('books').put({ ...link, syncEnabled: false }); + } + signal?.throwIfAborted(); + }); } finally { signal?.removeEventListener('abort', cancel); } @@ -119,21 +113,12 @@ export async function disconnectDav(id: string) { await withDavSourceLock(id, async () => { const db = await integrationDB(); const tx = db.transaction(['metadata', 'books'], 'readwrite'); - try { + await commitTransaction(tx, async () => { await tx.objectStore('metadata').delete(prefix + id); // Other metadata and imported books are not erased by disconnecting a source. for (const link of await tx.objectStore('books').getAll()) if (link.sourceId === id) await tx.objectStore('books').delete(link.id); - await tx.done; - } catch (error) { - try { - tx.abort(); - } catch { - /* Already settled. */ - } - await tx.done.catch(() => undefined); - throw error; - } + }); // A preceding queued configuration may have installed new session state // while this disconnect waited. Clear it under the same source lock too. lifetimes.get(id)?.abort(); @@ -258,7 +243,7 @@ export class WebDavSource implements LibrarySource { throw new DavError('reconnect', 'This book belongs to a different WebDAV connection.'); const db = await integrationDB(); const tx = db.transaction(['metadata', 'books'], 'readwrite'); - try { + return commitTransaction(tx, async () => { const latest = await tx.objectStore('metadata').get(prefix + this.id); if (!equal(latest, this.configuration)) throw new DavError( @@ -276,17 +261,8 @@ export class WebDavSource implements LibrarySource { 'The WebDAV book link changed during import. Refresh before retrying.' ); if (!existing) await tx.objectStore('books').put(link); - await tx.done; return existing ?? link; - } catch (error) { - try { - tx.abort(); - } catch { - /* Already committed or aborted. */ - } - await tx.done.catch(() => undefined); - throw error; - } + }); } private statePath(key: string) { if (!/^book_[a-f0-9]{64}$/.test(key)) throw new Error('Invalid WebDAV reading-data identity.'); From 6531f0228b5a0b8b06b213fb17395ef5008bd3d9 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 03:02:51 -0400 Subject: [PATCH 007/273] fix(storage): drain preview-cache transactions from first write --- apps/web/src/lib/library/previews.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/apps/web/src/lib/library/previews.ts b/apps/web/src/lib/library/previews.ts index e12118ce4b..4b0bdf460b 100644 --- a/apps/web/src/lib/library/previews.ts +++ b/apps/web/src/lib/library/previews.ts @@ -5,6 +5,7 @@ */ import { openDB, type DBSchema } from 'idb'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import { writable } from 'svelte/store'; import extractEpub from '$lib/functions/file-loaders/epub/extract-epub'; import coverFilename from '$lib/functions/file-loaders/epub/get-epub-cover-image-filename'; @@ -180,15 +181,16 @@ async function readPreview( const db = await previewDB(); checkAccess(source, signal); const tx = db.transaction('previews', 'readwrite'); - await tx.store.put(saved); - let count = await tx.store.count(); - let cursor = await tx.store.index('scannedAt').openCursor(); - while (cursor && count > 500) { - await cursor.delete(); - count--; - cursor = await cursor.continue(); - } - await tx.done; + await commitTransaction(tx, async () => { + await tx.store.put(saved); + let count = await tx.store.count(); + let cursor = await tx.store.index('scannedAt').openCursor(); + while (cursor && count > 500) { + await cursor.delete(); + count--; + cursor = await cursor.continue(); + } + }); checkAccess(source, signal); return value; } From 7ecd19f77775949f2fe2c2eee6e1fcd8b2bb21c8 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 03:03:54 -0400 Subject: [PATCH 008/273] test(storage): require early completion observation across writers --- .../indexeddb-transaction-lifetime.test.mjs | 247 ++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 tests/unit/indexeddb-transaction-lifetime.test.mjs diff --git a/tests/unit/indexeddb-transaction-lifetime.test.mjs b/tests/unit/indexeddb-transaction-lifetime.test.mjs new file mode 100644 index 0000000000..631d126f63 --- /dev/null +++ b/tests/unit/indexeddb-transaction-lifetime.test.mjs @@ -0,0 +1,247 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { loadOfflineModule } from './fixtures/offline-module.mjs'; + +function transaction(stores = {}) { + let observed = false; + const done = { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }; + const fallback = { + async get() { + assert.equal(observed, true, 'tx.done was not observed before the first request'); + return undefined; + }, + async put() { + assert.equal(observed, true, 'tx.done was not observed before the first request'); + }, + async delete() { + assert.equal(observed, true, 'tx.done was not observed before the first request'); + }, + async getAll() { + assert.equal(observed, true, 'tx.done was not observed before the first request'); + return []; + } + }; + const tx = { + done, + store: stores.default ?? fallback, + objectStore(name) { + return stores[name] ?? fallback; + }, + abort() {} + }; + return tx; +} + +test('reader local identity observes transaction completion before its first read', async () => { + const tx = transaction({ + readerLocalIdentity: { + async get(bookId) { + // The assertion lives in the default wrapper below; return an existing identity. + assert.equal(bookId, 7); + return { bookId, uuid: '11111111-1111-4111-8111-111111111111' }; + } + } + }); + // Preserve early-observation evidence for the custom store too. + let observed = false; + tx.done = { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }; + tx.objectStore = () => ({ + async get(bookId) { + assert.equal(observed, true); + return { bookId, uuid: '11111111-1111-4111-8111-111111111111' }; + }, + async put() { + assert.equal(observed, true); + } + }); + const { api } = loadOfflineModule('apps/web/src/lib/reader-identity.ts', { + modules: { '$lib/data/store': { database: { db: Promise.resolve({ transaction: () => tx }) } } } + }); + assert.equal(await api.readerBookKeyFor(7), 'local:11111111-1111-4111-8111-111111111111'); +}); + +test('imported-note edit observes transaction completion before reading the record', async () => { + const expected = { + id: '11111111-1111-4111-8111-111111111111', + bookId: 7, + bookKey: 'local:22222222-2222-4222-8222-222222222222', + accountId: null, + part: 'notes', + source: {}, + sourceCanonical: '{}', + status: 'book-note', + label: 'Before', + body: 'Body', + quote: '', + importedBody: '', + importedLabel: '', + createdAt: '2026-09-30T00:00:00.000Z', + modifiedAt: '2026-09-30T00:00:00.000Z' + }; + let observed = false; + const tx = { + done: { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }, + store: { + async get() { + assert.equal(observed, true); + return expected; + }, + async put() { + assert.equal(observed, true); + } + }, + abort() {} + }; + class MigrationConflict extends Error {} + const { api } = loadOfflineModule('apps/web/src/lib/manabi/imported-notes.ts', { + modules: { + '$lib/data/store': { database: { db: Promise.resolve({ transaction: () => tx }) } }, + './client': { localProfileUser: () => null }, + './ttu-migration-format': { + canonical: (value) => JSON.stringify(value), + MigrationConflict + } + } + }); + await api.editImportedNote(expected, 'After', 'Edited'); +}); + +test('cloud-series receipts observe transaction completion before receipt lookup', async () => { + let observed = false; + const store = { + async get() { + assert.equal(observed, true); + return undefined; + }, + async put() { + assert.equal(observed, true); + }, + async delete() { + assert.equal(observed, true); + } + }; + const tx = { + done: { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }, + store, + abort() {} + }; + const { api } = loadOfflineModule('apps/web/src/lib/library/cloud-series.ts', { + modules: { + '$lib/manabi/client': { + currentUser: () => ({ id: 'owner' }), + request: () => assert.fail('No network request expected') + }, + '$lib/manabi/persistence': { + integrationDB: async () => ({ transaction: () => tx }), + metadata: async () => undefined, + setMetadata: async () => undefined + }, + './organization': { sourceKey: () => 'source-key' } + } + }); + const source = { + id: '11111111-1111-4111-8111-111111111111', + owner: 'owner', + root: '/Books/', + provider: 'onedrive', + name: 'Cloud' + }; + const changed = await api.applyCloudSeriesReceipts(source, { + id: '22222222-2222-4222-8222-222222222222', + root: '/Books/', + operation: 'move_books', + revision: 1, + status: 'complete', + issue: '', + expires_at: '2026-10-01T00:00:00Z', + preview: { + folder_name: null, + name: null, + book_names: [], + parent_id: null, + destination_id: null + }, + steps: [], + receipts: [ + { + connection_id: source.id, + root: source.root, + item_id: 'item', + name: 'Book' + } + ] + }); + assert.equal(changed, true); +}); + +test('WebDAV disconnect observes transaction completion before deleting authority', async () => { + let observed = false; + const metadata = { + async delete() { + assert.equal(observed, true); + } + }; + const books = { + async getAll() { + assert.equal(observed, true); + return []; + }, + async delete() { + assert.equal(observed, true); + } + }; + const tx = { + done: { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }, + objectStore(name) { + return name === 'metadata' ? metadata : books; + }, + abort() {} + }; + class DavError extends Error {} + const { api } = loadOfflineModule('apps/web/src/lib/webdav/source.ts', { + modules: { + '$lib/manabi/persistence': { + integrationDB: async () => ({ transaction: () => tx }), + exclusive: async (_name, work) => work(), + equal: (a, b) => JSON.stringify(a) === JSON.stringify(b) + }, + '$lib/manabi/sources': {}, + '$lib/manabi/operation-scope': { withLibraryOperation: async (_owner, work) => work() }, + '$lib/library/book-download': { verifySelectedBook: (value) => value }, + './client': { + WebDavClient: class {}, + davRoot: (value) => new URL(value), + davChild: (_root, value) => new URL(value), + DavError, + strongEtag: () => false, + decodeDavText: () => '' + } + } + }); + await api.disconnectDav('webdav-test'); +}); From 5fa14f0431d918352684afcdf4e930f74b5170ff Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:07:06 -0400 Subject: [PATCH 009/273] fix(epub): enforce reflow-only rendition on restored publications --- .../src/lib/foliate-epub/publication-data.ts | 2 ++ test/reader/restored-book.test.ts | 33 +++++++++++++++++++ tests/unit/foliate-publication-data.test.mjs | 13 ++++++++ 3 files changed, 48 insertions(+) diff --git a/apps/web/src/lib/foliate-epub/publication-data.ts b/apps/web/src/lib/foliate-epub/publication-data.ts index bfda27fc06..4649479159 100644 --- a/apps/web/src/lib/foliate-epub/publication-data.ts +++ b/apps/web/src/lib/foliate-epub/publication-data.ts @@ -5,6 +5,7 @@ */ import type { PublicationManifest, PublicationResource } from '../reader-location'; +import { assertSupportedEpubRendition } from './epub-import-policy'; /** Prepared runtime resource. Image URLs belong to the owning read lifetime. */ export interface EpubResourceData extends PublicationResource { @@ -223,6 +224,7 @@ export function readEpubPublication(value: unknown, source: string): EpubPublica if (position !== source.length) throw new Error('EPUB resource ranges do not cover the source.'); const navigation = readNavigation(publication.navigation); const rendition = readRendition(publication.rendition); + assertSupportedEpubRendition(rendition); return { version: 1, resources, diff --git a/test/reader/restored-book.test.ts b/test/reader/restored-book.test.ts index e0f4a6808b..a8d16b28bd 100644 --- a/test/reader/restored-book.test.ts +++ b/test/reader/restored-book.test.ts @@ -187,3 +187,36 @@ test('JSON prototype keys are never spread into the restored model', async () => assert.equal(Object.hasOwn(result, 'id'), false); assert.equal(({} as Record).polluted, undefined); }); + + +test('restored fixed-layout EPUB metadata is rejected before any book is exposed', async () => { + const elementHtml = '

fixed

'; + const fixed = { + ...meta, + sourceFormat: 'epub', + elementHtml, + publicationManifest: { + version: 1, + resources: [{ href: 'fixed.xhtml', spineIndex: 0, sectionId: 'ttu-epub-0' }] + }, + epubPublication: { + version: 1, + resources: [ + { + href: 'fixed.xhtml', + spineIndex: 0, + sectionId: 'ttu-epub-0', + start: 0, + end: elementHtml.length, + style: 0 + } + ], + styleSheets: [''], + rendition: { layout: 'pre-paginated' } + } + }; + await assert.rejects( + readRestoredBook(await book(fixed), mime, options), + /Fixed-layout EPUBs are not supported/i + ); +}); diff --git a/tests/unit/foliate-publication-data.test.mjs b/tests/unit/foliate-publication-data.test.mjs index 94f1177770..1645479f4f 100644 --- a/tests/unit/foliate-publication-data.test.mjs +++ b/tests/unit/foliate-publication-data.test.mjs @@ -294,3 +294,16 @@ test('restored rendition retains only bounded supported scalar hints', () => { value.rendition = { layout: 'x'.repeat(129) }; assert.throws(() => readEpubPublication(value, packed.elementHtml), /navigation text|rendition/i); }); + + +test('persisted fixed-layout rendition cannot bypass the reflow-only import gate', () => { + const packed = packEpubResources(resources(), { + rendition: { layout: 'reflowable' } + }); + const restored = globalThis.structuredClone(packed.epubPublication); + restored.rendition.layout = 'pre-paginated'; + assert.throws( + () => readEpubPublication(restored, packed.elementHtml), + /Fixed-layout EPUBs are not supported/i + ); +}); From cccb149d4bd264cff27ed14a4b1fa9fc1feb3cf4 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:32:22 -0400 Subject: [PATCH 010/273] refactor(library): bind selection eligibility to page owner --- .../src/lib/library/library-workspace.svelte | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/apps/web/src/lib/library/library-workspace.svelte b/apps/web/src/lib/library/library-workspace.svelte index 8251b6d8f4..d5192a014b 100644 --- a/apps/web/src/lib/library/library-workspace.svelte +++ b/apps/web/src/lib/library/library-workspace.svelte @@ -140,13 +140,16 @@ export let selectMode = false; export let destinationTitle = 'Library'; export let menu: LibraryMenuModel | undefined = undefined; + /** Parent-owned selection eligibility; binding avoids lifecycle-sensitive scope events. */ + export let selectionScopeKey = ''; + export let selectableBookIds: number[] = []; + export let selectablePreviewKeys: string[] = []; const dispatch = createEventDispatcher<{ bookClick: { id: number }; prepareBook: { prepare: () => Promise; locator?: ReaderLocator }; selectionManyClick: { ids: number[] }; selectionChange: { ids: number[]; previews: string[] }; selectionCancel: void; - selectionScopeChange: { key: string; ids: number[]; previews: string[] }; removeBookClick: { id: number }; }>(); let catalogs: Catalog[] = [], @@ -171,7 +174,6 @@ $: personalSeriesNames = [ ...new Set(books.flatMap((book) => (book.series ? [book.series.name] : []))) ].sort(); - let announcedSelectionScope = ''; let organizationScope = ''; let dialogOpen = false, dialog: 'details' | 'rename' | 'date' | 'membership' | 'series-name' | 'new-series' = 'rename'; @@ -417,25 +419,12 @@ $: selectableBookIds = visibleBooks.flatMap((book) => (book.bookId ? [book.bookId] : [])); $: selectionScopeKey = `${viewerId ?? 'local'}:${collectionId}:${series?.id || ''}:${notFinished ? 'unfinished' : 'all'}:${normalizedQuery}`; $: selectablePreviewKeys = visibleBooks.filter((book) => !book.bookId).map((book) => book.key); - $: selectionSignature = JSON.stringify([ - selectionScopeKey, - selectableBookIds, - selectablePreviewKeys - ]); $: if (organizationScope !== selectionScopeKey) { organizationScope = selectionScopeKey; organizationEpoch++; organizationDialog = undefined; organizationTargets = []; } - $: if (selectionSignature !== announcedSelectionScope) { - announcedSelectionScope = selectionSignature; - dispatch('selectionScopeChange', { - key: selectionScopeKey, - ids: selectableBookIds, - previews: selectablePreviewKeys - }); - } const groupKey = (source: SourceDescriptor) => source.owner === null ? source.id : sourceKey(source); $: groupCandidates = books.filter( From eac8ff882a4e79d20c871af75f70cbaf1765773d Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:32:25 -0400 Subject: [PATCH 011/273] fix(library): reconcile selection from bound visible scope --- apps/web/src/routes/manage/+page.svelte | 54 ++++++++++++++++--------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/apps/web/src/routes/manage/+page.svelte b/apps/web/src/routes/manage/+page.svelte index 8674e714dc..e6faf01492 100644 --- a/apps/web/src/routes/manage/+page.svelte +++ b/apps/web/src/routes/manage/+page.svelte @@ -159,6 +159,8 @@ let selectionScopeKey = ''; let selectableBookIds: number[] = []; let selectablePreviewKeys: string[] = []; + let reconciledSelectionScopeKey = ''; + let reconciledSelectionEligibility = ''; let libraryMenu: LibraryMenuModel | undefined; let pageAlive = true; let openGeneration = 0; @@ -202,6 +204,37 @@ } } + $: { + const eligibility = JSON.stringify([ + selectionScopeKey, + selectableBookIds, + selectablePreviewKeys + ]); + if (selectionScopeKey !== reconciledSelectionScopeKey) { + reconciledSelectionScopeKey = selectionScopeKey; + reconciledSelectionEligibility = eligibility; + if (selectMode) { + // A search/collection/series scope is a distinct selection operation. + // Never carry hidden selections into a different visible scope. + selectedPreviewKeys = new Set(); + selectedBookIds = new Set(); + } + } else if (eligibility !== reconciledSelectionEligibility) { + reconciledSelectionEligibility = eligibility; + if (selectMode) { + // Same scope, changing availability: retain only still-actionable items. + const eligibleBooks = new Set(selectableBookIds); + const eligiblePreviews = new Set(selectablePreviewKeys); + selectedPreviewKeys = new Set( + [...selectedPreviewKeys].filter((key) => eligiblePreviews.has(key)) + ); + selectedBookIds = new Set( + [...selectedBookIds].filter((id) => eligibleBooks.has(id)) + ); + } + } + } + onDestroy(() => { pageAlive = false; openGeneration++; @@ -631,22 +664,6 @@ }); } - function updateSelectionScope(key: string, ids: number[], previews: string[] = []) { - selectableBookIds = ids; - selectablePreviewKeys = previews; - if (key !== selectionScopeKey) { - selectionScopeKey = key; - selectedPreviewKeys = new Set(); - selectedBookIds = new Set(); - } else { - const eligible = new Set(ids); - selectedPreviewKeys = new Set( - [...selectedPreviewKeys].filter((key) => previews.includes(key)) - ); - selectedBookIds = new Set([...selectedBookIds].filter((id) => eligible.has(id))); - } - } - function toggleCollections() { collectionsOpen = true; } @@ -1232,6 +1249,9 @@ (selectMode = false)} - on:selectionScopeChange={(ev) => - updateSelectionScope(ev.detail.key, ev.detail.ids, ev.detail.previews)} on:removeBookClick={(ev) => removeBooks([ev.detail.id])} > {@render emptyLibrary()} From 059116ebccf010d2f69982e668a21c3a70680160 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:33:10 -0400 Subject: [PATCH 012/273] test(library): clear selection across both search scope directions --- tests/browser/test_library_parity.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/browser/test_library_parity.py b/tests/browser/test_library_parity.py index 237c444a48..90f37cd5ce 100644 --- a/tests/browser/test_library_parity.py +++ b/tests/browser/test_library_parity.py @@ -93,6 +93,13 @@ def test_menu_selection_enters_keyboard_scope_and_visible_all_respects_search(se self.count(1) self.assertEqual(1, self.items().count()) + # Clearing the filter is another visible selection scope. The filtered + # selection must not silently reappear among the full shelf. + search.fill('') + self.count(0) + self.assertEqual(3, self.items().count()) + expect(self.items().filter(has=self.page.get_by_text('Selected', exact=True))).to_have_count(0) + def start_drag(self, layout): first, second = self.items().nth(0).bounding_box(), self.items().nth(1).bounding_box() if layout == 'Grid': From 70effb7a2ed6537cabde1059e1fe60f053c3abe5 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:38:19 -0400 Subject: [PATCH 013/273] refactor(library): publish selection eligibility atomically --- .../src/lib/library/library-workspace.svelte | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/apps/web/src/lib/library/library-workspace.svelte b/apps/web/src/lib/library/library-workspace.svelte index d5192a014b..f5889cc0ab 100644 --- a/apps/web/src/lib/library/library-workspace.svelte +++ b/apps/web/src/lib/library/library-workspace.svelte @@ -140,10 +140,12 @@ export let selectMode = false; export let destinationTitle = 'Library'; export let menu: LibraryMenuModel | undefined = undefined; - /** Parent-owned selection eligibility; binding avoids lifecycle-sensitive scope events. */ - export let selectionScopeKey = ''; - export let selectableBookIds: number[] = []; - export let selectablePreviewKeys: string[] = []; + /** One immutable snapshot keeps scope and eligibility atomic across the component boundary. */ + export let selectionEligibility: { key: string; ids: number[]; previews: string[] } = { + key: '', + ids: [], + previews: [] + }; const dispatch = createEventDispatcher<{ bookClick: { id: number }; prepareBook: { prepare: () => Promise; locator?: ReaderLocator }; @@ -174,6 +176,9 @@ $: personalSeriesNames = [ ...new Set(books.flatMap((book) => (book.series ? [book.series.name] : []))) ].sort(); + let selectionScopeKey = '', + selectableBookIds: number[] = [], + selectablePreviewKeys: string[] = []; let organizationScope = ''; let dialogOpen = false, dialog: 'details' | 'rename' | 'date' | 'membership' | 'series-name' | 'new-series' = 'rename'; @@ -419,6 +424,11 @@ $: selectableBookIds = visibleBooks.flatMap((book) => (book.bookId ? [book.bookId] : [])); $: selectionScopeKey = `${viewerId ?? 'local'}:${collectionId}:${series?.id || ''}:${notFinished ? 'unfinished' : 'all'}:${normalizedQuery}`; $: selectablePreviewKeys = visibleBooks.filter((book) => !book.bookId).map((book) => book.key); + $: selectionEligibility = { + key: selectionScopeKey, + ids: selectableBookIds, + previews: selectablePreviewKeys + }; $: if (organizationScope !== selectionScopeKey) { organizationScope = selectionScopeKey; organizationEpoch++; From 7cffc142bc424a3dca2e6ac0211a12a127e6d056 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:38:23 -0400 Subject: [PATCH 014/273] refactor(library): reconcile one immutable eligibility snapshot --- apps/web/src/routes/manage/+page.svelte | 36 ++++++++++++------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/apps/web/src/routes/manage/+page.svelte b/apps/web/src/routes/manage/+page.svelte index e6faf01492..0207fab943 100644 --- a/apps/web/src/routes/manage/+page.svelte +++ b/apps/web/src/routes/manage/+page.svelte @@ -159,8 +159,12 @@ let selectionScopeKey = ''; let selectableBookIds: number[] = []; let selectablePreviewKeys: string[] = []; - let reconciledSelectionScopeKey = ''; - let reconciledSelectionEligibility = ''; + let selectionEligibility: { key: string; ids: number[]; previews: string[] } = { + key: '', + ids: [], + previews: [] + }; + let reconciledSelectionEligibility = selectionEligibility; let libraryMenu: LibraryMenuModel | undefined; let pageAlive = true; let openGeneration = 0; @@ -204,24 +208,20 @@ } } - $: { - const eligibility = JSON.stringify([ - selectionScopeKey, - selectableBookIds, - selectablePreviewKeys - ]); - if (selectionScopeKey !== reconciledSelectionScopeKey) { - reconciledSelectionScopeKey = selectionScopeKey; - reconciledSelectionEligibility = eligibility; - if (selectMode) { + $: if (selectionEligibility !== reconciledSelectionEligibility) { + const previousScope = reconciledSelectionEligibility.key; + reconciledSelectionEligibility = selectionEligibility; + selectionScopeKey = selectionEligibility.key; + selectableBookIds = selectionEligibility.ids; + selectablePreviewKeys = selectionEligibility.previews; + + if (selectMode) { + if (selectionScopeKey !== previousScope) { // A search/collection/series scope is a distinct selection operation. // Never carry hidden selections into a different visible scope. selectedPreviewKeys = new Set(); selectedBookIds = new Set(); - } - } else if (eligibility !== reconciledSelectionEligibility) { - reconciledSelectionEligibility = eligibility; - if (selectMode) { + } else { // Same scope, changing availability: retain only still-actionable items. const eligibleBooks = new Set(selectableBookIds); const eligiblePreviews = new Set(selectablePreviewKeys); @@ -1249,9 +1249,7 @@ Date: Wed, 30 Sep 2026 16:38:55 -0400 Subject: [PATCH 015/273] refactor(library): centralize visible-scope reconciliation --- apps/web/src/lib/library/selection.ts | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/apps/web/src/lib/library/selection.ts b/apps/web/src/lib/library/selection.ts index 0ff5aa3e15..a6911f932c 100644 --- a/apps/web/src/lib/library/selection.ts +++ b/apps/web/src/lib/library/selection.ts @@ -78,6 +78,34 @@ export class LibrarySelection { } } +export interface LibrarySelectionEligibility { + key: string; + ids: readonly number[]; + previews: readonly string[]; +} + +export function reconcileSelectionEligibility( + previousScope: string, + next: LibrarySelectionEligibility, + selectedIds: ReadonlySet, + selectedPreviews: ReadonlySet +) { + if (next.key !== previousScope) + return { + scope: next.key, + ids: new Set(), + previews: new Set() + }; + + const eligibleIds = new Set(next.ids); + const eligiblePreviews = new Set(next.previews); + return { + scope: next.key, + ids: new Set([...selectedIds].filter((id) => eligibleIds.has(id))), + previews: new Set([...selectedPreviews].filter((key) => eligiblePreviews.has(key))) + }; +} + export interface SelectionRect { key: string; left: number; From 5eddae206517318686de8d521956d641fe8b02c3 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:38:59 -0400 Subject: [PATCH 016/273] refactor(library): share selection eligibility contract --- apps/web/src/lib/library/library-workspace.svelte | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/library/library-workspace.svelte b/apps/web/src/lib/library/library-workspace.svelte index f5889cc0ab..87ef5d5b5e 100644 --- a/apps/web/src/lib/library/library-workspace.svelte +++ b/apps/web/src/lib/library/library-workspace.svelte @@ -2,6 +2,7 @@ import { foldSearch } from './search-normalization'; import { bookTitleMatchIndex } from '../search/book-title-match-text'; import { librarySelection } from './selection-action'; + import type { LibrarySelectionEligibility } from './selection'; import BookOrganizationDialog from './book-organization-dialog.svelte'; import type { BookPresentation, PresentationChange } from './organization'; import { onMount, createEventDispatcher, tick, type Snippet } from 'svelte'; @@ -141,7 +142,7 @@ export let destinationTitle = 'Library'; export let menu: LibraryMenuModel | undefined = undefined; /** One immutable snapshot keeps scope and eligibility atomic across the component boundary. */ - export let selectionEligibility: { key: string; ids: number[]; previews: string[] } = { + export let selectionEligibility: LibrarySelectionEligibility = { key: '', ids: [], previews: [] From 03b728c4b5a024fb0a26169c8d0b99e6f50cae6c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:39:02 -0400 Subject: [PATCH 017/273] refactor(library): use tested selection reconciliation rule --- apps/web/src/routes/manage/+page.svelte | 30 +++++++++++-------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/apps/web/src/routes/manage/+page.svelte b/apps/web/src/routes/manage/+page.svelte index 0207fab943..461a1946f1 100644 --- a/apps/web/src/routes/manage/+page.svelte +++ b/apps/web/src/routes/manage/+page.svelte @@ -6,6 +6,10 @@ import { beforeNavigate, goto } from '$app/navigation'; import BookCardList from '$lib/components/book-card/book-card-list.svelte'; import LibraryWorkspace from '$lib/library/library-workspace.svelte'; + import { + reconcileSelectionEligibility, + type LibrarySelectionEligibility + } from '$lib/library/selection'; import type { BookCardProps } from '$lib/components/book-card/book-card-props'; import BookManagerHeader from '$lib/components/book-card/book-manager-header.svelte'; import BookExportDialog from '$lib/components/book-export/book-export-dialog.svelte'; @@ -159,7 +163,7 @@ let selectionScopeKey = ''; let selectableBookIds: number[] = []; let selectablePreviewKeys: string[] = []; - let selectionEligibility: { key: string; ids: number[]; previews: string[] } = { + let selectionEligibility: LibrarySelectionEligibility = { key: '', ids: [], previews: [] @@ -216,22 +220,14 @@ selectablePreviewKeys = selectionEligibility.previews; if (selectMode) { - if (selectionScopeKey !== previousScope) { - // A search/collection/series scope is a distinct selection operation. - // Never carry hidden selections into a different visible scope. - selectedPreviewKeys = new Set(); - selectedBookIds = new Set(); - } else { - // Same scope, changing availability: retain only still-actionable items. - const eligibleBooks = new Set(selectableBookIds); - const eligiblePreviews = new Set(selectablePreviewKeys); - selectedPreviewKeys = new Set( - [...selectedPreviewKeys].filter((key) => eligiblePreviews.has(key)) - ); - selectedBookIds = new Set( - [...selectedBookIds].filter((id) => eligibleBooks.has(id)) - ); - } + const reconciled = reconcileSelectionEligibility( + previousScope, + selectionEligibility, + selectedBookIds, + selectedPreviewKeys + ); + selectedBookIds = reconciled.ids; + selectedPreviewKeys = reconciled.previews; } } From bafa8213403295108d77ca9a1b1328b0137caaab Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:39:18 -0400 Subject: [PATCH 018/273] test(library): cover visible-scope reconciliation contract --- tests/unit/library-selection.test.mjs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/unit/library-selection.test.mjs b/tests/unit/library-selection.test.mjs index 4351384cd3..c724329468 100644 --- a/tests/unit/library-selection.test.mjs +++ b/tests/unit/library-selection.test.mjs @@ -3,7 +3,8 @@ import test from 'node:test'; import { LibrarySelection, adjacentSelection, - marqueeSelection + marqueeSelection, + reconcileSelectionEligibility } from '../../apps/web/src/lib/library/selection.ts'; const items = ['a', 'b', 'c', 'd', 'e'].map((key, i) => ({ key, ids: [i + 1] })); const ids = (value) => [...value].sort((a, b) => a - b); @@ -90,6 +91,29 @@ test('external Select All replaces the old range baseline while equal UI echoes assert.deepEqual(ids(selection.choose('b', items, { shift: true })), [1, 2, 3, 4, 5]); }); +test('visible-scope reconciliation clears selection when the scope changes', () => { + const result = reconcileSelectionEligibility( + 'local:books::all:', + { key: 'local:books::all:parity 1', ids: [2], previews: ['preview-b'] }, + new Set([1]), + new Set(['preview-a']) + ); + assert.equal(result.scope, 'local:books::all:parity 1'); + assert.deepEqual([...result.ids], []); + assert.deepEqual([...result.previews], []); +}); + +test('visible-scope reconciliation only trims unavailable items inside one scope', () => { + const result = reconcileSelectionEligibility( + 'local:books::all:', + { key: 'local:books::all:', ids: [2, 3], previews: ['preview-b'] }, + new Set([1, 2, 3]), + new Set(['preview-a', 'preview-b']) + ); + assert.deepEqual([...result.ids], [2, 3]); + assert.deepEqual([...result.previews], ['preview-b']); +}); + test('rendered string identities select unopened previews without manufacturing browser IDs', () => { const model = new LibrarySelection(); const entries = [ From fa08c4ac7d3a0d1aec93e9545de65709d9ef0408 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:42:37 -0400 Subject: [PATCH 019/273] test(library): stress compact selection at 200 percent text --- tests/browser/test_library_parity.py | 66 ++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/tests/browser/test_library_parity.py b/tests/browser/test_library_parity.py index 90f37cd5ce..9edffc462b 100644 --- a/tests/browser/test_library_parity.py +++ b/tests/browser/test_library_parity.py @@ -100,6 +100,72 @@ def test_menu_selection_enters_keyboard_scope_and_visible_all_respects_search(se self.assertEqual(3, self.items().count()) expect(self.items().filter(has=self.page.get_by_text('Selected', exact=True))).to_have_count(0) + def test_compact_selection_toolbar_reflows_at_200_percent_text(self): + self.page.set_viewport_size({'width': 320, 'height': 568}) + self.populate(3) + self.page.evaluate('document.documentElement.style.fontSize = "200%"') + + actions = self.page.get_by_role('button', name='Library actions', exact=True) + actions.click() + menu = self.page.get_by_role('menu') + expect(menu).to_be_visible() + menu.get_by_role('menuitem', name='Select Books', exact=True).click() + + toolbar = self.page.get_by_label('Book selection', exact=True) + expect(toolbar).to_be_visible() + self.assertLessEqual(toolbar.evaluate('e => e.scrollWidth-e.clientWidth'), 1) + self.assertLessEqual( + self.page.evaluate('document.documentElement.scrollWidth-innerWidth'), 1) + + def reachable(control): + box = control.bounding_box() + self.assertIsNotNone(box) + self.assertGreaterEqual(box['width'], 43.99) + self.assertGreaterEqual(box['height'], 43.99) + self.assertGreaterEqual(box['x'], -1) + self.assertGreaterEqual(box['y'], -1) + self.assertLessEqual(box['x'] + box['width'], 321) + self.assertLessEqual(box['y'] + box['height'], 569) + self.assertTrue(control.evaluate('''e => { + const r=e.getBoundingClientRect(); + const hit=document.elementFromPoint(r.left+r.width/2,r.top+r.height/2); + return !!hit && (hit===e || e.contains(hit)); + }''')) + + cancel = toolbar.get_by_role('button', name='Cancel selection', exact=True) + select_all = toolbar.get_by_role('button', name='Select All Visible', exact=True) + reachable(cancel) + reachable(select_all) + expect(toolbar.get_by_text('0 selected', exact=True)).to_be_visible() + + select_all.click() + expect(toolbar.get_by_text('3 selected', exact=True)).to_be_visible() + export = toolbar.get_by_role('button', name='Export', exact=True) + more = toolbar.get_by_role('button', name='Selected book actions', exact=True) + reachable(export) + reachable(more) + self.assertLessEqual(toolbar.evaluate('e => e.scrollWidth-e.clientWidth'), 1) + + more.focus() + more.press('Enter') + selected_menu = self.page.get_by_role('menu') + expect(selected_menu).to_be_visible() + menu_box = selected_menu.bounding_box() + self.assertGreaterEqual(menu_box['x'], -1) + self.assertGreaterEqual(menu_box['y'], -1) + self.assertLessEqual(menu_box['x'] + menu_box['width'], 321) + self.assertLessEqual(menu_box['y'] + menu_box['height'], 569) + self.assertLessEqual(selected_menu.evaluate('e => e.scrollWidth-e.clientWidth'), 1) + for item in selected_menu.get_by_role('menuitem').all(): + self.assertGreaterEqual(item.bounding_box()['height'], 43.99) + self.page.keyboard.press('Escape') + expect(selected_menu).to_have_count(0) + expect(more).to_be_focused() + + cancel.click() + expect(toolbar).to_have_count(0) + self.page.evaluate('document.documentElement.style.fontSize = ""') + def start_drag(self, layout): first, second = self.items().nth(0).bounding_box(), self.items().nth(1).bounding_box() if layout == 'Grid': From e4d65dfb9d8a4b6504b6997a03b3c0a767b2a560 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:46:26 -0400 Subject: [PATCH 020/273] refine(video): make batch selection state explicit --- apps/web/src/lib/media/workspace.ts | 79 +++++++++++++++++++++-------- 1 file changed, 58 insertions(+), 21 deletions(-) diff --git a/apps/web/src/lib/media/workspace.ts b/apps/web/src/lib/media/workspace.ts index 064d8450c6..7a607cd4fb 100644 --- a/apps/web/src/lib/media/workspace.ts +++ b/apps/web/src/lib/media/workspace.ts @@ -88,6 +88,10 @@ export class VideoWorkspace { private jobs = make('section'); private syncPanel = make('section'); private selected = new Set(); + private selectionStatus = make('span'); + private selectVisibleButton!: HTMLButtonElement; + private clearSelectionButton!: HTMLButtonElement; + private bulkGenerateButton!: HTMLButtonElement; private sources = new Map(); /** A digest belongs to this immutable local File instance, not its filename or mtime. */ private verifiedSources = new WeakMap(); @@ -187,6 +191,7 @@ export class VideoWorkspace { this.search.setAttribute('aria-label', 'Search videos'); this.search.addEventListener('input', () => { this.selected.clear(); + this.updateSelectionActions(); void this.refresh(); }); for (const [value, label] of [ @@ -212,6 +217,7 @@ export class VideoWorkspace { } this.filter.addEventListener('change', () => { this.selected.clear(); + this.updateSelectionActions(); void this.refresh(); }); tools.append(this.search, this.sort, this.filter); @@ -271,19 +277,32 @@ export class VideoWorkspace { ); const batch = make('div'); batch.className = 'media-actions'; + batch.setAttribute('role', 'group'); + batch.setAttribute('aria-label', 'Video selection actions'); + this.selectionStatus.className = 'media-selection-status'; + this.selectionStatus.setAttribute('role', 'status'); + this.selectionStatus.setAttribute('aria-live', 'polite'); + this.selectVisibleButton = action('Select visible videos', () => { + for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) { + check.checked = true; + this.selected.add(check.value as ContentKey); + } + this.updateSelectionActions(); + }); + this.clearSelectionButton = action('Clear selection', () => { + this.selected.clear(); + this.updateSelectionActions(); + void this.refresh(); + }); + this.bulkGenerateButton = action( + 'Generate missing transcripts', + () => void this.bulk().catch((e) => this.error(e)) + ); batch.append( - action('Select visible videos', () => { - for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) { - check.checked = true; - this.selected.add(check.value as ContentKey); - } - this.notice(`${this.selected.size} videos selected`); - }), - action('Clear selection', () => { - this.selected.clear(); - void this.refresh(); - }), - action('Generate missing transcripts', () => void this.bulk().catch((e) => this.error(e))) + this.selectVisibleButton, + this.clearSelectionButton, + this.bulkGenerateButton, + this.selectionStatus ); this.shelf.className = 'video-shelf'; this.shelf.setAttribute('aria-label', 'Video library'); @@ -302,6 +321,7 @@ export class VideoWorkspace { this.jobs ); host.append(this.root); + this.updateSelectionActions(); const engine = options.engine ?? new MossClient(options.runtimeBase); this.decoderCache = new DecodeSessionCache(async (job, signal) => { const source = await this.resolveSource(jobContentKey(job), signal); @@ -369,6 +389,21 @@ export class VideoWorkspace { label.append(document.createTextNode(text), control); return label; } + private updateSelectionActions() { + const visible = [ + ...this.shelf.querySelectorAll('input[type=checkbox]') + ]; + this.clearSelectionButton.disabled = this.selected.size === 0; + this.bulkGenerateButton.disabled = this.selected.size === 0; + this.selectVisibleButton.disabled = + visible.length === 0 || + visible.every((check) => this.selected.has(check.value as ContentKey)); + this.selectionStatus.textContent = + this.selected.size === 0 + ? 'No videos selected' + : `${this.selected.size} ${this.selected.size === 1 ? 'video' : 'videos'} selected`; + } + private notice(text: string) { if (!this.closed) this.status.textContent = text; } @@ -1119,9 +1154,8 @@ export class VideoWorkspace { await this.refreshJobs(); return job.id; } - private async bulk() { + private async bulk(selection: ContentKey[] = [...this.selected]) { const lang = language(this.lang.value), - selection = [...this.selected], skipped: string[] = []; for (const key of selection) { this.lifetime.signal.throwIfAborted(); @@ -1385,9 +1419,11 @@ export class VideoWorkspace { checkbox.value = key; checkbox.checked = this.selected.has(key); checkbox.setAttribute('aria-label', `Select ${info.title}`); - checkbox.addEventListener('change', () => - checkbox.checked ? this.selected.add(key) : this.selected.delete(key) - ); + checkbox.addEventListener('change', () => { + if (checkbox.checked) this.selected.add(key); + else this.selected.delete(key); + this.updateSelectionActions(); + }); const selectionTarget = make('label'); selectionTarget.className = 'video-select'; selectionTarget.append(checkbox); @@ -1410,10 +1446,10 @@ export class VideoWorkspace { menu.append( make('summary', 'Actions'), action('Open video', () => void this.reopen(key).catch((e) => this.error(e))), - action('Generate missing transcript', () => { - this.selected = new Set([key]); - void this.bulk().catch((e) => this.error(e)); - }), + action( + 'Generate missing transcript', + () => void this.bulk([key]).catch((e) => this.error(e)) + ), action('Rename title', () => { const title = window.prompt('Video display title', info.title); if (title?.trim()) @@ -1447,6 +1483,7 @@ export class VideoWorkspace { ?.focus({ preventScroll: true }); } } + this.updateSelectionActions(); } catch (e) { this.error(e); } From 9adb918b9085a5607aa32a8ba7922c31f43d5f73 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:46:47 -0400 Subject: [PATCH 021/273] refine(video): style persistent selection status --- apps/web/src/lib/media/media.css | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/web/src/lib/media/media.css b/apps/web/src/lib/media/media.css index a34d35a228..75cb8b0130 100644 --- a/apps/web/src/lib/media/media.css +++ b/apps/web/src/lib/media/media.css @@ -119,6 +119,14 @@ .media-actions { margin: 16px 0; } +.media-selection-status { + flex: 1 1 100%; + min-width: 0; + min-height: 1.5em; + color: var(--media-secondary); + font-size: 0.875rem; + overflow-wrap: anywhere; +} .media-actions input[type='search'] { flex: 1; min-width: 160px; From 31e01e2aa504e97da20ddec4331df560b0270b5b Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:46:50 -0400 Subject: [PATCH 022/273] test(video): qualify batch selection state in real app --- tests/media/app-browser.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/tests/media/app-browser.py b/tests/media/app-browser.py index eec55f1f4e..181c69077a 100644 --- a/tests/media/app-browser.py +++ b/tests/media/app-browser.py @@ -154,13 +154,41 @@ def upload(): const hit=document.elementFromPoint(r.left+r.width/2,r.top+r.height/2); return !!hit && (hit===label || label.contains(hit)); }""") + batch = page.get_by_role('group', name='Video selection actions', exact=True) + select_visible = batch.get_by_role('button', name='Select visible videos', exact=True) + clear_selection = batch.get_by_role('button', name='Clear selection', exact=True) + bulk_generate = batch.get_by_role('button', name='Generate missing transcripts', exact=True) + selection_status = batch.get_by_role('status') + expect(selection_status).to_have_text('No videos selected') + expect(select_visible).to_be_enabled() + expect(clear_selection).to_be_disabled() + expect(bulk_generate).to_be_disabled() + card_select.focus() expect(card_select).to_be_focused() page.keyboard.press('Space') expect(card_select).to_be_checked() + expect(selection_status).to_have_text('1 video selected') + expect(select_visible).to_be_disabled() + expect(clear_selection).to_be_enabled() + expect(bulk_generate).to_be_enabled() + page.keyboard.press('Space') expect(card_select).not_to_be_checked() - results.append('video card selection has a native 44px keyboard and pointer target') + expect(selection_status).to_have_text('No videos selected') + expect(select_visible).to_be_enabled() + expect(clear_selection).to_be_disabled() + expect(bulk_generate).to_be_disabled() + + select_visible.click() + expect(card_select).to_be_checked() + expect(selection_status).to_have_text('1 video selected') + clear_selection.click() + expect(card_select).not_to_be_checked() + expect(selection_status).to_have_text('No videos selected') + expect(clear_selection).to_be_disabled() + expect(bulk_generate).to_be_disabled() + results.append('video batch selection exposes one coherent count and disables no-op actions') existing = page.get_by_label('Choose existing subtitles', exact=True) expect(existing.locator('option')).to_have_count(3) From 456cd17ead2a2bb510dbe42ce8fbfdb617049c62 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:47:25 -0400 Subject: [PATCH 023/273] test(video): cover explicit batch selection ownership --- tests/media/workspace-dom.py | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/media/workspace-dom.py b/tests/media/workspace-dom.py index a89f3e7ce3..60dfd2203f 100644 --- a/tests/media/workspace-dom.py +++ b/tests/media/workspace-dom.py @@ -1002,6 +1002,52 @@ def populate(): await store.edit('guest','video_resume',syntheticKey('b'),syntheticKey('b'),resume(syntheticKey('b'),30,true)); }''') page.wait_for_function('document.querySelectorAll(".video-card").length===3') + def batch_selection_state(): + populate() + batch=page.get_by_role('group',name='Video selection actions',exact=True) + select_visible=batch.get_by_role('button',name='Select visible videos',exact=True) + clear=batch.get_by_role('button',name='Clear selection',exact=True) + generate=batch.get_by_role('button',name='Generate missing transcripts',exact=True) + status=batch.get_by_role('status') + assert status.inner_text()=='No videos selected' + assert select_visible.is_enabled() + assert clear.is_disabled() and generate.is_disabled() + + watching=page.get_by_label('Select Watching',exact=True) + watching.check() + assert status.inner_text()=='1 video selected' + assert clear.is_enabled() and generate.is_enabled() + + page.get_by_label('Search videos',exact=True).fill('Finished') + page.wait_for_function('document.querySelectorAll(".video-card").length===1') + assert page.evaluate('workspace.selected.size')==0 + assert status.inner_text()=='No videos selected' + assert clear.is_disabled() and generate.is_disabled() + + page.get_by_label('Search videos',exact=True).fill('') + page.wait_for_function('document.querySelectorAll(".video-card").length===3') + page.evaluate('window.bulkSelections=[];workspace.bulk=async selection=>bulkSelections.push([...selection])') + card=page.locator('.video-card').filter( + has=page.get_by_role('button',name='Watching',exact=True)) + card.get_by_text('Actions',exact=True).click() + card.get_by_role('button',name='Generate missing transcript',exact=True).click() + assert page.evaluate('bulkSelections')==[[page.evaluate("syntheticKey('a')")]] + assert page.evaluate('workspace.selected.size')==0 + assert not page.get_by_label('Select Watching',exact=True).is_checked() + + select_visible.click() + assert status.inner_text()=='3 videos selected' + assert select_visible.is_disabled() + assert clear.is_enabled() and generate.is_enabled() + generate.click() + assert len(page.evaluate('bulkSelections[1]'))==3 + clear.click() + assert page.evaluate('workspace.selected.size')==0 + assert status.inner_text()=='No videos selected' + assert clear.is_disabled() and generate.is_disabled() + assert all(not check.is_checked() for check in page.get_by_label(re.compile('^Select ')).all()) + case('video batch actions expose selection state and card generation does not mutate it', + batch_selection_state) def filtering(): populate();page.get_by_label('Select New',exact=True).check() page.get_by_label('Filter videos',exact=True).select_option('continue') From c5005d52874754b22fa8a486134d9231068f0970 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:49:06 -0400 Subject: [PATCH 024/273] fix(library): type bound eligibility as readonly --- apps/web/src/routes/manage/+page.svelte | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/routes/manage/+page.svelte b/apps/web/src/routes/manage/+page.svelte index 461a1946f1..158335e197 100644 --- a/apps/web/src/routes/manage/+page.svelte +++ b/apps/web/src/routes/manage/+page.svelte @@ -161,8 +161,8 @@ let collectionsOpen = false; let destinationTitle = 'Library'; let selectionScopeKey = ''; - let selectableBookIds: number[] = []; - let selectablePreviewKeys: string[] = []; + let selectableBookIds: readonly number[] = []; + let selectablePreviewKeys: readonly string[] = []; let selectionEligibility: LibrarySelectionEligibility = { key: '', ids: [], From 3ed0d4ff05373d8e6468ec0d1c69a65648bc230d Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:56:57 -0400 Subject: [PATCH 025/273] refine(tracker): keep pager geometry fixed under text scaling --- .../book-reading-tracker-menu.svelte | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte index 447dec3f80..62d862832b 100644 --- a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte +++ b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte @@ -473,7 +473,7 @@ variant="ghost" size="icon" shape="circle" - class="size-11" + class="tracker-history-page" aria-label="Previous history page" title="Previous Page" disabled={currentTrackingHistoryIndex === 0} @@ -482,7 +482,7 @@ @@ -493,7 +493,7 @@ variant="ghost" size="icon" shape="circle" - class="size-11" + class="tracker-history-page" aria-label="Next history page" title="Next Page" disabled={!hasNextPage} @@ -519,3 +519,13 @@ {/if} + + From bb67357ee0a67f3f26608844cca8b088f90009f3 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 16:57:03 -0400 Subject: [PATCH 026/273] test(tracker): cap pager chrome at 44 pixels under large text --- tests/browser/test_panel_usability.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/browser/test_panel_usability.py b/tests/browser/test_panel_usability.py index 8bdb5fe03c..e9e53ffadd 100644 --- a/tests/browser/test_panel_usability.py +++ b/tests/browser/test_panel_usability.py @@ -174,6 +174,15 @@ def test_tracker_history_paginates_without_stranding_keyboard_focus(self): previous = panel.get_by_role('button', name='Previous history page', exact=True) next_page = panel.get_by_role('button', name='Next history page', exact=True) + for pager in (previous, next_page): + box = pager.bounding_box() + self.assertGreaterEqual(box['width'], 43.5) + self.assertLessEqual(box['width'], 44.5) + self.assertGreaterEqual(box['height'], 43.5) + self.assertLessEqual(box['height'], 44.5) + page_status = panel.get_by_role('status').filter(has_text='Page 1 of 2') + expect(page_status).to_be_visible() + self.assertEqual('nowrap', page_status.evaluate('e => getComputedStyle(e).whiteSpace')) expect(previous).to_be_disabled() expect(next_page).to_be_enabled() expect(panel.get_by_role('status').filter(has_text='Page 1 of 2')).to_be_visible() From cc266458e253d5c4391cd0030a32424e9d184664 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:23:07 -0400 Subject: [PATCH 027/273] fix(video): preserve focus across batch selection boundaries --- apps/web/src/lib/media/workspace.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/web/src/lib/media/workspace.ts b/apps/web/src/lib/media/workspace.ts index 7a607cd4fb..b873b7be3e 100644 --- a/apps/web/src/lib/media/workspace.ts +++ b/apps/web/src/lib/media/workspace.ts @@ -283,15 +283,26 @@ export class VideoWorkspace { this.selectionStatus.setAttribute('role', 'status'); this.selectionStatus.setAttribute('aria-live', 'polite'); this.selectVisibleButton = action('Select visible videos', () => { + const ownsFocus = document.activeElement === this.selectVisibleButton; for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) { check.checked = true; this.selected.add(check.value as ContentKey); } this.updateSelectionActions(); + if (ownsFocus && this.selectVisibleButton.disabled) + this.clearSelectionButton.focus({ preventScroll: true }); }); this.clearSelectionButton = action('Clear selection', () => { + const ownsFocus = document.activeElement === this.clearSelectionButton; this.selected.clear(); + // Reflect the cleared model immediately. Refresh can still reconcile the + // complete shelf, but keyboard/pointer users should never observe checked + // boxes while the status already says that nothing is selected. + for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) + check.checked = false; this.updateSelectionActions(); + if (ownsFocus && this.clearSelectionButton.disabled) + this.selectVisibleButton.focus({ preventScroll: true }); void this.refresh(); }); this.bulkGenerateButton = action( From 6228cd0d4b6f5b82391b8a9e6130231ebf873a3b Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:23:28 -0400 Subject: [PATCH 028/273] test(video): require batch focus handoff at disabled boundaries --- tests/media/app-browser.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/media/app-browser.py b/tests/media/app-browser.py index 181c69077a..c52afe21d0 100644 --- a/tests/media/app-browser.py +++ b/tests/media/app-browser.py @@ -180,13 +180,20 @@ def upload(): expect(clear_selection).to_be_disabled() expect(bulk_generate).to_be_disabled() - select_visible.click() + select_visible.focus() + select_visible.press('Enter') expect(card_select).to_be_checked() expect(selection_status).to_have_text('1 video selected') - clear_selection.click() + expect(select_visible).to_be_disabled() + expect(clear_selection).to_be_focused() + + clear_selection.press('Enter') + # The checked DOM state clears in the same activation turn; async shelf + # refresh must not create a checked/no-selection visual contradiction. expect(card_select).not_to_be_checked() expect(selection_status).to_have_text('No videos selected') expect(clear_selection).to_be_disabled() + expect(select_visible).to_be_focused() expect(bulk_generate).to_be_disabled() results.append('video batch selection exposes one coherent count and disables no-op actions') From 2bd829ac4795cd13d92fc5459b800d057b040469 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:23:32 -0400 Subject: [PATCH 029/273] test(video): cover focus continuity and synchronous clear --- tests/media/workspace-dom.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/media/workspace-dom.py b/tests/media/workspace-dom.py index 60dfd2203f..b9e6e47207 100644 --- a/tests/media/workspace-dom.py +++ b/tests/media/workspace-dom.py @@ -1035,16 +1035,21 @@ def batch_selection_state(): assert page.evaluate('workspace.selected.size')==0 assert not page.get_by_label('Select Watching',exact=True).is_checked() - select_visible.click() + select_visible.focus() + select_visible.press('Enter') assert status.inner_text()=='3 videos selected' assert select_visible.is_disabled() assert clear.is_enabled() and generate.is_enabled() + assert clear.is_focused() generate.click() assert len(page.evaluate('bulkSelections[1]'))==3 - clear.click() + + clear.focus() + clear.press('Enter') assert page.evaluate('workspace.selected.size')==0 assert status.inner_text()=='No videos selected' assert clear.is_disabled() and generate.is_disabled() + assert select_visible.is_focused() assert all(not check.is_checked() for check in page.get_by_label(re.compile('^Select ')).all()) case('video batch actions expose selection state and card generation does not mutate it', batch_selection_state) From 09c0b4944cec3cee100c4d278b929b181b8a44f4 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:24:43 -0400 Subject: [PATCH 030/273] test(video): stress batch actions at enlarged text --- tests/media/app-browser.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/media/app-browser.py b/tests/media/app-browser.py index c52afe21d0..a50175fcbd 100644 --- a/tests/media/app-browser.py +++ b/tests/media/app-browser.py @@ -197,6 +197,22 @@ def upload(): expect(bulk_generate).to_be_disabled() results.append('video batch selection exposes one coherent count and disables no-op actions') + page.set_viewport_size({'width':320,'height':568}) + page.evaluate("document.documentElement.style.fontSize='200%'") + batch.scroll_into_view_if_needed() + assert batch.evaluate("e => e.scrollWidth-e.clientWidth") <= 1 + assert page.locator('html').evaluate("e => e.scrollWidth-e.clientWidth") <= 1 + for control in (select_visible, clear_selection, bulk_generate): + box = control.bounding_box() + assert box and box['height'] >= 43.5, box + assert box['x'] >= -1 and box['x'] + box['width'] <= 321, box + status_box = selection_status.bounding_box() + assert status_box and status_box['x'] >= -1 and status_box['x'] + status_box['width'] <= 321 + page.screenshot(path=str(args.output/'video-selection-200-percent.png'), full_page=True) + page.evaluate("document.documentElement.style.fontSize=''") + page.set_viewport_size({'width':1280,'height':900}) + results.append('video batch actions reflow without overflow at 200 percent text') + existing = page.get_by_label('Choose existing subtitles', exact=True) expect(existing.locator('option')).to_have_count(3) assert page.locator('.transcript-cue').count() == 0 From 32051674aedc56cf4057608e31cce36127c6992c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:25:45 -0400 Subject: [PATCH 031/273] refactor(video): centralize synchronous selection clearing --- apps/web/src/lib/media/workspace.ts | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/apps/web/src/lib/media/workspace.ts b/apps/web/src/lib/media/workspace.ts index b873b7be3e..0d1b4ec8a5 100644 --- a/apps/web/src/lib/media/workspace.ts +++ b/apps/web/src/lib/media/workspace.ts @@ -190,8 +190,7 @@ export class VideoWorkspace { this.search.placeholder = 'Search videos'; this.search.setAttribute('aria-label', 'Search videos'); this.search.addEventListener('input', () => { - this.selected.clear(); - this.updateSelectionActions(); + this.clearSelectionView(); void this.refresh(); }); for (const [value, label] of [ @@ -216,8 +215,7 @@ export class VideoWorkspace { this.filter.append(option); } this.filter.addEventListener('change', () => { - this.selected.clear(); - this.updateSelectionActions(); + this.clearSelectionView(); void this.refresh(); }); tools.append(this.search, this.sort, this.filter); @@ -294,13 +292,7 @@ export class VideoWorkspace { }); this.clearSelectionButton = action('Clear selection', () => { const ownsFocus = document.activeElement === this.clearSelectionButton; - this.selected.clear(); - // Reflect the cleared model immediately. Refresh can still reconcile the - // complete shelf, but keyboard/pointer users should never observe checked - // boxes while the status already says that nothing is selected. - for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) - check.checked = false; - this.updateSelectionActions(); + this.clearSelectionView(); if (ownsFocus && this.clearSelectionButton.disabled) this.selectVisibleButton.focus({ preventScroll: true }); void this.refresh(); @@ -400,6 +392,15 @@ export class VideoWorkspace { label.append(document.createTextNode(text), control); return label; } + private clearSelectionView() { + this.selected.clear(); + // The durable shelf refresh can be asynchronous. Keep the already-rendered + // controls consistent with the model/status in the same interaction turn. + for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) + check.checked = false; + this.updateSelectionActions(); + } + private updateSelectionActions() { const visible = [ ...this.shelf.querySelectorAll('input[type=checkbox]') From bbdbf30e443d2e89d8cb929930867ee533262811 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:26:00 -0400 Subject: [PATCH 032/273] test(video): assert same-turn selection clearing on search --- tests/media/workspace-dom.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tests/media/workspace-dom.py b/tests/media/workspace-dom.py index b9e6e47207..4c4399e7e4 100644 --- a/tests/media/workspace-dom.py +++ b/tests/media/workspace-dom.py @@ -1018,10 +1018,20 @@ def batch_selection_state(): assert status.inner_text()=='1 video selected' assert clear.is_enabled() and generate.is_enabled() - page.get_by_label('Search videos',exact=True).fill('Finished') + immediate=page.evaluate("""()=>{ + const input=document.querySelector('[aria-label="Search videos"]'); + input.value='Finished'; + input.dispatchEvent(new Event('input',{bubbles:true})); + return { + selected:workspace.selected.size, + checked:[...document.querySelectorAll('.video-card input[type=checkbox]')] + .map(input=>input.checked), + status:document.querySelector('[aria-label="Video selection actions"] [role=status]') + ?.textContent + }; + }""") + assert immediate==dict(selected=0,checked=[False,False,False],status='No videos selected'),immediate page.wait_for_function('document.querySelectorAll(".video-card").length===1') - assert page.evaluate('workspace.selected.size')==0 - assert status.inner_text()=='No videos selected' assert clear.is_disabled() and generate.is_disabled() page.get_by_label('Search videos',exact=True).fill('') From 72145e72cf2c23f67119a4e6371e26e5f24ba65b Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:27:00 -0400 Subject: [PATCH 033/273] fix(library): restore focus after toolbar selection cancel --- .../components/book-card/book-manager-header.svelte | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/components/book-card/book-manager-header.svelte b/apps/web/src/lib/components/book-card/book-manager-header.svelte index a778665670..cae53102ef 100644 --- a/apps/web/src/lib/components/book-card/book-manager-header.svelte +++ b/apps/web/src/lib/components/book-card/book-manager-header.svelte @@ -58,6 +58,7 @@ let hydrated = false; let searchInput: HTMLInputElement | undefined; let searchButton: HTMLButtonElement | null = null; + let libraryActionsButton: HTMLButtonElement | null = null; onMount(() => { hydrated = true; const media = window.matchMedia('(max-width: 1023px)'); @@ -117,6 +118,13 @@ }) ); } + async function exitSelectionMode() { + selectMode = false; + // Compact selection removes the ordinary header, including its actions + // trigger. Wait for that trigger to be recreated before restoring focus. + await tick(); + libraryActionsButton?.focus({ preventScroll: true }); + } let countImportElm: HTMLInputElement; $: isOldUrl = browser && isOnOldUrl(window); $: showLoadCount = browser && new URLSearchParams(window.location.search).has('count'); @@ -318,6 +326,7 @@ {#snippet child({ props })} {selectedCount} selected From 0366d6843be31e3cbf86f2fb444379b0895e53cc Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:27:03 -0400 Subject: [PATCH 034/273] fix(media): persist sparse digital-silence evidence --- .../web/src/lib/media/sparse-transcription.ts | 44 +++++++++++++++++-- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/apps/web/src/lib/media/sparse-transcription.ts b/apps/web/src/lib/media/sparse-transcription.ts index 99cf2ca972..34faf82a6d 100644 --- a/apps/web/src/lib/media/sparse-transcription.ts +++ b/apps/web/src/lib/media/sparse-transcription.ts @@ -15,6 +15,9 @@ export const SPARSE_CONTEXT_SECONDS = 2; export interface SparseWindow { cues: Cue[]; inferenceMs: number; + /** Strong negative evidence from the exact PCM passed to MOSS. Optional so + * older saved windows keep their historical reconciliation semantics. */ + digitalSilence?: true; } export interface SparseState { policy: 'overlap-sparse-v1' | 'overlap-sparse-v2'; @@ -89,10 +92,17 @@ export function validateSparseState(value: unknown, duration: number): SparseSta const windows = state.windows.map((raw, index) => { if (raw === null) return null; const w = record(raw); - onlyKeys(w, ['cues', 'inferenceMs']); - if (!Array.isArray(w.cues) || w.cues.length > 2048) throw new Error('Invalid sparse window'); + onlyKeys(w, ['cues', 'inferenceMs', 'digitalSilence']); + if ( + !Array.isArray(w.cues) || + w.cues.length > 2048 || + (w.digitalSilence !== undefined && w.digitalSilence !== true) + ) + throw new Error('Invalid sparse window'); const bounds = sparseBounds(index, duration); const cues = w.cues.map(validateCue); + if (w.digitalSilence === true && cues.length) + throw new Error('Digital-silent sparse window cannot contain speech'); if ( new Set(cues.map((cue) => cue.id)).size !== cues.length || cues.some( @@ -103,7 +113,11 @@ export function validateSparseState(value: unknown, duration: number): SparseSta ) ) throw new Error('Sparse cue lies outside its input'); - return { cues, inferenceMs: finite(w.inferenceMs, 0, 3600000) }; + return { + cues, + inferenceMs: finite(w.inferenceMs, 0, 3600000), + ...(w.digitalSilence === true ? { digitalSilence: true as const } : {}) + }; }); const repairs = rawRepairs.map((raw, index) => { if (raw === null) return null; @@ -232,6 +246,28 @@ interface SparseComponent { cues: Cue[]; } +/** A neighboring exact-zero input is stronger evidence than a one-sided MOSS + * hypothesis wholly inside that same PCM. Filter only the reconciliation copy: + * source hypotheses remain durable, and a cue crossing the zero-input boundary + * stays whole and unresolved. Repairs are not rewritten by older silence evidence. */ +function rawSparseCues(state: SparseState, index: number): Cue[] { + const window = state.windows[index]; + if (!window) return []; + const previousSeam = index * SPARSE_CORE_SECONDS; + const nextSeam = (index + 1) * SPARSE_CORE_SECONDS; + return window.cues.filter( + (cue) => + !( + (index > 0 && + state.windows[index - 1]?.digitalSilence === true && + cue.end <= previousSeam + SPARSE_CONTEXT_SECONDS) || + (index + 1 < state.windows.length && + state.windows[index + 1]?.digitalSilence === true && + cue.start >= nextSeam - SPARSE_CONTEXT_SECONDS) + ) + ); +} + /** Reconcile the same whole-cue hypotheses for display, readiness and publication. * A repair is one two-core input; its superseded raw windows never decide its * outer seams. The cursor advances by time, not an arbitrary last-N cue slice. @@ -250,7 +286,7 @@ function sparseComponents( if (repair) { segments.push({ first: index, last: index + 1, cues: [...repair] }); } else if (window && !state.repairs[index - 1]) - segments.push({ first: index, last: index, cues: [...window.cues] }); + segments.push({ first: index, last: index, cues: rawSparseCues(state, index) }); } for (const segment of segments) { if (active && active.last + 1 >= segment.first) { From 8f37da995d3cc4e6ec1a48b451b908e9b08d2f4a Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:27:13 -0400 Subject: [PATCH 035/273] fix(library): restore focus after toolbar selection cancel From c6500438cab0699333fe1b2046eca52ef3a07d39 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:27:14 -0400 Subject: [PATCH 036/273] fix(media): retain zero-audio evidence in sparse checkpoints --- apps/web/src/lib/media/queue.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/media/queue.ts b/apps/web/src/lib/media/queue.ts index 1ecf3b6d0d..7ae7a37b13 100644 --- a/apps/web/src/lib/media/queue.ts +++ b/apps/web/src/lib/media/queue.ts @@ -891,9 +891,10 @@ export class TranscriptionQueue { ? await audioProofAsync(bounds.start, bounds.end, pcm, signal) : undefined; const inputDuration = pcm.length / 16000; + const digitalSilence = pcm.every((sample) => sample === 0); let raw = ''; let inferenceMs = performance.now() - decodeStarted; - if (!pcm.every((sample) => sample === 0)) { + if (!digitalSilence) { await this.engine.prepare(signal, (p) => this.notify({ job, ...p })); const inferenceStarted = performance.now(); raw = await transcribeWithPreview(this.engine, pcm, signal, (text) => { @@ -920,7 +921,11 @@ export class TranscriptionQueue { ...(cue.speaker ? { speaker: `w${index}/${cue.speaker}` } : {}) })); const next = { ...state, windows: [...state.windows] }; - next.windows[index] = { cues, inferenceMs }; + next.windows[index] = { + cues, + inferenceMs, + ...(digitalSilence ? { digitalSilence: true as const } : {}) + }; const safe = acceptedSparseCues(next, job.duration); preserveAccepted(job.cues, safe); job = { From cfac39cf9548de3b593303919d9772a7c2a79de0 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:27:32 -0400 Subject: [PATCH 037/273] test(library): require focus return after cancel selection --- tests/browser/test_library_parity.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/browser/test_library_parity.py b/tests/browser/test_library_parity.py index 9edffc462b..432943798e 100644 --- a/tests/browser/test_library_parity.py +++ b/tests/browser/test_library_parity.py @@ -162,8 +162,12 @@ def reachable(control): expect(selected_menu).to_have_count(0) expect(more).to_be_focused() - cancel.click() + cancel.focus() + expect(cancel).to_be_focused() + cancel.press('Enter') expect(toolbar).to_have_count(0) + restored_actions = self.page.get_by_role('button', name='Library actions', exact=True) + expect(restored_actions).to_be_focused() self.page.evaluate('document.documentElement.style.fontSize = ""') def start_drag(self, layout): From 5cc629b0deb908e14f8ef2038b18c93778a2d36c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:27:51 -0400 Subject: [PATCH 038/273] test(media): cover sparse zero-audio seam evidence --- tests/media/sparse-transcription.test.mjs | 93 +++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/tests/media/sparse-transcription.test.mjs b/tests/media/sparse-transcription.test.mjs index 2f1b759e17..20302a0a94 100644 --- a/tests/media/sparse-transcription.test.mjs +++ b/tests/media/sparse-transcription.test.mjs @@ -101,6 +101,55 @@ test('agreed whole cues crossing a seam margin appear, one-sided cues require re assert.deepEqual(assembleSparse(state), { repair: 0 }); assert.equal(sparseLead(state, 52, 0), 23); }); +test('verified digital silence resolves only whole cues covered by the zero input', () => { + const state = newSparseState(52); + const early = cue(0, 3, 4, 'real speech'); + state.windows[0] = { + cues: [early, cue(0, 24, 27, 'silence hallucination')], + inferenceMs: 1 + }; + state.windows[1] = { cues: [], inferenceMs: 1, digitalSilence: true }; + assert.deepEqual(safeSparseCues(state, 52), [early]); + assert.deepEqual(assembleSparse(state), { cues: [early] }); + + // A cue beginning before the verified-zero input is kept whole and remains + // ambiguous. Silence evidence is not permission to clip its prefix. + state.windows[0] = { cues: [early, cue(0, 23, 27, 'crossing speech')], inferenceMs: 1 }; + assert.deepEqual(assembleSparse(state), { repair: 0 }); + + // The evidence works in the other direction too: a previous zero window can + // refute only the part of the next hypothesis wholly inside its input. + state.windows[0] = { cues: [], inferenceMs: 1, digitalSilence: true }; + state.windows[1] = { cues: [cue(1, 24, 27, 'reverse hallucination')], inferenceMs: 1 }; + assert.deepEqual(assembleSparse(state), { cues: [] }); +}); +test('digital-silence evidence is explicit and cannot coexist with saved speech', () => { + const state = newSparseState(52); + state.windows[0] = { + cues: [cue(0, 3, 4, 'contradiction')], + inferenceMs: 1, + digitalSilence: true + }; + assert.throws( + () => + validateJob({ + version: 3, + sparse: state, + id: crypto.randomUUID(), + mediaKey: key, + language: 'ja', + audioTrack: '1', + duration: 52, + status: 'failed', + nextWindow: 1, + cues: [], + modelSha256: 'a'.repeat(64), + engineRevision: 'test', + createdAt: Date.now() + }), + /Digital-silent sparse window/ + ); +}); test('an empty seam repair cannot erase recognized speech', () => { const state = newSparseState(52); state.windows[0] = { cues: [cue(0, 24, 27, 'spoken left')], inferenceMs: 1 }; @@ -229,6 +278,50 @@ test('watched-through sparse job completes from one inference per window', async else globalThis.IDBKeyRange = old; } }); +test('a verified-zero neighbor removes a sparse halo hallucination without repair inference', async () => { + const old = globalThis.IDBKeyRange; + globalThis.IDBKeyRange = RangeDouble; + const store = new MediaStore(new TransactionFactory(), 'sparse-silence-evidence-tests'); + const decoded = [], + inferred = []; + const engine = { + async prepare() {}, + async transcribe() { + inferred.push(1); + if (inferred.length > 1) throw Error('silence reconciliation must not start repair inference'); + return '[3][S01]real speech[4][24][S01]silence hallucination[27]'; + }, + dispose() {} + }; + const queue = new TranscriptionQueue(store, 'guest', engine, async (_job, start, end) => { + decoded.push(start); + const pcm = new Float32Array(Math.round((end - start) * 16000)); + if (start === 0) pcm.fill(0.1); + return pcm; + }); + try { + const job = await queue.enqueue(key, 'ja', '1', 52, 0); + for (let i = 0; i < 500; i++) { + const saved = await store.local('guest', 'jobs', job.id); + if (saved?.status === 'complete' || saved?.status === 'failed') break; + await new Promise((resolve) => setTimeout(resolve, 1)); + } + const saved = validateJob(await store.local('guest', 'jobs', job.id)); + assert.equal(saved.status, 'complete', saved.error); + assert.deepEqual(decoded, [0, 24]); + assert.equal(inferred.length, 1); + const [track] = await store.tracks('guest', key); + assert.deepEqual( + track.cues.map((item) => item.text), + ['real speech'] + ); + } finally { + await queue.dispose(); + await store.close(); + if (old === undefined) delete globalThis.IDBKeyRange; + else globalThis.IDBKeyRange = old; + } +}); test('an ambiguous near-playhead seam is repaired before unrelated later windows', async () => { const old = globalThis.IDBKeyRange; globalThis.IDBKeyRange = RangeDouble; From 6ef7ddffa13f8ed06781a31e12afdbbc8822cf3f Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:28:00 -0400 Subject: [PATCH 039/273] refine(video): avoid redundant selection live announcements --- apps/web/src/lib/media/workspace.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/media/workspace.ts b/apps/web/src/lib/media/workspace.ts index 0d1b4ec8a5..2d0ca9d162 100644 --- a/apps/web/src/lib/media/workspace.ts +++ b/apps/web/src/lib/media/workspace.ts @@ -280,6 +280,7 @@ export class VideoWorkspace { this.selectionStatus.className = 'media-selection-status'; this.selectionStatus.setAttribute('role', 'status'); this.selectionStatus.setAttribute('aria-live', 'polite'); + this.selectionStatus.setAttribute('aria-atomic', 'true'); this.selectVisibleButton = action('Select visible videos', () => { const ownsFocus = document.activeElement === this.selectVisibleButton; for (const check of this.shelf.querySelectorAll('input[type=checkbox]')) { @@ -410,10 +411,13 @@ export class VideoWorkspace { this.selectVisibleButton.disabled = visible.length === 0 || visible.every((check) => this.selected.has(check.value as ContentKey)); - this.selectionStatus.textContent = + const status = this.selected.size === 0 ? 'No videos selected' : `${this.selected.size} ${this.selected.size === 1 ? 'video' : 'videos'} selected`; + // Refreshes are frequent (storage, captions, jobs). Do not recreate the + // live-region text node unless the user-visible selection state changed. + if (this.selectionStatus.textContent !== status) this.selectionStatus.textContent = status; } private notice(text: string) { From 805f18bfd1771dbbfc61fe03742a0b53eef3e63d Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:28:18 -0400 Subject: [PATCH 040/273] test(video): suppress redundant live-region mutations --- tests/media/workspace-dom.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/media/workspace-dom.py b/tests/media/workspace-dom.py index 4c4399e7e4..6fe01ad022 100644 --- a/tests/media/workspace-dom.py +++ b/tests/media/workspace-dom.py @@ -1010,6 +1010,20 @@ def batch_selection_state(): generate=batch.get_by_role('button',name='Generate missing transcripts',exact=True) status=batch.get_by_role('status') assert status.inner_text()=='No videos selected' + assert status.get_attribute('aria-atomic')=='true' + redundant=page.evaluate("""async()=>{ + const status=document.querySelector( + '[aria-label="Video selection actions"] [role=status]'); + let mutations=0; + const observer=new MutationObserver(records=>mutations+=records.length); + observer.observe(status,{subtree:true,childList:true,characterData:true}); + workspace.updateSelectionActions(); + workspace.updateSelectionActions(); + await Promise.resolve(); + observer.disconnect(); + return mutations; + }""") + assert redundant==0,redundant assert select_visible.is_enabled() assert clear.is_disabled() and generate.is_disabled() From 1bec7c5abbb44ca231cae54a27ef5225396dade3 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:28:20 -0400 Subject: [PATCH 041/273] test(video): require atomic batch selection status --- tests/media/app-browser.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/media/app-browser.py b/tests/media/app-browser.py index a50175fcbd..0bc294da1c 100644 --- a/tests/media/app-browser.py +++ b/tests/media/app-browser.py @@ -160,6 +160,7 @@ def upload(): bulk_generate = batch.get_by_role('button', name='Generate missing transcripts', exact=True) selection_status = batch.get_by_role('status') expect(selection_status).to_have_text('No videos selected') + expect(selection_status).to_have_attribute('aria-atomic', 'true') expect(select_visible).to_be_enabled() expect(clear_selection).to_be_disabled() expect(bulk_generate).to_be_disabled() From e0288dd2450190dfb46b25941b9d3164c24ec5fa Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:28:32 -0400 Subject: [PATCH 042/273] docs(media): document sparse silence evidence --- docs/moss-progressive-transcription.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/moss-progressive-transcription.md b/docs/moss-progressive-transcription.md index 2457b0bc49..d8f004466e 100644 --- a/docs/moss-progressive-transcription.md +++ b/docs/moss-progressive-transcription.md @@ -148,7 +148,13 @@ a second full transcription pass. Bulk jobs and saved v1/v2 jobs retain their original sequential policy and can resume without reinterpretation. Draft captions use whole cues away from unresolved seams. Once neighboring -windows agree, their boundary cues can appear too. A completed track is +windows agree, their boundary cues can appear too. A normal sparse window whose exact +model PCM is entirely zero now persists that fact as optional device-only evidence. It +may refute only a neighboring one-sided cue wholly covered by the same zero-valued +input; a cue crossing outside that input remains whole and unresolved. An ordinary +empty hypothesis has no such authority and still requires agreement or repair. Older +saved windows do not gain silence evidence retroactively. + A completed track is published only after every core is covered and the whole-cue hypotheses join. An ambiguous seam is repaired with a bounded union input; overlapping repairs that exceed the model budget fail with the original hypotheses preserved. From 72fc2c089594698ef3f3291a7348aa05946c2e32 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:30:01 -0400 Subject: [PATCH 043/273] fix(media): exclude silent cores from ASR ETA rate --- apps/web/src/lib/media/sparse-transcription.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/web/src/lib/media/sparse-transcription.ts b/apps/web/src/lib/media/sparse-transcription.ts index 34faf82a6d..4017a3fc0a 100644 --- a/apps/web/src/lib/media/sparse-transcription.ts +++ b/apps/web/src/lib/media/sparse-transcription.ts @@ -428,6 +428,10 @@ export function sparsePlaybackSnapshot(state: SparseState, duration: number) { if (!window) return; const bounds = sparseBounds(index, duration); count++; + // Coverage includes exact-silent cores, but they bypass MOSS entirely and + // are not an ASR throughput sample. Including their cheap decode time makes + // later speech look artificially fast and understates likely buffering. + if (window.digitalSilence) return; totalMs += window.inferenceMs; inputSeconds += bounds.end - bounds.start; coreSeconds += bounds.coreEnd - bounds.coreStart; From 568378ba05094dea9bb25d6045f34d16785cc794 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:30:13 -0400 Subject: [PATCH 044/273] test(media): keep silence out of sparse ETA timing --- tests/media/sparse-playback-snapshot.test.mjs | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/tests/media/sparse-playback-snapshot.test.mjs b/tests/media/sparse-playback-snapshot.test.mjs index 90bba93e29..1c37e761db 100644 --- a/tests/media/sparse-playback-snapshot.test.mjs +++ b/tests/media/sparse-playback-snapshot.test.mjs @@ -16,10 +16,11 @@ function compare(state, duration) { snapshot = sparsePlaybackSnapshot(state, duration); assert.ok(Object.isFrozen(snapshot)); assert.equal(snapshot.cueDigest, cueDigest(safeSparseCues(state, duration))); - const samples = state.windows.flatMap((w, i) => - w ? [{ ...sparseBounds(i, duration), ms: w.inferenceMs }] : [] - ); - assert.equal(snapshot.count, samples.length); + const completed = state.windows.flatMap((w, i) => + w ? [{ ...sparseBounds(i, duration), ms: w.inferenceMs, digitalSilence: w.digitalSilence }] : [] + ), + samples = completed.filter((sample) => !sample.digitalSilence); + assert.equal(snapshot.count, completed.length); assert.equal( snapshot.totalMs, samples.reduce((n, s) => n + s.ms, 0) @@ -106,6 +107,17 @@ for (const policy of ['overlap-sparse-v1', 'overlap-sparse-v2']) { compare(state, 78); }); } +test('digital-silent coverage does not make the ASR throughput estimate look faster', () => { + const state = newSparseState(52); + state.windows[0] = { cues: [], inferenceMs: 52000 }; + state.windows[1] = { cues: [], inferenceMs: 250, digitalSilence: true }; + const snapshot = compare(state, 52), + first = sparseBounds(0, 52); + assert.equal(snapshot.count, 2, 'both completed cores still count as coverage'); + assert.equal(snapshot.totalMs, 52000); + assert.equal(snapshot.inputSeconds, first.end - first.start); + assert.equal(snapshot.coreSeconds, first.coreEnd - first.coreStart); +}); test('snapshot has no live dependence on its mutable input; a new notification recomputes', () => { const state = newSparseState(52); state.windows[0] = { cues: [cue('w0/cue-0', 2, 3)], inferenceMs: 17 }; From edc91112aae41da2cd2d65fbc7f96a0371d669f1 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:30:20 -0400 Subject: [PATCH 045/273] docs(media): keep silence out of recognition ETA --- docs/moss-progressive-transcription.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/moss-progressive-transcription.md b/docs/moss-progressive-transcription.md index d8f004466e..05e049877f 100644 --- a/docs/moss-progressive-transcription.md +++ b/docs/moss-progressive-transcription.md @@ -169,8 +169,8 @@ the identities and timing of matched accepted cues. Completed version-3 jobs are compacted after atomic track publication, so routine queue reads do not reload the complete window hypotheses. -The player measures decode plus warm inference time for each finished core, -excluding first-time model download/preparation, and estimates how +The player measures decode plus warm inference time for each finished **non-silent** core, +excluding first-time model download/preparation and exact-zero cores that bypass MOSS, and estimates how long it will take to build a 26-second caption lead. The estimate is updated as more windows finish; before the first window it says that it is estimating. If inference takes longer than one core of playback, the UI says captions may From 79a46a31da7d9d7996e97e7fa78d0b1bbbe3f7f0 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:30:33 -0400 Subject: [PATCH 046/273] fix(tracker): own pager geometry on Button roots --- .../book-reading-tracker-menu.svelte | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte index 62d862832b..0e58f39a3a 100644 --- a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte +++ b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte @@ -473,7 +473,8 @@ variant="ghost" size="icon" shape="circle" - class="tracker-history-page" + class="shrink-0" + style="inline-size:44px;block-size:44px;min-inline-size:44px;min-block-size:44px" aria-label="Previous history page" title="Previous Page" disabled={currentTrackingHistoryIndex === 0} @@ -493,7 +494,8 @@ variant="ghost" size="icon" shape="circle" - class="tracker-history-page" + class="shrink-0" + style="inline-size:44px;block-size:44px;min-inline-size:44px;min-block-size:44px" aria-label="Next history page" title="Next Page" disabled={!hasNextPage} @@ -520,12 +522,3 @@ {/if} - From 699c337cc49abf864a33a28284b58569df6f4b26 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:32:16 -0400 Subject: [PATCH 047/273] chore(video): format batch selection query --- apps/web/src/lib/media/workspace.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/apps/web/src/lib/media/workspace.ts b/apps/web/src/lib/media/workspace.ts index 2d0ca9d162..f305ea2e29 100644 --- a/apps/web/src/lib/media/workspace.ts +++ b/apps/web/src/lib/media/workspace.ts @@ -403,9 +403,7 @@ export class VideoWorkspace { } private updateSelectionActions() { - const visible = [ - ...this.shelf.querySelectorAll('input[type=checkbox]') - ]; + const visible = [...this.shelf.querySelectorAll('input[type=checkbox]')]; this.clearSelectionButton.disabled = this.selected.size === 0; this.bulkGenerateButton.disabled = this.selected.size === 0; this.selectVisibleButton.disabled = From 324d1114af98dfc9704c00d73e3406cb0c9bfbac Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:32:46 -0400 Subject: [PATCH 048/273] style(media): format sparse silence ETA test --- tests/media/sparse-playback-snapshot.test.mjs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/media/sparse-playback-snapshot.test.mjs b/tests/media/sparse-playback-snapshot.test.mjs index 1c37e761db..3ed3f76a60 100644 --- a/tests/media/sparse-playback-snapshot.test.mjs +++ b/tests/media/sparse-playback-snapshot.test.mjs @@ -17,7 +17,15 @@ function compare(state, duration) { assert.ok(Object.isFrozen(snapshot)); assert.equal(snapshot.cueDigest, cueDigest(safeSparseCues(state, duration))); const completed = state.windows.flatMap((w, i) => - w ? [{ ...sparseBounds(i, duration), ms: w.inferenceMs, digitalSilence: w.digitalSilence }] : [] + w + ? [ + { + ...sparseBounds(i, duration), + ms: w.inferenceMs, + digitalSilence: w.digitalSilence + } + ] + : [] ), samples = completed.filter((sample) => !sample.digitalSilence); assert.equal(snapshot.count, completed.length); From 667b99884381045c19526bcde65c6f4a9cdb805a Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:32:49 -0400 Subject: [PATCH 049/273] style(media): format sparse silence queue test --- tests/media/sparse-transcription.test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/media/sparse-transcription.test.mjs b/tests/media/sparse-transcription.test.mjs index 20302a0a94..961dd9ad51 100644 --- a/tests/media/sparse-transcription.test.mjs +++ b/tests/media/sparse-transcription.test.mjs @@ -288,7 +288,8 @@ test('a verified-zero neighbor removes a sparse halo hallucination without repai async prepare() {}, async transcribe() { inferred.push(1); - if (inferred.length > 1) throw Error('silence reconciliation must not start repair inference'); + if (inferred.length > 1) + throw Error('silence reconciliation must not start repair inference'); return '[3][S01]real speech[4][24][S01]silence hallucination[27]'; }, dispose() {} From a4032967ab226d347e4007da81af73284e01675c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Wed, 30 Sep 2026 18:32:54 -0400 Subject: [PATCH 050/273] fix(library): let Escape dismiss selection toolbar --- .../src/lib/components/book-card/book-manager-header.svelte | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/web/src/lib/components/book-card/book-manager-header.svelte b/apps/web/src/lib/components/book-card/book-manager-header.svelte index cae53102ef..26727b76f3 100644 --- a/apps/web/src/lib/components/book-card/book-manager-header.svelte +++ b/apps/web/src/lib/components/book-card/book-manager-header.svelte @@ -600,6 +600,11 @@ class:compact-selection={compactLibrary} class="library-selection-toolbar mx-auto flex min-h-14 max-w-6xl flex-wrap items-center gap-2 border-t border-border/60 px-[16px] py-[8px] sm:px-[24px]" aria-label="Book selection" + onkeydown={(event) => { + if (event.key !== 'Escape' || event.isComposing || event.altKey) return; + event.preventDefault(); + void exitSelectionMode(); + }} > + From 836faddfdbf5a56735749138dc0e10c3926c0995 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:00:42 -0400 Subject: [PATCH 199/273] fix(audio): accept optional SwiftF0 window duration --- apps/web/src/lib/features/whispersync/pitch/analysis.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/lib/features/whispersync/pitch/analysis.ts b/apps/web/src/lib/features/whispersync/pitch/analysis.ts index 55ada318d2..1591b242b1 100644 --- a/apps/web/src/lib/features/whispersync/pitch/analysis.ts +++ b/apps/web/src/lib/features/whispersync/pitch/analysis.ts @@ -25,7 +25,7 @@ export const SAMPLE_INTERVAL_MS = 256; export const SWIFT_F0_EMIT_STRIDE = 2; const SILENCE_PEAK = 1e-3; -const finite = (value: number, fallback = 0) => (Number.isFinite(value) ? value : fallback); +const finite = (value: number | undefined, fallback = 0) =>\n Number.isFinite(value) ? (value as number) : fallback; const clamp = (value: number, minimum: number, maximum: number) => Math.min(maximum, Math.max(minimum, value)); const sinc = (value: number) => From 6f33a4299d519dbef151e40bc9fa7425d7418b0f Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:00:45 -0400 Subject: [PATCH 200/273] style(audio): format SwiftF0 context bound --- apps/web/src/lib/features/whispersync/pitch/browser.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/web/src/lib/features/whispersync/pitch/browser.ts b/apps/web/src/lib/features/whispersync/pitch/browser.ts index f85df05238..0622a4c532 100644 --- a/apps/web/src/lib/features/whispersync/pitch/browser.ts +++ b/apps/web/src/lib/features/whispersync/pitch/browser.ts @@ -7,8 +7,7 @@ import { PitchController } from './controller'; import type { PitchState } from './model'; const MIN_CONTEXT_SECONDS = - (SWIFT_F0_LEFT_CONTEXT_FRAMES + 1 + SWIFT_F0_LOOKAHEAD_FRAMES) * - SWIFT_F0_FRAME_SECONDS; + (SWIFT_F0_LEFT_CONTEXT_FRAMES + 1 + SWIFT_F0_LOOKAHEAD_FRAMES) * SWIFT_F0_FRAME_SECONDS; const MAX_ANALYSIS_CONTEXT_RATE = Math.floor(32768 / MIN_CONTEXT_SECONDS); function createAudioContext() { From af5ddaaf327222682f1aa244abb56b66afce6154 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:00:46 -0400 Subject: [PATCH 201/273] test(snippets): preserve concurrent captures and committed append --- test/snippets/browser.mjs | 168 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) diff --git a/test/snippets/browser.mjs b/test/snippets/browser.mjs index aa38d0a5f3..b6a8ab1d56 100644 --- a/test/snippets/browser.mjs +++ b/test/snippets/browser.mjs @@ -257,6 +257,174 @@ try { await expect(page.getByRole('article', { name: 'Snippet content' })).toContainText('京都'); passed('create, durable native IndexedDB save and reader reload'); + // Every deliberate capture is persisted before presentation. Dispatch both + // in the same task so the second event exercises the first capture's busy + // suspension rather than only the already-open dialog path. + const capturePrefix = 'capture-durability-' + Date.now(); + const draftCount = async () => + (await records(page, 'snippetDrafts')).filter((draft) => + draft.document?.source?.item?.startsWith(capturePrefix) + ).length; + await page.evaluate((capturePrefix) => { + const dispatch = (suffix, html) => + window.dispatchEvent( + new CustomEvent('manabi-capture-snippet', { + detail: { + html, + title: 'Concurrent capture source', + item: capturePrefix + '-' + suffix, + owner: null + } + }) + ); + dispatch('first', '

最初の選択は開いたダイアログで処理します。

'); + dispatch('second', '

二番目の選択も失わず後で復元します。

'); + }, capturePrefix); + const captureDialog = page.getByRole('dialog', { name: 'Add to snippet' }); + await expect(captureDialog).toBeVisible(); + await expect.poll(draftCount).toBe(2); + await expect(captureDialog.getByRole('status')).toContainText( + '1 additional selection saved for later.' + ); + await captureDialog.getByRole('button', { name: 'Keep for later', exact: true }).click(); + await expect(captureDialog).toHaveCount(0); + await expect(page.getByRole('status')).toContainText('1 additional selection saved for later.'); + await page.reload(); + await expect.poll(draftCount).toBe(2); + const capturedDrafts = (await records(page, 'snippetDrafts')).filter((draft) => + draft.document?.source?.item?.startsWith(capturePrefix) + ); + assert.deepEqual(capturedDrafts.map((draft) => draft.document.source.item).sort(), [ + capturePrefix + '-first', + capturePrefix + '-second' + ]); + assert( + capturedDrafts.some((draft) => + JSON.stringify(draft.document.content).includes('最初の選択は開いたダイアログで処理します。') + ) + ); + assert( + capturedDrafts.some((draft) => + JSON.stringify(draft.document.content).includes('二番目の選択も失わず後で復元します。') + ) + ); + const deleteDraftKeys = (keys) => + page.evaluate( + async (keys) => + new Promise((resolve, reject) => { + const open = indexedDB.open('manabi-reader-integrations'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const db = open.result; + const tx = db.transaction('snippetDrafts', 'readwrite'); + for (const key of keys) tx.objectStore('snippetDrafts').delete(key); + tx.onerror = () => reject(tx.error); + tx.oncomplete = () => { + db.close(); + resolve(); + }; + }; + }), + keys + ); + await deleteDraftKeys(capturedDrafts.map((draft) => draft.key)); + passed('concurrent captures persist independently before destination UI'); + + // A failing first capture must not hide or discard a second capture admitted + // during the same busy window. + const mixedPrefix = 'capture-mixed-outcome-' + Date.now(); + await page.evaluate((mixedPrefix) => { + const dispatch = (suffix, html) => + window.dispatchEvent( + new CustomEvent('manabi-capture-snippet', { + detail: { + html, + title: 'Mixed capture source', + item: mixedPrefix + '-' + suffix, + owner: null + } + }) + ); + dispatch('too-large', '

' + 'x'.repeat(2 * 1024 * 1024 + 1) + '

'); + dispatch('saved', '

先の選択が失敗しても、この選択は下書きに残します。

'); + }, mixedPrefix); + const mixedDrafts = async () => + (await records(page, 'snippetDrafts')).filter((draft) => + draft.document?.source?.item?.startsWith(mixedPrefix) + ); + await expect.poll(async () => (await mixedDrafts()).length).toBe(1); + await expect(page.getByRole('dialog', { name: 'Add to snippet' })).toHaveCount(0); + const captureNotice = page.getByRole('alert'); + await expect(captureNotice).toContainText('Pasted content exceeds the 2 MiB limit.'); + await expect(captureNotice).toContainText('1 additional selection saved for later.'); + const [mixedDraft] = await mixedDrafts(); + assert.equal(mixedDraft.document.source.item, mixedPrefix + '-saved'); + assert(JSON.stringify(mixedDraft.document.content).includes('この選択は下書きに残します。')); + await deleteDraftKeys([mixedDraft.key]); + await captureNotice.getByRole('button', { name: 'Dismiss', exact: true }).click(); + passed('a failed capture cannot hide or discard a concurrent persisted capture'); + + // A committed append must not be reported as failed merely because best-effort + // cleanup of its already-durable capture draft failed. + const cleanupPrefix = 'capture-cleanup-failure-' + Date.now(); + await page.evaluate((cleanupPrefix) => { + window.dispatchEvent( + new CustomEvent('manabi-capture-snippet', { + detail: { + html: '

追加は成功し、下書き削除だけ失敗します。

', + title: 'Cleanup failure source', + item: cleanupPrefix, + owner: null + } + }) + ); + }, cleanupPrefix); + const cleanupDialog = page.getByRole('dialog', { name: 'Add to snippet' }); + await expect(cleanupDialog).toBeVisible(); + await expect + .poll( + async () => + (await records(page, 'snippetDrafts')).filter( + (draft) => draft.document?.source?.item === cleanupPrefix + ).length + ) + .toBe(1); + await page.evaluate(() => { + const original = globalThis.IDBObjectStore.prototype.delete; + let armed = true; + globalThis.IDBObjectStore.prototype.delete = function (key) { + if (armed && this.name === 'snippetDrafts') { + armed = false; + globalThis.IDBObjectStore.prototype.delete = original; + throw new globalThis.DOMException('Injected capture cleanup failure', 'AbortError'); + } + return original.call(this, key); + }; + }); + await cleanupDialog.getByRole('link', { name: '散歩の記録', exact: true }).click(); + await expect(cleanupDialog).toHaveCount(0); + const cleanupNotice = page + .getByRole('status') + .filter({ hasText: 'Added to snippet. The saved capture draft could not be cleaned up' }); + await expect(cleanupNotice).toBeVisible(); + await expect + .poll(async () => { + const item = (await records(page)).find((record) => record.document.id === id); + return ( + JSON.stringify(item?.document.content ?? {}).match( + /追加は成功し、下書き削除だけ失敗します。/g + )?.length ?? 0 + ); + }) + .toBe(1); + const cleanupDrafts = (await records(page, 'snippetDrafts')).filter( + (draft) => draft.document?.source?.item === cleanupPrefix + ); + assert.equal(cleanupDrafts.length, 1, 'Failed cleanup keeps the capture draft recoverable.'); + await deleteDraftKeys(cleanupDrafts.map((draft) => draft.key)); + await cleanupNotice.getByRole('button', { name: 'Dismiss', exact: true }).click(); + passed('committed capture append survives draft cleanup failure without inviting a retry'); + // Stress the actual reader controls and vertical layout at enlarged UI text. await page.setViewportSize({ width: 320, height: 480 }); await page.evaluate(() => { From d6cf74747545b9b85d81a2672a4cc736f9ca8c42 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:00:48 -0400 Subject: [PATCH 202/273] style(audio): format pitch help copy --- .../src/lib/features/whispersync/pitch/pitch-strip.svelte | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/src/lib/features/whispersync/pitch/pitch-strip.svelte b/apps/web/src/lib/features/whispersync/pitch/pitch-strip.svelte index a522fbef14..8acd76b5c4 100644 --- a/apps/web/src/lib/features/whispersync/pitch/pitch-strip.svelte +++ b/apps/web/src/lib/features/whispersync/pitch/pitch-strip.svelte @@ -113,9 +113,9 @@ Yellow follows the dialogue’s estimated pitch; the shaded waveform shows the mixed audio level. Pausing holds the trace. Seeking starts a new one. Gaps can mean silence, unvoiced speech, or a pitch outside 85–520 Hz. Analysis pauses between timed subtitle cues so - background sound is less likely to be mistaken for dialogue. Simultaneous music or - another speaker can still affect the estimate. This is a listening aid, not a pitch-accent - score. Audio stays on your device. + background sound is less likely to be mistaken for dialogue. Simultaneous music or another + speaker can still affect the estimate. This is a listening aid, not a pitch-accent score. + Audio stays on your device.

{/if} From 20cea70bc50c8707ca384655ea1a0a1d6955567e Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:00:50 -0400 Subject: [PATCH 203/273] style(audio): format empty SwiftF0 result --- apps/web/src/lib/features/whispersync/pitch/swift-f0.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/web/src/lib/features/whispersync/pitch/swift-f0.ts b/apps/web/src/lib/features/whispersync/pitch/swift-f0.ts index b5225207f0..869561450c 100644 --- a/apps/web/src/lib/features/whispersync/pitch/swift-f0.ts +++ b/apps/web/src/lib/features/whispersync/pitch/swift-f0.ts @@ -32,8 +32,7 @@ export async function analyseSwiftF0Window( rate: number ): Promise { const samples = resampleForSwiftF0(input, rate); - if (!samples.length) - return []; + if (!samples.length) return []; const session = await prepareSwiftF0(); const tensorSession: SwiftF0SessionLike = { From 5e276b12ef62ab0a76c688d18b102be42b9ed5a1 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:00:53 -0400 Subject: [PATCH 204/273] style(audio): format SwiftF0 regressions --- test/pitch/pitch.test.mjs | 82 ++++++++++++++++++++++++++++++++++----- 1 file changed, 72 insertions(+), 10 deletions(-) diff --git a/test/pitch/pitch.test.mjs b/test/pitch/pitch.test.mjs index fe0ba2e06e..77c8e2bf7a 100644 --- a/test/pitch/pitch.test.mjs +++ b/test/pitch/pitch.test.mjs @@ -94,7 +94,9 @@ test('SwiftF0 batches stable frames at 32 ms spacing while retaining future cont assert.ok(results[0].offsetSeconds >= 11 * SWIFT_F0_FRAME_SECONDS); assert.ok(results.at(-1).offsetSeconds <= ANALYSIS_WINDOW_SECONDS - 0.15); for (let index = 1; index < results.length; index++) { - assert.ok(Math.abs(results[index].offsetSeconds - results[index - 1].offsetSeconds - 0.032) < 1e-9); + assert.ok( + Math.abs(results[index].offsetSeconds - results[index - 1].offsetSeconds - 0.032) < 1e-9 + ); } }); test('live inference cadence is aligned to multiple emitted pitch frames', () => { @@ -163,7 +165,11 @@ test('SwiftF0 runtime releases feeds after failure and rejects malformed model o const samples = tone(220, 16000); await assert.rejects( runSwiftF0Inference( - { run: async () => { throw new Error('inference failed'); } }, + { + run: async () => { + throw new Error('inference failed'); + } + }, (type, data, dims) => new Tensor(type, data, dims), samples, 85, @@ -518,8 +524,22 @@ test('overlapping result batches append only newly stable timestamps', async () type: 'result', id: id1, results: [ - { hz: 220, amplitude: 0.4, confidence: 1, rms: 0.3, offsetSeconds: 0.256, windowSeconds: ANALYSIS_WINDOW_SECONDS }, - { hz: 221, amplitude: 0.4, confidence: 1, rms: 0.3, offsetSeconds: 0.288, windowSeconds: ANALYSIS_WINDOW_SECONDS } + { + hz: 220, + amplitude: 0.4, + confidence: 1, + rms: 0.3, + offsetSeconds: 0.256, + windowSeconds: ANALYSIS_WINDOW_SECONDS + }, + { + hz: 221, + amplitude: 0.4, + confidence: 1, + rms: 0.3, + offsetSeconds: 0.288, + windowSeconds: ANALYSIS_WINDOW_SECONDS + } ] } }); @@ -535,8 +555,22 @@ test('overlapping result batches append only newly stable timestamps', async () id: id2, results: [ // This maps to the previous window's last absolute timestamp. - { hz: 221, amplitude: 0.4, confidence: 1, rms: 0.3, offsetSeconds: 0.032, windowSeconds: ANALYSIS_WINDOW_SECONDS }, - { hz: 222, amplitude: 0.4, confidence: 1, rms: 0.3, offsetSeconds: 0.064, windowSeconds: ANALYSIS_WINDOW_SECONDS } + { + hz: 221, + amplitude: 0.4, + confidence: 1, + rms: 0.3, + offsetSeconds: 0.032, + windowSeconds: ANALYSIS_WINDOW_SECONDS + }, + { + hz: 222, + amplitude: 0.4, + confidence: 1, + rms: 0.3, + offsetSeconds: 0.064, + windowSeconds: ANALYSIS_WINDOW_SECONDS + } ] } }); @@ -708,8 +742,22 @@ test('first subtitle synchronization establishes a cue boundary even when speech type: 'result', id, results: [ - { hz: 110, amplitude: 0.3, confidence: 1, rms: 0.2, offsetSeconds: 0.1, windowSeconds: ANALYSIS_WINDOW_SECONDS }, - { hz: 220, amplitude: 0.3, confidence: 1, rms: 0.2, offsetSeconds: 0.6, windowSeconds: ANALYSIS_WINDOW_SECONDS } + { + hz: 110, + amplitude: 0.3, + confidence: 1, + rms: 0.2, + offsetSeconds: 0.1, + windowSeconds: ANALYSIS_WINDOW_SECONDS + }, + { + hz: 220, + amplitude: 0.3, + confidence: 1, + rms: 0.2, + offsetSeconds: 0.6, + windowSeconds: ANALYSIS_WINDOW_SECONDS + } ] } }); @@ -732,8 +780,22 @@ test('active cue boundary can advance without requiring a subtitle gap', async ( type: 'result', id, results: [ - { hz: 180, amplitude: 0.4, confidence: 1, rms: 0.3, offsetSeconds: 0.2, windowSeconds: ANALYSIS_WINDOW_SECONDS }, - { hz: 220, amplitude: 0.4, confidence: 1, rms: 0.3, offsetSeconds: 0.6, windowSeconds: ANALYSIS_WINDOW_SECONDS } + { + hz: 180, + amplitude: 0.4, + confidence: 1, + rms: 0.3, + offsetSeconds: 0.2, + windowSeconds: ANALYSIS_WINDOW_SECONDS + }, + { + hz: 220, + amplitude: 0.4, + confidence: 1, + rms: 0.3, + offsetSeconds: 0.6, + windowSeconds: ANALYSIS_WINDOW_SECONDS + } ] } }); From 96494e53270845cfc5a6f4f5d07fa4f0adac1db4 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:01:48 -0400 Subject: [PATCH 205/273] refactor(epub): centralize page progression direction policy --- .../book-reader-paginated.svelte | 3 +- .../src/lib/foliate-epub/page-direction.ts | 29 ++++++++ apps/web/src/lib/foliate-epub/paginator.js | 13 ++-- tests/unit/foliate-page-direction.test.mjs | 70 +++++++++++++++++++ 4 files changed, 108 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/lib/foliate-epub/page-direction.ts create mode 100644 tests/unit/foliate-page-direction.test.mjs diff --git a/apps/web/src/lib/components/book-reader/book-reader-paginated/book-reader-paginated.svelte b/apps/web/src/lib/components/book-reader/book-reader-paginated/book-reader-paginated.svelte index e4fe7563ec..392b20201a 100644 --- a/apps/web/src/lib/components/book-reader/book-reader-paginated/book-reader-paginated.svelte +++ b/apps/web/src/lib/components/book-reader/book-reader-paginated/book-reader-paginated.svelte @@ -18,6 +18,7 @@ import { observeReaderFontLayout } from '$lib/functions/reader-font-layout'; import { FuriganaStyle } from '$lib/data/furigana-style'; import type { PageDirection } from '$lib/library/direction'; + import { reversesPhysicalPageTurns } from '$lib/foliate-epub/page-direction'; import { disableWheelNavigation$, firstDimensionMargin$, @@ -236,7 +237,7 @@ // The legacy paginator remains the production fallback while Foliate is gated. // Keep reading order separate from paragraph bidi direction here too. - $: reversePageOrder = verticalMode || (!verticalMode && pageDirection === 'rtl'); + $: reversePageOrder = reversesPhysicalPageTurns(verticalMode, pageDirection); $: { if (htmlContent) { diff --git a/apps/web/src/lib/foliate-epub/page-direction.ts b/apps/web/src/lib/foliate-epub/page-direction.ts new file mode 100644 index 0000000000..a84e026f24 --- /dev/null +++ b/apps/web/src/lib/foliate-epub/page-direction.ts @@ -0,0 +1,29 @@ +/** + * @license BSD-3-Clause + * Copyright (c) 2026, ッツ Reader Authors + * All rights reserved. + */ + +export function paginatedPageRtl({ + flow, + vertical, + bookDirection, + contentRtl +}: { + flow: string | null; + vertical: boolean; + bookDirection?: string; + contentRtl: boolean; +}): boolean { + if (flow === 'scrolled' || vertical) return contentRtl; + if (bookDirection === 'rtl') return true; + if (bookDirection === 'ltr') return false; + return contentRtl; +} + +export function reversesPhysicalPageTurns( + vertical: boolean, + pageDirection: 'ltr' | 'rtl' | 'unknown' | undefined +): boolean { + return vertical || (!vertical && pageDirection === 'rtl'); +} diff --git a/apps/web/src/lib/foliate-epub/paginator.js b/apps/web/src/lib/foliate-epub/paginator.js index 9bc21ae99b..788c75b332 100644 --- a/apps/web/src/lib/foliate-epub/paginator.js +++ b/apps/web/src/lib/foliate-epub/paginator.js @@ -2,6 +2,7 @@ // See LICENSE.foliate-js.txt in this directory. import { slideGeometry } from './slide-geometry.ts' import { PageCountCache, pageNumber, pageNumberLabel } from './page-counts.ts' +import { paginatedPageRtl } from './page-direction.ts' const wait = ms => new Promise(resolve => setTimeout(resolve, ms)) @@ -803,12 +804,12 @@ export class Paginator extends HTMLElement { cancelAnimationFrame(this.#resizeFrame) this.#resizeFrame = 0 const flow = this.getAttribute('flow') - const pageRtl = - flow !== 'scrolled' && !vertical && this.bookDir === 'rtl' - ? true - : flow !== 'scrolled' && !vertical && this.bookDir === 'ltr' - ? false - : rtl + const pageRtl = paginatedPageRtl({ + flow, + vertical, + bookDirection: this.bookDir, + contentRtl: rtl, + }) this.#vertical = vertical this.#contentRtl = rtl this.#rtl = pageRtl diff --git a/tests/unit/foliate-page-direction.test.mjs b/tests/unit/foliate-page-direction.test.mjs new file mode 100644 index 0000000000..e3857cb71a --- /dev/null +++ b/tests/unit/foliate-page-direction.test.mjs @@ -0,0 +1,70 @@ +/** + * @license BSD-3-Clause + * Copyright (c) 2026, ッツ Reader Authors + * All rights reserved. + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + paginatedPageRtl, + reversesPhysicalPageTurns +} from '../../apps/web/src/lib/foliate-epub/page-direction.ts'; + +test('explicit horizontal page progression outranks content bidi direction', () => { + assert.equal( + paginatedPageRtl({ + flow: 'paginated', + vertical: false, + bookDirection: 'rtl', + contentRtl: false + }), + true + ); + assert.equal( + paginatedPageRtl({ + flow: 'paginated', + vertical: false, + bookDirection: 'ltr', + contentRtl: true + }), + false + ); +}); + +test('missing horizontal progression uses authored content direction', () => { + assert.equal( + paginatedPageRtl({ + flow: 'paginated', + vertical: false, + contentRtl: true + }), + true + ); + assert.equal( + paginatedPageRtl({ + flow: 'paginated', + vertical: false, + bookDirection: 'default', + contentRtl: false + }), + false + ); +}); + +test('vertical and scrolled flows retain content direction rather than forcing horizontal progression', () => { + for (const input of [ + { flow: 'paginated', vertical: true, bookDirection: 'ltr', contentRtl: true }, + { flow: 'paginated', vertical: true, bookDirection: 'rtl', contentRtl: false }, + { flow: 'scrolled', vertical: false, bookDirection: 'rtl', contentRtl: false }, + { flow: 'scrolled', vertical: false, bookDirection: 'ltr', contentRtl: true } + ]) + assert.equal(paginatedPageRtl(input), input.contentRtl); +}); + +test('legacy physical keys and swipes follow the same horizontal page direction contract', () => { + assert.equal(reversesPhysicalPageTurns(false, 'rtl'), true); + assert.equal(reversesPhysicalPageTurns(false, 'ltr'), false); + assert.equal(reversesPhysicalPageTurns(false, 'unknown'), false); + assert.equal(reversesPhysicalPageTurns(true, 'ltr'), true); + assert.equal(reversesPhysicalPageTurns(true, 'unknown'), true); +}); From 76c85ef3540fdb9b130cb373d8800baa21aff2dd Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:03:20 -0400 Subject: [PATCH 206/273] fix(search): document resolved shallow URL for navigation lint --- apps/web/src/lib/library/library-workspace.svelte | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/lib/library/library-workspace.svelte b/apps/web/src/lib/library/library-workspace.svelte index b9bfb53fdc..ea39e20157 100644 --- a/apps/web/src/lib/library/library-workspace.svelte +++ b/apps/web/src/lib/library/library-workspace.svelte @@ -580,6 +580,8 @@ // q/scope are local presentation state for this already-mounted route. // Shallow replacement keeps the address bar/shareability in sync without // starting SvelteKit navigation work on each keystroke or filter change. + // The base path is resolved above; q/scope/hash are already-normalized presentation state. + // eslint-disable-next-line svelte/no-navigation-without-resolve replaceState(`${resolve('/manage')}${url.search}${url.hash}`, $page.state); } function setQuery(value: string) { From 79a628989b2d615f872ad40ed820839499b45a0f Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:04:31 -0400 Subject: [PATCH 207/273] test(epub): qualify consecutive illustration-only sections --- tests/browser/test_epub_publication.py | 91 ++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/tests/browser/test_epub_publication.py b/tests/browser/test_epub_publication.py index 750f27c7bb..e2a5e398ec 100644 --- a/tests/browser/test_epub_publication.py +++ b/tests/browser/test_epub_publication.py @@ -58,6 +58,39 @@ def resource_epub(malformed=False): return output.getvalue() +def illustration_epub(): + output = io.BytesIO() + svg = ''' + + ''' + package = f''' +{TITLE}ja + + + + + +''' + start = ''' +

挿絵の前

挿絵へ''' + image1 = '''

+First illustration

''' + image2 = '''

+Second illustration

''' + with zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as archive: + archive.writestr('mimetype', 'application/epub+zip') + archive.writestr( + 'META-INF/container.xml', + '' + ) + archive.writestr('book.opf', package) + archive.writestr('start.xhtml', start) + archive.writestr('image1.xhtml', image1) + archive.writestr('image2.xhtml', image2) + archive.writestr('plate.svg', svg) + return output.getvalue() + + def deep_fragment_epub(): """Put the linked target well past page one so chapter-start navigation cannot pass.""" output = io.BytesIO() @@ -248,6 +281,64 @@ def open_resource_book(self, view='paginated', malformed=False, payload=None, fo else: expect(self.page.locator('#ttu-epub-0 .text')).to_be_visible(timeout=30000) + def test_foliate_consecutive_illustration_sections_are_single_visible_pages(self): + self.page.set_viewport_size({'width': 390, 'height': 844}) + self.open_resource_book(payload=illustration_epub()) + result = self.page.evaluate(f"""async () => {{ + const p={P}; + const check=async(index,id)=>{{ + if(!(await p.goTo({{index}}))) throw Error('Failed illustration navigation'); + await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))); + const doc=p.getContents()[0].doc, image=doc.getElementById(id); + const ir=image.getBoundingClientRect(), pr=p.getBoundingClientRect(); + return {{index:p.getContents()[0].index,pages:p.pages-2, + visible:ir.width>0&&ir.height>0&&ir.right>0&&ir.bottom>0&&ir.left + document.querySelector('.book-content-container')?.dataset.manabiSpineIndex === '1' + && document.querySelector('#plate1')?.naturalWidth > 0""") + first = self.page.evaluate("""() => { + const host=document.querySelector('.book-content').getBoundingClientRect(); + const image=document.querySelector('#plate1').getBoundingClientRect(); + return {visible:image.width>0&&image.height>0&&image.right>host.left&&image.lefthost.top&&image.top + document.querySelector('.book-content-container')?.dataset.manabiSpineIndex === '2' + && document.querySelector('#plate2')?.naturalWidth > 0""") + second = self.page.evaluate("""() => { + const host=document.querySelector('.book-content').getBoundingClientRect(); + const image=document.querySelector('#plate2').getBoundingClientRect(); + return {visible:image.width>0&&image.height>0&&image.right>host.left&&image.lefthost.top&&image.top Date: Thu, 1 Oct 2026 16:06:12 -0400 Subject: [PATCH 208/273] fix(snippets): preserve safe link semantics in HTML Markdown fallback --- apps/web/src/lib/snippets/editor.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/lib/snippets/editor.ts b/apps/web/src/lib/snippets/editor.ts index c5d3dc187e..6e3687dc4c 100644 --- a/apps/web/src/lib/snippets/editor.ts +++ b/apps/web/src/lib/snippets/editor.ts @@ -95,7 +95,7 @@ export function cleanHTML(html: string): string { 'rp', 'span' ], - ALLOWED_ATTR: ['href', 'title', 'start', 'type', 'data-id'], + ALLOWED_ATTR: ['href', 'title', 'target', 'rel', 'start', 'type', 'data-id'], ALLOW_DATA_ATTR: false, ADD_URI_SAFE_ATTR: ['data-id', 'start', 'type', 'title'], FORBID_TAGS: [ From 1d1ec32f634c75b8d14c7d587a14b3de7d8672e7 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:06:15 -0400 Subject: [PATCH 209/273] fix(snippets): restrict persisted link rel tokens --- apps/web/src/lib/snippets/document.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/snippets/document.ts b/apps/web/src/lib/snippets/document.ts index 7e29337b8d..cd8c2129c6 100644 --- a/apps/web/src/lib/snippets/document.ts +++ b/apps/web/src/lib/snippets/document.ts @@ -94,6 +94,14 @@ const validText = (value: unknown, length: number): value is string => value.length <= length && // eslint-disable-next-line no-control-regex -- reject unsafe control characters !/[\u0000\ud800-\udbff](?![\udc00-\udfff])|(? { + const tokens = value.trim().split(/\s+/).filter(Boolean); + return ( + tokens.length > 0 && + tokens.every((token) => ['noopener', 'noreferrer', 'nofollow'].includes(token)) && + new Set(tokens).size === tokens.length + ); +}; const blockTypes = new Set([ 'paragraph', 'heading', @@ -192,7 +200,17 @@ export function validateContent(value: unknown): asserts value is TextNode { fail(); if (mark.attrs.target != null && !['_blank', '_self'].includes(String(mark.attrs.target))) fail(); - if (mark.attrs.rel != null && !validText(mark.attrs.rel, 120)) fail(); + if ( + mark.attrs.rel != null && + (!validText(mark.attrs.rel, 120) || !safeLinkRel(String(mark.attrs.rel))) + ) + fail(); + if ( + mark.attrs.target === '_blank' && + mark.attrs.rel != null && + !String(mark.attrs.rel).split(/\s+/).includes('noopener') + ) + fail(); if ( mark.attrs.class != null || (mark.attrs.title != null && !validText(mark.attrs.title, 1000)) From 213656f633d2efd156ea0038fe1b45999275f776 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:06:31 -0400 Subject: [PATCH 210/273] test(snippets): verify safe link Markdown round trip --- tests/unit/snippet-markdown-safety.test.mjs | 73 +++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/tests/unit/snippet-markdown-safety.test.mjs b/tests/unit/snippet-markdown-safety.test.mjs index cdc3f4487b..fd2932d376 100644 --- a/tests/unit/snippet-markdown-safety.test.mjs +++ b/tests/unit/snippet-markdown-safety.test.mjs @@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto'; import test from 'node:test'; import { exportMarkdown, + importContent, markdownHTML, requiresHTMLMarkdown } from '../../apps/web/src/lib/snippets/editor.ts'; @@ -202,6 +203,78 @@ test('lossless fallback emits HTML that preserves underline and list marker type assert.match(markdown, />alpha { + const content = { + type: 'doc', + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [ + { + type: 'text', + text: 'safe link', + marks: [ + { + type: 'link', + attrs: { + href: 'https://example.com/', + target: '_self', + rel: 'noopener', + class: null, + title: 'Example' + } + } + ] + } + ] + } + ] + }; + const markdown = exportMarkdown(content); + assert.match(markdown, /target="_self"/); + assert.match(markdown, /rel="noopener"/); + const imported = importContent(markdown, 'markdown'); + const link = imported.content[0].content[0].marks.find((mark) => mark.type === 'link'); + assert.equal(link.attrs.href, 'https://example.com/'); + assert.equal(link.attrs.target, '_self'); + assert.equal(link.attrs.rel, 'noopener'); + assert.equal(link.attrs.title, 'Example'); +}); + +test('snippet schema rejects unsafe link rel tokens and opener semantics', () => { + const unsafe = { + type: 'doc', + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [ + { + type: 'text', + text: 'unsafe', + marks: [ + { + type: 'link', + attrs: { + href: 'https://example.com/', + target: '_blank', + rel: 'opener', + class: null, + title: null + } + } + ] + } + ] + } + ] + }; + assert.throws(() => validateContent(unsafe)); + unsafe.content[0].content[0].marks[0].attrs.rel = 'noopener noreferrer'; + assert.doesNotThrow(() => validateContent(unsafe)); +}); + test('fenced code containing list-like prose is not treated as a list', () => { const markdown = ['```text', 'Hi. there', '0. zero', '```'].join('\n'); const html = markdownHTML(markdown); From 84438ca43500708e201ecd912332eb529480d2d8 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:10:07 -0400 Subject: [PATCH 211/273] chore: sync current main library route fix --- apps/web/src/lib/library/library-workspace.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/lib/library/library-workspace.svelte b/apps/web/src/lib/library/library-workspace.svelte index b93d3fcf96..b9bfb53fdc 100644 --- a/apps/web/src/lib/library/library-workspace.svelte +++ b/apps/web/src/lib/library/library-workspace.svelte @@ -580,7 +580,7 @@ // q/scope are local presentation state for this already-mounted route. // Shallow replacement keeps the address bar/shareability in sync without // starting SvelteKit navigation work on each keystroke or filter change. - replaceState(resolve(`/manage${url.search}${url.hash}`), $page.state); + replaceState(`${resolve('/manage')}${url.search}${url.hash}`, $page.state); } function setQuery(value: string) { query = queryURL = value; From ba27b680b37586163114f289e55a83d10dac1c8c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:19:57 -0400 Subject: [PATCH 212/273] test(snippets): strengthen enlarged selection actionability --- test/snippets/browser.mjs | 77 +++++++++++++++++++++++++++++---------- 1 file changed, 57 insertions(+), 20 deletions(-) diff --git a/test/snippets/browser.mjs b/test/snippets/browser.mjs index 2421c117e3..0895b177f0 100644 --- a/test/snippets/browser.mjs +++ b/test/snippets/browser.mjs @@ -445,47 +445,84 @@ try { (await enlargedBatch.evaluate((node) => node.scrollWidth - node.clientWidth)) <= 1, 'Snippet batch actions must not overflow horizontally at 200% text' ); + const batchBox = await enlargedBatch.boundingBox(); + assert( + batchBox.x >= -1 && batchBox.x + batchBox.width <= 321, + 'Snippet batch toolbar must remain inside the narrow viewport' + ); const batchStatus = enlargedBatch.getByRole('status'); await expect(batchStatus).toHaveAttribute('aria-atomic', 'true'); await expect(batchStatus).toHaveText('0 selected'); - const enlargedSelection = page.getByRole('checkbox', { - name: 'Select 散歩の記録', + const selectAllLarge = enlargedBatch.getByRole('button', { + name: 'Select all visible', exact: true }); - await enlargedSelection.focus(); - await enlargedSelection.press('Space'); + await selectAllLarge.focus(); + await selectAllLarge.press('Enter'); await expect(batchStatus).toHaveText('1 selected'); + const enlargedSelection = page.getByRole('checkbox', { name: 'Select 散歩の記録', exact: true }); + await expect(enlargedSelection).toBeChecked(); + for (const name of [ + 'Select all visible', + 'Collections…', + 'Move to…', + 'Export selected', + 'Move to Trash' + ]) { + const control = enlargedBatch.getByRole('button', { name, exact: true }); + const box = await control.boundingBox(); + assert(box && box.height >= 43.5, `${name} must remain at least 44 CSS px high`); + assert(box.x >= -1 && box.x + box.width <= 321, `${name} must stay inside the viewport`); + } + if (largeTextEvidence) { + const selectionPath = largeTextEvidence.replace(/\.png$/i, '-selection-large-text.png'); + await page.screenshot({ path: selectionPath, fullPage: true }); + } - await page.setViewportSize({ width: 320, height: 320 }); - await enlargedSelection.scrollIntoViewIfNeeded(); - await enlargedSelection.press('Escape'); + await selectAllLarge.press('Escape'); await expect(enlargedBatch).toHaveCount(0); await expect(selectionToggleLarge).toHaveText('Select'); await expect(selectionToggleLarge).toBeFocused(); + + await selectionToggleLarge.press('Enter'); + const checkboxEscape = page.getByRole('checkbox', { name: 'Select 散歩の記録', exact: true }); + await checkboxEscape.focus(); + await checkboxEscape.press('Space'); + await expect( + page.getByRole('toolbar', { name: 'Selected snippet actions', exact: true }).getByRole('status') + ).toHaveText('1 selected'); + await page.setViewportSize({ width: 320, height: 320 }); + await checkboxEscape.scrollIntoViewIfNeeded(); + const beforeExit = await selectionToggleLarge.boundingBox(); + assert( + beforeExit.y < 0 || beforeExit.y + beforeExit.height > 321, + 'Short-viewport fixture must actually move the selection toggle offscreen' + ); + await checkboxEscape.press('Escape'); + await expect( + page.getByRole('toolbar', { name: 'Selected snippet actions', exact: true }) + ).toHaveCount(0); + await expect(selectionToggleLarge).toBeFocused(); const returnedToggle = await selectionToggleLarge.boundingBox(); assert( - returnedToggle && - returnedToggle.x >= -1 && + returnedToggle.x >= -1 && returnedToggle.y >= -1 && returnedToggle.x + returnedToggle.width <= 321 && returnedToggle.y + returnedToggle.height <= 321, `Selection exit must return visible focus: ${JSON.stringify(returnedToggle)}` ); - assert( - await selectionToggleLarge.evaluate((button) => { - const r = button.getBoundingClientRect(); - const hit = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); - return !!hit && (hit === button || button.contains(hit)); - }), - 'Selection exit target must be hit-testable after focus restoration' - ); - + await selectionToggleLarge.click({ trial: true }); await page.setViewportSize({ width: 320, height: 640 }); + await selectionToggleLarge.press('Enter'); - await expect(enlargedBatch).toBeVisible(); + await expect( + page.getByRole('toolbar', { name: 'Selected snippet actions', exact: true }) + ).toBeVisible(); await expect(selectionToggleLarge).toHaveText('Done selecting'); await selectionToggleLarge.press('Escape'); - await expect(enlargedBatch).toHaveCount(0); + await expect( + page.getByRole('toolbar', { name: 'Selected snippet actions', exact: true }) + ).toHaveCount(0); await expect(selectionToggleLarge).toHaveText('Select'); await expect(selectionToggleLarge).toBeFocused(); passed('snippet selection reflows and exits consistently by keyboard at 200% text'); From 2eddcbceb78963e502453391ab50319f8aafaad6 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:20:49 -0400 Subject: [PATCH 213/273] fix(storage): drain reader-annotation transactions from first request --- apps/web/src/lib/reader-annotations.ts | 38 +++++++------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/apps/web/src/lib/reader-annotations.ts b/apps/web/src/lib/reader-annotations.ts index 2294f1ac57..0cb6ffda48 100644 --- a/apps/web/src/lib/reader-annotations.ts +++ b/apps/web/src/lib/reader-annotations.ts @@ -13,6 +13,7 @@ import type { } from '$lib/data/database/books-db/versions/v7/books-db-v7'; import { snapshotReaderLocator } from '$lib/reader-location'; import { readIndexedBookMetadata } from '$lib/data/database/books-db/content-hash-index'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import { captureLibraryOperation } from '$lib/manabi/operation-scope'; export type AnnotationDraft = Pick & @@ -63,20 +64,13 @@ async function commitAnnotationTransaction( ): Promise { const unbind = bindTransactionLifetime(transaction, operation.signal); try { - const result = await work(); - operation.assertCurrent(); - await transaction.done; + const result = await commitTransaction(transaction, async () => { + const value = await work(); + operation.assertCurrent(); + return value; + }); operation.assertCurrent(); return result; - } catch (error) { - try { - transaction.abort(); - } catch { - /* The transaction may already have settled. */ - } - await transaction.done.catch(() => undefined); - operation.assertCurrent(); - throw error; } finally { unbind(); } @@ -165,13 +159,9 @@ async function bookAccounts( ): Promise> { const db = await database.db; const tx = db.transaction(['data', 'readerBookScope']); - const result = await bookAccountsFromStores( - bookKeys, - tx.objectStore('data'), - tx.objectStore('readerBookScope') + return commitTransaction(tx, () => + bookAccountsFromStores(bookKeys, tx.objectStore('data'), tx.objectStore('readerBookScope')) ); - await tx.done; - return result; } export interface ReaderAnnotationArchive { @@ -443,11 +433,7 @@ export async function resolveAnnotationImportConflict( await commitAnnotationTransaction(tx, operation, async () => { const conflict = await tx.objectStore('readerConflict').get(id); operation.assertCurrent(); - if (!conflict) { - await tx.done; - operation.assertCurrent(); - return; - } + if (!conflict) return; if (id !== `import:${conflict.local.id}`) throw new Error('Invalid archive conflict.'); const [existingOwner, current] = await Promise.all([ tx.objectStore('readerAnnotationScope').get(conflict.local.id), @@ -703,11 +689,7 @@ export async function removeReaderAnnotation( await commitAnnotationTransaction(tx, operation, async () => { const current = await tx.objectStore('readerAnnotation').get(id); operation.assertCurrent(); - if (!current || current.deletedAt) { - await tx.done; - operation.assertCurrent(); - return; - } + if (!current || current.deletedAt) return; const [owner, bookOwner] = await Promise.all([ tx.objectStore('readerAnnotationScope').get(id), bookAccountFromStores( From e7c8314ab12114bad7fcd00cbc4d4871e83c4253 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:20:55 -0400 Subject: [PATCH 214/273] refactor(snippets): share schema-safe text truncation --- apps/web/src/lib/snippets/document.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/web/src/lib/snippets/document.ts b/apps/web/src/lib/snippets/document.ts index 17774c277b..b965b8f6e7 100644 --- a/apps/web/src/lib/snippets/document.ts +++ b/apps/web/src/lib/snippets/document.ts @@ -14,6 +14,22 @@ export function snippetSearchTooLong(value: string) { return false; } export const isSnippetFile = (name: string) => name.toLowerCase().endsWith(SNIPPET_SUFFIX); +/** Apply schema UTF-16 bounds without manufacturing an unpaired surrogate. */ +export function truncateValidText(value: string, maximum: number): string { + if (!Number.isSafeInteger(maximum) || maximum < 0) throw new Error('Invalid text limit.'); + if (value.length <= maximum) return value; + let end = maximum; + if ( + end > 0 && + end < value.length && + value.charCodeAt(end - 1) >= 0xd800 && + value.charCodeAt(end - 1) <= 0xdbff && + value.charCodeAt(end) >= 0xdc00 && + value.charCodeAt(end) <= 0xdfff + ) + end--; + return value.slice(0, end); +} export const isUUID = (value: unknown): value is string => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value); From ce25a4828a6e5a20e90a46561a2fb56551342d23 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:20:59 -0400 Subject: [PATCH 215/273] refactor(snippets): use canonical provenance truncation --- apps/web/src/lib/snippets/capture.svelte | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/apps/web/src/lib/snippets/capture.svelte b/apps/web/src/lib/snippets/capture.svelte index 93f3dc6761..95005e0f5b 100644 --- a/apps/web/src/lib/snippets/capture.svelte +++ b/apps/web/src/lib/snippets/capture.svelte @@ -19,6 +19,7 @@ createSnippet, passages, snippetKey, + truncateValidText, type SnippetDocument, type TextNode } from './document'; @@ -47,21 +48,6 @@ captured: SnippetScope | undefined; $: choices = $snippetItems.filter((item) => !item.trashedAt && !item.transfer && !item.conflicts); - function boundedText(value: string, maximum: number) { - if (value.length <= maximum) return value; - let end = maximum; - const previous = value.charCodeAt(end - 1), - next = value.charCodeAt(end); - if ( - previous >= 0xd800 && - previous <= 0xdbff && - next >= 0xdc00 && - next <= 0xdfff - ) - end--; - return value.slice(0, end); - } - function capturePayload(event: Event): CapturePayload { const value = (event as CustomEvent).detail; if ( @@ -88,9 +74,9 @@ const text = importContent(value.html, 'html'); const created = createSnippet(text); created.source = { - title: boundedText(value.title, 1000), - item: boundedText(value.item, 1000), - quote: boundedText( + title: truncateValidText(value.title, 1000), + item: truncateValidText(value.item, 1000), + quote: truncateValidText( passages(text) .map((passage) => passage.text) .join('\n'), From 20357f894561de1a4d8566287f82f3d9fc694ca4 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:21:01 -0400 Subject: [PATCH 216/273] test(snippets): cover schema-safe provenance truncation --- test/snippets/unit.test.mjs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/snippets/unit.test.mjs b/test/snippets/unit.test.mjs index 3b11b8e9ce..c1c87731d9 100644 --- a/test/snippets/unit.test.mjs +++ b/test/snippets/unit.test.mjs @@ -22,6 +22,7 @@ import { MAX_SNIPPET_BYTES, MAX_SNIPPET_SEARCH_CODEPOINTS, snippetSearchTooLong, + truncateValidText, validateContent } from '../../apps/web/src/lib/snippets/document.ts'; import { @@ -113,6 +114,21 @@ async function stored(text = '元の文章', s = source()) { return { selected, doc, source: s }; } +test('bounded provenance truncation never splits a Unicode surrogate pair', () => { + const exact = 'a'.repeat(998) + '😀'; + assert.equal(exact.length, 1000); + assert.equal(truncateValidText(exact, 1000), exact); + + const crossing = 'a'.repeat(999) + '😀'; + const truncated = truncateValidText(crossing, 1000); + assert.equal(truncated, 'a'.repeat(999)); + assert.equal(truncated.length, 999); + assert.doesNotThrow(() => new TextEncoder().encode(truncated)); + assert.equal(truncateValidText('日本語', 2), '日本'); + assert.equal(truncateValidText('😀', 0), ''); + assert.throws(() => truncateValidText('x', -1), /Invalid text limit/); +}); + test('automatic titles exclude ruby and preserve Japanese graphemes', () => { const doc = ruby(); assert.equal(displayTitle(doc), '東京へ行く。'); From 3d28e2624e9f1e53d3a227a117d275f96a0b2fb5 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:22:21 -0400 Subject: [PATCH 217/273] fix(statistics): keep privacy blur off focus chrome --- .../statistics-summary/statistics-summary.svelte | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/apps/web/src/lib/components/statistics/statistics-summary/statistics-summary.svelte b/apps/web/src/lib/components/statistics/statistics-summary/statistics-summary.svelte index 314a71fe7d..ac4332f6fa 100644 --- a/apps/web/src/lib/components/statistics/statistics-summary/statistics-summary.svelte +++ b/apps/web/src/lib/components/statistics/statistics-summary/statistics-summary.svelte @@ -546,7 +546,6 @@ type="button" data-summary-metric="readingTime" class="min-h-[44px] rounded-lg px-2 py-2 text-left focus-visible:outline-2 focus-visible:outline-ring" - class:blur={$lastBlurredTrackerItems$.has('readingTime')} aria-pressed={$lastBlurredTrackerItems$.has('readingTime')} aria-label={metricAccessibleLabel('readingTime', 'Reading time', readingTimeValue)} on:click={(event) => @@ -558,7 +557,7 @@ )} min` ])} > - {readingTimeValue} + {readingTimeValue} {/if} {#if currentRowInEdit} @@ -580,7 +579,6 @@ type="button" data-summary-metric="charactersRead" class="min-h-[44px] rounded-lg px-2 py-2 text-left focus-visible:outline-2 focus-visible:outline-ring" - class:blur={$lastBlurredTrackerItems$.has('charactersRead')} aria-pressed={$lastBlurredTrackerItems$.has('charactersRead')} aria-label={metricAccessibleLabel('charactersRead', 'Characters', charactersValue)} on:click={(event) => @@ -590,7 +588,7 @@ `Weighted Characters: ${currentStatisticsSummaryRow.averageWeightedCharactersRead}` ])} > - {charactersValue} @@ -609,7 +607,6 @@ type="button" data-summary-metric="lastReadingSpeed" class="min-h-[44px] rounded-lg px-2 py-2 text-left focus-visible:outline-2 focus-visible:outline-ring" - class:blur={$lastBlurredTrackerItems$.has('lastReadingSpeed')} aria-pressed={$lastBlurredTrackerItems$.has('lastReadingSpeed')} aria-label={metricAccessibleLabel('lastReadingSpeed', 'Reading speed', speedValue)} on:click={(event) => @@ -620,7 +617,7 @@ `Max Speed: ${currentStatisticsSummaryRow.maxReadingSpeed}` ])} > - {speedValue} + {speedValue} {/if} {/each} From b3a6f45eafb9d7699824551bb9b9f850f8a3ad33 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:22:32 -0400 Subject: [PATCH 218/273] test(statistics): keep privacy blur off focusable metric --- tests/browser/test_panel_usability.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/browser/test_panel_usability.py b/tests/browser/test_panel_usability.py index dd3d69811c..3de2d63a49 100644 --- a/tests/browser/test_panel_usability.py +++ b/tests/browser/test_panel_usability.py @@ -246,6 +246,10 @@ def test_summary_privacy_targets_and_paging_hold_at_200_percent_text(self): self.assertGreaterEqual(metric.bounding_box()['height'], 43.99) self.assert_unoccluded(metric) expect(metric).to_have_attribute('aria-pressed', 'true') + hidden_value = metric.locator('[aria-hidden="true"]').first + expect(hidden_value).to_be_attached() + self.assertEqual('none', metric.evaluate('e => getComputedStyle(e).filter')) + self.assertNotEqual('none', hidden_value.evaluate('e => getComputedStyle(e).filter')) hidden_label = metric.get_attribute('aria-label') self.assertIn('value hidden', hidden_label) self.assertNotIn('1 min', hidden_label) From 6b2cd9891cabb03f8dd13ddea4cd1c84da97d88a Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:23:41 -0400 Subject: [PATCH 219/273] test(storage): cover annotation transaction completion ordering --- .../indexeddb-transaction-lifetime.test.mjs | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/tests/unit/indexeddb-transaction-lifetime.test.mjs b/tests/unit/indexeddb-transaction-lifetime.test.mjs index 631d126f63..f1d8493b5b 100644 --- a/tests/unit/indexeddb-transaction-lifetime.test.mjs +++ b/tests/unit/indexeddb-transaction-lifetime.test.mjs @@ -245,3 +245,148 @@ test('WebDAV disconnect observes transaction completion before deleting authorit }); await api.disconnectDav('webdav-test'); }); + +function annotationHarness(transactionFactory, databaseExtras = {}) { + const scope = { + profileId: null, + signal: new AbortController().signal, + assertCurrent() {}, + stop() {} + }; + return loadOfflineModule('apps/web/src/lib/reader-annotations.ts', { + modules: { + '$lib/data/store': { + database: { + db: Promise.resolve({ + transaction: transactionFactory, + getAllFromIndex: async () => [], + get: async () => undefined, + ...databaseExtras + }) + } + }, + 'svelte/store': { get: () => ({ status: 'available' }) }, + '$lib/manabi/client': { + account: {}, + localProfileUser: () => null + }, + '$lib/reader-location': { + snapshotReaderLocator(target, bookKey) { + return { ...target, bookKey }; + } + }, + '$lib/data/database/books-db/content-hash-index': { + readIndexedBookMetadata: async (store) => store.getAll() + }, + '$lib/manabi/operation-scope': { + captureLibraryOperation: () => scope + } + } + }).api; +} + +test('annotation write wrapper observes completion before its first store read', async () => { + let observed = false; + const empty = { + async get() { + assert.equal(observed, true); + return undefined; + }, + async put() { + assert.equal(observed, true); + }, + async getAll() { + assert.equal(observed, true); + return []; + } + }; + const tx = { + done: { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }, + objectStore() { + return empty; + }, + abort() {} + }; + const api = annotationHarness(() => tx); + const bookKey = 'local:11111111-1111-4111-8111-111111111111'; + const saved = await api.saveReaderAnnotation({ + bookKey, + kind: 'bookmark', + targets: [ + { + bookKey, + resource: { spineIndex: 0, href: 'chapter.xhtml', sectionId: 's1' }, + resourceDigest: 'digest', + start: 0, + end: 0, + quote: '', + prefix: '', + suffix: '' + } + ] + }); + assert.equal(saved.bookKey, bookKey); +}); + +test('annotation ownership lookup observes readonly completion before inventory reads', async () => { + const contentHash = 'a'.repeat(64); + const bookKey = `content:${contentHash}`; + const record = { + id: '11111111-1111-4111-8111-111111111111', + bookKey, + kind: 'bookmark', + targets: [ + { + bookKey, + resource: { spineIndex: 0, href: 'chapter.xhtml', sectionId: 's1' }, + resourceDigest: 'digest', + start: 0, + end: 0, + quote: '', + prefix: '', + suffix: '' + } + ], + createdAt: '2026-10-01T00:00:00.000Z', + modifiedAt: '2026-10-01T00:00:00.000Z', + revision: 1 + }; + let observed = false; + const data = { + async getAll() { + assert.equal(observed, true); + return [{ id: 7, contentHash, invalidOwner: false, libraryOwner: null }]; + } + }; + const scopes = { + async getAll() { + assert.equal(observed, true); + return []; + } + }; + const tx = { + done: { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }, + objectStore(name) { + return name === 'data' ? data : scopes; + }, + abort() {} + }; + const api = annotationHarness(() => tx, { + getAllFromIndex: async () => [record], + get: async () => undefined + }); + const rows = await api.listReaderAnnotations(bookKey); + assert.equal(rows.length, 1); + assert.equal(rows[0].id, record.id); +}); + From c31b34439a5a7eba03df7179c231f7729248ce91 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:29:21 -0400 Subject: [PATCH 220/273] fix(storage): drain appearance background transactions --- apps/web/src/lib/appearance/backgrounds.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/apps/web/src/lib/appearance/backgrounds.ts b/apps/web/src/lib/appearance/backgrounds.ts index 74305c0a98..9020bad3cc 100644 --- a/apps/web/src/lib/appearance/backgrounds.ts +++ b/apps/web/src/lib/appearance/backgrounds.ts @@ -5,6 +5,7 @@ */ import { openDB, type DBSchema, type IDBPDatabase } from 'idb'; +import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import { writable } from 'svelte/store'; import type { BackgroundMode, BackgroundTarget } from './state'; import { @@ -306,21 +307,23 @@ export function chooseBackground( // Decode outside the transaction; keep read-modify-write atomic across tabs. const image = await prepare(file); const tx = database.transaction('backgrounds', 'readwrite'); - const saved = (await tx.store.get(target)) ?? {}; - saved[mode] = image; - await tx.store.put(saved, target); - await tx.done; + await commitTransaction(tx, async () => { + const saved = (await tx.store.get(target)) ?? {}; + saved[mode] = image; + await tx.store.put(saved, target); + }); }); } export function removeBackground(target: BackgroundTarget, mode: BackgroundMode): Promise { return mutate(target, [mode], async (database) => { const tx = database.transaction('backgrounds', 'readwrite'); - const saved = (await tx.store.get(target)) ?? {}; - delete saved[mode]; - if (saved.light || saved.dark) await tx.store.put(saved, target); - else await tx.store.delete(target); - await tx.done; + await commitTransaction(tx, async () => { + const saved = (await tx.store.get(target)) ?? {}; + delete saved[mode]; + if (saved.light || saved.dark) await tx.store.put(saved, target); + else await tx.store.delete(target); + }); }); } From d374fd090eca55b236077ef33cd3366d2d2cbb61 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:29:54 -0400 Subject: [PATCH 221/273] fix(storage): drain statistics recovery read transaction --- .../database/books-db/reader-statistics.ts | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/apps/web/src/lib/data/database/books-db/reader-statistics.ts b/apps/web/src/lib/data/database/books-db/reader-statistics.ts index 271de958a2..68491bb95b 100644 --- a/apps/web/src/lib/data/database/books-db/reader-statistics.ts +++ b/apps/web/src/lib/data/database/books-db/reader-statistics.ts @@ -498,14 +498,18 @@ export async function readStatisticsRecoverySnapshot(db: IDBPDatabase) ['data', 'statistic', 'readerStatistic', 'readerStatisticMigration', 'readerLocalIdentity'], 'readonly' ); - const [books, legacyRows, contentRows, migrationReceipts, localIdentities] = await Promise.all([ - readIndexedBookTitles(tx.objectStore('data')), - tx.objectStore('statistic').getAll(), - tx.objectStore('readerStatistic').getAll(), - tx.objectStore('readerStatisticMigration').getAll(), - tx.objectStore('readerLocalIdentity').getAll() - ]); - await tx.done; + const { books, legacyRows, contentRows, migrationReceipts, localIdentities } = + await commitTransaction(tx, async () => { + const [books, legacyRows, contentRows, migrationReceipts, localIdentities] = + await Promise.all([ + readIndexedBookTitles(tx.objectStore('data')), + tx.objectStore('statistic').getAll(), + tx.objectStore('readerStatistic').getAll(), + tx.objectStore('readerStatisticMigration').getAll(), + tx.objectStore('readerLocalIdentity').getAll() + ]); + return { books, legacyRows, contentRows, migrationReceipts, localIdentities }; + }); return { format: 'manabi-reader-statistics-recovery', version: 1, From 57e9b7da7c784ffdf09f429dca08673b160b014d Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 16:30:30 -0400 Subject: [PATCH 222/273] test(storage): cover statistics recovery completion ordering --- .../indexeddb-transaction-lifetime.test.mjs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/unit/indexeddb-transaction-lifetime.test.mjs b/tests/unit/indexeddb-transaction-lifetime.test.mjs index f1d8493b5b..41312bf9e5 100644 --- a/tests/unit/indexeddb-transaction-lifetime.test.mjs +++ b/tests/unit/indexeddb-transaction-lifetime.test.mjs @@ -390,3 +390,51 @@ test('annotation ownership lookup observes readonly completion before inventory assert.equal(rows[0].id, record.id); }); +test('statistics recovery export observes readonly completion before inventory reads', async () => { + let observed = false; + const store = { + async getAll() { + assert.equal(observed, true); + return []; + } + }; + const tx = { + done: { + then(onFulfilled, onRejected) { + observed = true; + return Promise.resolve().then(onFulfilled, onRejected); + } + }, + objectStore() { + return store; + }, + abort() {} + }; + const { api } = loadOfflineModule( + 'apps/web/src/lib/data/database/books-db/reader-statistics.ts', + { + modules: { + idb: {}, + './versions/books-db': {}, + './content-hash-index.ts': { + contentHashPrimaryKeys: async () => [], + readIndexedBookTitles: async (source) => source.getAll() + } + }, + globals: { + IDBKeyRange: { + bound: () => ({}) + } + } + } + ); + const snapshot = await api.readStatisticsRecoverySnapshot({ + transaction() { + observed = false; + return tx; + } + }); + assert.equal(snapshot.format, 'manabi-reader-statistics-recovery'); + assert.deepEqual(snapshot.books, []); +}); + From c1e8627e749bced54213efe734ae0ae3ebb1edad Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 19:51:05 -0400 Subject: [PATCH 223/273] test(storage): preserve merged persistence fixture --- tests/unit/library-selection-authority.test.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/unit/library-selection-authority.test.mjs b/tests/unit/library-selection-authority.test.mjs index ce10e2bc86..b69c4f8c42 100644 --- a/tests/unit/library-selection-authority.test.mjs +++ b/tests/unit/library-selection-authority.test.mjs @@ -610,6 +610,9 @@ function linkFixture(records, links) { '$lib/data/storage/storage-handler-factory': {}, '$lib/data/database/books-db/book-binary': {}, '$lib/data/database/books-db/commit-transaction.mjs': { commitTransaction }, + '$lib/data/window/navigator/persistent-storage': { + requestPersistentStorageOnce: () => Promise.resolve(false) + }, '$lib/data/database/books-db/library-import': { readIndexedBookIdentities: async () => records }, From f7705617881662d4f28467fbf0a4f339e1e85a99 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 19:51:22 -0400 Subject: [PATCH 224/273] test(annotations): wire shared transaction helper --- tests/unit/foliate-annotation-snapshot.test.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/unit/foliate-annotation-snapshot.test.mjs b/tests/unit/foliate-annotation-snapshot.test.mjs index d2c320ecb4..593e4e0d53 100644 --- a/tests/unit/foliate-annotation-snapshot.test.mjs +++ b/tests/unit/foliate-annotation-snapshot.test.mjs @@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url'; import { compileFunction } from 'node:vm'; import test from 'node:test'; import ts from 'typescript'; +import { commitTransaction } from '../../apps/web/src/lib/data/database/books-db/commit-transaction.mjs'; const root = new URL('../../apps/web/src/lib/', import.meta.url); let database; @@ -29,6 +30,8 @@ function load(url) { compileFunction(outputText, ['require', 'module', 'exports'])( (name) => { if (name === '$lib/data/store') return { database }; + if (name === '$lib/data/database/books-db/commit-transaction.mjs') + return { commitTransaction }; if (name === 'svelte/store') return { get: () => ({ status: 'ready' }) }; if (name === '$lib/manabi/client') return { account: {}, localProfileUser: () => profile }; if (name === '$lib/manabi/operation-scope') From 0ab91df753b37ccb92c40f7ba314f343d051c892 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 19:51:25 -0400 Subject: [PATCH 225/273] test(annotations): wire transaction helper into ownership fixture --- tests/unit/library-reader-write-ownership.test.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/library-reader-write-ownership.test.mjs b/tests/unit/library-reader-write-ownership.test.mjs index c75df6bfe2..735097b50c 100644 --- a/tests/unit/library-reader-write-ownership.test.mjs +++ b/tests/unit/library-reader-write-ownership.test.mjs @@ -406,6 +406,7 @@ function annotationFixture({ bookOwner, scopeOwner, onTransaction } = {}) { const operationControllers = new Set(); const api = load('reader-annotations.ts', { '$lib/data/store': { database: { db: Promise.resolve(db) } }, + '$lib/data/database/books-db/commit-transaction.mjs': { commitTransaction }, 'svelte/store': { get: (value) => value.value }, '$lib/manabi/client': { account: { value: { status: 'ready' } }, From daafb2b0e26bd6ee04a30ecd1def2ffcbf3ea12a Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 19:51:28 -0400 Subject: [PATCH 226/273] style(storage): trim transaction lifetime suite --- tests/unit/indexeddb-transaction-lifetime.test.mjs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/unit/indexeddb-transaction-lifetime.test.mjs b/tests/unit/indexeddb-transaction-lifetime.test.mjs index 41312bf9e5..7669d7c353 100644 --- a/tests/unit/indexeddb-transaction-lifetime.test.mjs +++ b/tests/unit/indexeddb-transaction-lifetime.test.mjs @@ -437,4 +437,3 @@ test('statistics recovery export observes readonly completion before inventory r assert.equal(snapshot.format, 'manabi-reader-statistics-recovery'); assert.deepEqual(snapshot.books, []); }); - From 9a2732f50aee5a130ffe9e2e9b9190454279a357 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 19:53:06 -0400 Subject: [PATCH 227/273] fix(annotations): preserve authority error after transaction abort --- apps/web/src/lib/reader-annotations.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apps/web/src/lib/reader-annotations.ts b/apps/web/src/lib/reader-annotations.ts index 0cb6ffda48..a285a3ddde 100644 --- a/apps/web/src/lib/reader-annotations.ts +++ b/apps/web/src/lib/reader-annotations.ts @@ -71,6 +71,12 @@ async function commitAnnotationTransaction( }); operation.assertCurrent(); return result; + } catch (error) { + // Account/profile authority outranks a lower-level transaction abort. This + // preserves the pre-helper behavior when revocation happens while waiting + // for commit. + operation.assertCurrent(); + throw error; } finally { unbind(); } From 3a72d95bade1269782545aca64afa6ac78c002a0 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:10:00 -0400 Subject: [PATCH 228/273] test(storage): wait for the actual first transaction request --- tests/unit/books-db-service-commit-lifetime.test.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/unit/books-db-service-commit-lifetime.test.mjs b/tests/unit/books-db-service-commit-lifetime.test.mjs index e7359b7ac7..acbb5d7210 100644 --- a/tests/unit/books-db-service-commit-lifetime.test.mjs +++ b/tests/unit/books-db-service-commit-lifetime.test.mjs @@ -66,10 +66,15 @@ test('storage-source publication waits for transaction completion observed befor } }; const writes = []; + let resolveFirstRequest; + const firstRequest = new Promise((resolve) => { + resolveFirstRequest = resolve; + }); const store = { async add(value) { assert.equal(completionObserved, true); writes.push(['add', value.name]); + resolveFirstRequest(); }, async put(value) { assert.equal(completionObserved, true); @@ -110,7 +115,7 @@ test('storage-source publication waits for transaction completion observed befor true, true ); - await Promise.resolve(); + await firstRequest; assert.deepEqual(writes, [['add', 'Browser backup']]); assert.deepEqual(published, [], 'sync target published before transaction commit'); assert.deepEqual(defaults, [], 'default source published before transaction commit'); From 1dddf74ba7c39506213c8cd4d512da9baaafdaff Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:11:20 -0400 Subject: [PATCH 229/273] test(media): align sparse ETA copy with speech timing --- tests/media/dom-browser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/media/dom-browser.py b/tests/media/dom-browser.py index 8c1d15ef1a..7213eab28e 100644 --- a/tests/media/dom-browser.py +++ b/tests/media/dom-browser.py @@ -821,7 +821,7 @@ def sparse_buffer_controls(): windows:[null,null,null],repairs:[null,null]}}; player.generationProgress(sparseJob); }""") - assert 'estimating after the first window' in page.locator('.video-viewing [role=status]').all_inner_texts()[-1] + assert 'estimating after the first speech window' in page.locator('.video-viewing [role=status]').all_inner_texts()[-1] elapsed=page.evaluate("""()=>{ player.generationProgress(sparseJob,'transcribing'); player.firstWindowStartedAt-=5000; From 60e672bf42c437d328d86c3d2444e52b3b3cf72f Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:11:51 -0400 Subject: [PATCH 230/273] test(video): make card selection target rerender-safe --- tests/media/app-browser.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/media/app-browser.py b/tests/media/app-browser.py index 25e8c2e464..438bf4d334 100644 --- a/tests/media/app-browser.py +++ b/tests/media/app-browser.py @@ -146,10 +146,12 @@ def upload(): shelf = page.get_by_label('Video library', exact=True) card_select = shelf.get_by_role('checkbox').first expect(card_select).to_be_visible() - library_card = card_select.locator('..').locator('..') + library_card = card_select.locator('xpath=ancestor::article[1]') expect(library_card).to_have_class(re.compile(r'.*\bvideo-card\b.*')) - select_target = card_select.locator('..') + select_target = library_card.locator('.video-select') + expect(select_target).to_be_visible() select_box = select_target.bounding_box() + assert select_box is not None, 'selection target detached during shelf refresh' assert select_box['width'] >= 43.5 and select_box['height'] >= 43.5, select_box assert card_select.evaluate("""input => { const label=input.closest('label'); From 8630d998bca65be52eca384897e593bc58981a59 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:11:55 -0400 Subject: [PATCH 231/273] test(video): assert card generation by rendered identity --- tests/media/workspace-dom.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/media/workspace-dom.py b/tests/media/workspace-dom.py index 79a5c520ef..b987673e80 100644 --- a/tests/media/workspace-dom.py +++ b/tests/media/workspace-dom.py @@ -1056,9 +1056,12 @@ def batch_selection_state(): )""") card=page.locator('.video-card').filter( has=page.get_by_role('button',name='Watching',exact=True)) + card_key=card.get_attribute('data-media-key') + assert card_key card.get_by_text('Actions',exact=True).click() card.get_by_role('button',name='Generate missing transcript',exact=True).click() - assert page.evaluate('bulkSelections')==[[page.evaluate("syntheticKey('a')")]] + page.wait_for_function('bulkSelections.length===1') + assert page.evaluate('bulkSelections')==[[card_key]] assert page.evaluate('workspace.selected.size')==0 assert not page.get_by_label('Select Watching',exact=True).is_checked() From 843800b0eb0a079483ae70f66f6c9be3b2afe55c Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:17:15 -0400 Subject: [PATCH 232/273] fix(media): restart ETA clock after silent sparse cores --- apps/web/src/lib/media/player.ts | 33 ++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/apps/web/src/lib/media/player.ts b/apps/web/src/lib/media/player.ts index f4270dd8de..8e83a96c3d 100644 --- a/apps/web/src/lib/media/player.ts +++ b/apps/web/src/lib/media/player.ts @@ -78,6 +78,7 @@ export class VideoPlayer { private waitingForOriginLock?: string; private firstWindowJob?: string; private firstWindowStartedAt?: number; + private firstWindowCompleted = 0; private firstWindowClock?: ReturnType; private followGeneratedCaptions = false; private waitForCaptions = false; @@ -950,16 +951,32 @@ export class VideoPlayer { this.firstWindowClock = undefined; this.firstWindowJob = job.id; this.firstWindowStartedAt = undefined; + this.firstWindowCompleted = 0; } - if ( - job.sparse && - !job.sparse.windows.some(Boolean) && + const awaitingFirstSpeechTiming = + !!job.sparse && job.status === 'running' && - (stage === 'decoding' || stage === 'transcribing') - ) { - this.firstWindowStartedAt ??= Date.now(); - this.firstWindowClock ??= setInterval(() => this.updateBuffering(), 1000); - } else if (!job.sparse || job.status !== 'running' || job.sparse.windows.some(Boolean)) { + !!this.sparsePlayback && + this.sparsePlayback.inputSeconds === 0; + if (awaitingFirstSpeechTiming && (stage === 'decoding' || stage === 'transcribing')) { + const completed = this.sparsePlayback!.count; + // A completed exact-silent core is coverage, not an ASR timing sample. + // Retire its elapsed clock; the next decoding notification starts a fresh + // clock for the next candidate speech window. + if (this.firstWindowStartedAt !== undefined && completed > this.firstWindowCompleted) { + clearInterval(this.firstWindowClock); + this.firstWindowClock = undefined; + this.firstWindowStartedAt = undefined; + } + if ( + this.firstWindowStartedAt === undefined && + (stage === 'decoding' || completed === 0) + ) { + this.firstWindowCompleted = completed; + this.firstWindowStartedAt = Date.now(); + this.firstWindowClock = setInterval(() => this.updateBuffering(), 1000); + } + } else { clearInterval(this.firstWindowClock); this.firstWindowClock = undefined; this.firstWindowStartedAt = undefined; From aa58e87e90d90c8fe827947ccb643c7a46225bc7 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:17:26 -0400 Subject: [PATCH 233/273] test(media): cover silent-first sparse ETA timing --- tests/media/dom-browser.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/media/dom-browser.py b/tests/media/dom-browser.py index 7213eab28e..eef3c1bb0e 100644 --- a/tests/media/dom-browser.py +++ b/tests/media/dom-browser.py @@ -843,6 +843,28 @@ def sparse_buffer_controls(): assert page.get_by_role('button',name='Wait for captions',exact=True).is_visible() page.wait_for_function('!player.video.paused') case('slow sparse inference shows a measured ETA and playback bypass',sparse_buffer_controls) + def sparse_silence_restarts_speech_clock(): + result=page.evaluate("""async()=>{ + await createPlayer(); + await player.bindIdentity(mediaKey); + const job={id:trackId,mediaKey,status:'running',duration:52, + sparse:{policy:'overlap-sparse-v2',targetSeconds:0, + windows:[null,null],repairs:[null]}}; + player.generationProgress(job,'decoding'); + const firstStarted=typeof player.firstWindowStartedAt==='number'; + job.sparse.windows[0]={cues:[],inferenceMs:50,digitalSilence:true}; + player.generationProgress(job,'transcribing'); + const reset=player.firstWindowStartedAt===undefined; + player.generationProgress(job,'decoding'); + const restarted=typeof player.firstWindowStartedAt==='number' + && player.firstWindowCompleted===1; + player.firstWindowStartedAt-=3000; + player.updateBuffering(); + return {firstStarted,reset,restarted,status:player.bufferStatus.textContent}; + }""") + assert result['firstStarted'] and result['reset'] and result['restarted'],result + assert 'first speech window' in result['status'] and '0:03 elapsed on this device' in result['status'],result + case('digital-silent coverage restarts the first-speech ETA clock',sparse_silence_restarts_speech_clock) def native_play_at_sparse_gap(): result=page.evaluate("""async()=>{ await createPlayer(); From c2a81649cdb28e9bf2170409180928af18dabf19 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:19:30 -0400 Subject: [PATCH 234/273] test(media): cover MOSS marker-collapse fallback --- tests/media/sparse-transcription.test.mjs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/media/sparse-transcription.test.mjs b/tests/media/sparse-transcription.test.mjs index 4202f7abc5..22c785c1b2 100644 --- a/tests/media/sparse-transcription.test.mjs +++ b/tests/media/sparse-transcription.test.mjs @@ -16,6 +16,7 @@ import { } from '../../.cache/media-test-build/sparse-transcription.js'; import { TransactionFactory, RangeDouble } from './transaction-double.mjs'; import { transcriptionDraft } from '../../.cache/media-test-build/transcription-draft.js'; +import { parseMoss } from '../../.cache/media-test-build/moss-output.js'; const key = 'content:' + '6'.repeat(64); const cue = (window, start, end, text) => ({ @@ -101,6 +102,23 @@ test('agreed whole cues crossing a seam margin appear, one-sided cues require re assert.deepEqual(assembleSparse(state), { repair: 0 }); assert.equal(sparseLead(state, 52, 0), 23); }); +test('marker-collapse output preserves text but cannot claim boundary readiness', () => { + const parsed = parseMoss('[0.00]First sentence. Second sentence.[28.00]', 28); + assert.equal(parsed.length, 1); + assert.equal(parsed[0].text, 'First sentence. Second sentence.'); + assert.equal(parsed[0].speaker, undefined); + assert.deepEqual([parsed[0].start, parsed[0].end], [0, 28]); + + const state = newSparseState(52); + state.windows[0] = { + cues: [{ ...parsed[0], id: 'w0/cue-0' }], + inferenceMs: 1000 + }; + assert.deepEqual(safeSparseCues(state, 52), []); + assert.equal(sparseLead(state, 52, 0), 0); + assert.deepEqual(assembleSparse(state), {}); +}); + test('verified digital silence resolves only whole cues covered by the zero input', () => { const state = newSparseState(52); const early = cue(0, 3, 4, 'real speech'); From b0a21b626b5c4f41209909a3df5f7eeab2d853d2 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:23:59 -0400 Subject: [PATCH 235/273] fix(media): keep first-speech ETA clock through model preparation --- apps/web/src/lib/media/player.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/web/src/lib/media/player.ts b/apps/web/src/lib/media/player.ts index 8e83a96c3d..d3910afd8d 100644 --- a/apps/web/src/lib/media/player.ts +++ b/apps/web/src/lib/media/player.ts @@ -958,11 +958,12 @@ export class VideoPlayer { job.status === 'running' && !!this.sparsePlayback && this.sparsePlayback.inputSeconds === 0; - if (awaitingFirstSpeechTiming && (stage === 'decoding' || stage === 'transcribing')) { + if (awaitingFirstSpeechTiming) { const completed = this.sparsePlayback!.count; // A completed exact-silent core is coverage, not an ASR timing sample. // Retire its elapsed clock; the next decoding notification starts a fresh - // clock for the next candidate speech window. + // clock for the next candidate speech window. Preparation/download stages + // belong to the current attempt and must not clear its elapsed time. if (this.firstWindowStartedAt !== undefined && completed > this.firstWindowCompleted) { clearInterval(this.firstWindowClock); this.firstWindowClock = undefined; @@ -970,7 +971,7 @@ export class VideoPlayer { } if ( this.firstWindowStartedAt === undefined && - (stage === 'decoding' || completed === 0) + (stage === 'decoding' || (stage === 'transcribing' && completed === 0)) ) { this.firstWindowCompleted = completed; this.firstWindowStartedAt = Date.now(); From a2e29fe5c8a036c8cfc136e36cb486626a2fa236 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:24:11 -0400 Subject: [PATCH 236/273] test(media): keep sparse ETA timing through preparation --- tests/media/dom-browser.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/media/dom-browser.py b/tests/media/dom-browser.py index eef3c1bb0e..c036fc9c63 100644 --- a/tests/media/dom-browser.py +++ b/tests/media/dom-browser.py @@ -852,6 +852,9 @@ def sparse_silence_restarts_speech_clock(): windows:[null,null],repairs:[null]}}; player.generationProgress(job,'decoding'); const firstStarted=typeof player.firstWindowStartedAt==='number'; + const beforePrepare=player.firstWindowStartedAt; + player.generationProgress(job,'loading'); + const preparePreserved=player.firstWindowStartedAt===beforePrepare; job.sparse.windows[0]={cues:[],inferenceMs:50,digitalSilence:true}; player.generationProgress(job,'transcribing'); const reset=player.firstWindowStartedAt===undefined; @@ -860,9 +863,11 @@ def sparse_silence_restarts_speech_clock(): && player.firstWindowCompleted===1; player.firstWindowStartedAt-=3000; player.updateBuffering(); - return {firstStarted,reset,restarted,status:player.bufferStatus.textContent}; + return {firstStarted,preparePreserved,reset,restarted, + status:player.bufferStatus.textContent}; }""") - assert result['firstStarted'] and result['reset'] and result['restarted'],result + assert result['firstStarted'] and result['preparePreserved'],result + assert result['reset'] and result['restarted'],result assert 'first speech window' in result['status'] and '0:03 elapsed on this device' in result['status'],result case('digital-silent coverage restarts the first-speech ETA clock',sparse_silence_restarts_speech_clock) def native_play_at_sparse_gap(): From 83fb4896c3e78ae9adf4ef6050872c82743bff2a Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:25:33 -0400 Subject: [PATCH 237/273] docs(media): record MOSS marker-collapse behavior --- docs/moss-progressive-transcription.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/moss-progressive-transcription.md b/docs/moss-progressive-transcription.md index a4a2894622..a280cc0b9b 100644 --- a/docs/moss-progressive-transcription.md +++ b/docs/moss-progressive-transcription.md @@ -223,6 +223,11 @@ case, not a broad quality or performance result; the Mac was under load. https://github.com/localai-org/moss-transcribe.cpp/blob/190a569c13b4b247450f2fb3b2a431244e84833e/src/audio_encoder.cpp - Upstream windowed realtime proposal (not copied as a proven stitcher): https://github.com/OpenMOSS/MOSS-Transcribe-Diarize/pull/58 +- Upstream marker-collapse report: short trailing/inserted quiet can preserve ASR text + while removing internal speaker/timestamp markers. Reader keeps the resulting + outer-timestamp cue whole and does not invent internal timing; sparse readiness + therefore stops at a boundary-crossing collapsed cue until later agreement/repair: + https://github.com/OpenMOSS/MOSS-Transcribe-Diarize/issues/61 - MOSS speaker-tag omission report: https://github.com/OpenMOSS/MOSS-Transcribe-Diarize/issues/40 - Whisper-Streaming's agreement approach: From c5e016ab423731f0bdaae73909dd9f86fa91b496 Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 20:29:49 -0400 Subject: [PATCH 238/273] docs(media): align MOSS design note with landed sparse v2 stack --- docs/moss-progressive-transcription.md | 42 ++++++++++++-------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/docs/moss-progressive-transcription.md b/docs/moss-progressive-transcription.md index a280cc0b9b..30d7fc3308 100644 --- a/docs/moss-progressive-transcription.md +++ b/docs/moss-progressive-transcription.md @@ -2,9 +2,8 @@ ## Scope -This change is stacked on video PR #46 at -`b1040f917f1af16ba7fd5b7cfbdcbf02a103197a`. It keeps the immutable Mudler Q5_0 -weights and CPU-first local architecture. It does not add another ASR model, +Reader's current local transcription stack keeps the immutable Mudler Q5_0 +weights and CPU-first browser architecture. It does not add another ASR model, forced alignment, a server, global speaker identities, or microphone streaming. There are two independent improvements: accepted window results become readable @@ -110,16 +109,15 @@ media. The transaction layer, native model computation and provider boundaries a explicit doubles where noted in the test reports. The native output patch test compiles a scripted C++ decoder; it is not a full MOSS or Emscripten build. -The opt-in real-ASR harness now records `partialUpdates`, `firstOutputSeconds`, and -`firstPreviewCueSeconds`, relative to inference start. It rejects missing callbacks -or invalid timing evidence. `prepareSeconds` remains separate. This harness change -has not been run against the v7 WASM/model here. +The real-ASR harness records `partialUpdates`, `firstOutputSeconds`, and +`firstPreviewCueSeconds`, relative to inference start, with `prepareSeconds` +reported separately. The repository's packaged-MOSS qualification exercises the +checked-in v7 runtime and pinned real speech; those CI-host results establish +runtime/fixture behavior, not representative-device performance. -Before merge, rebuild and qualify both v7 runtimes, run the repository-pinned -formatter/ESLint/Svelte/build and exact-head CI, and exercise real-model output, -cancellation and resume. Benchmark current legacy windows against the new profile; -compare unique covered media seconds, encoder and decoder time, time to first -preview and settled output, peak/steady memory and repair rate. Natural Japanese, +Remaining release qualification should compare unique covered media seconds, +encoder and decoder time, time to first preview and settled output, peak/steady +memory and repair rate on representative devices. Natural Japanese, quiet speech, repeated replies, numbers, music, speaker overlaps and deliberately seam-crossing utterances are required. Desktop/mobile and physical Safari/iOS, native multi-tab/IndexedDB and live cloud/account composition remain separate gates. @@ -129,17 +127,16 @@ PR #46's exact-head v4 CPU qualification run `36280725560` reports roughly single-threaded (about 5.7x realtime) for roughly 11 seconds of generated audio. That large base-v4 improvement motivates the short first input, but it is not v7 or representative-device qualification and inference is still slower than realtime on -that CI host. The base closeout -also identifies production packaging/serving of both WASM variants as unresolved. -This patch does not repair that deployment pipeline. It makes no new real-time -factor, accuracy, or device-memory claim. +that CI host. The historical v4 number remains useful only as context for why bounded inputs were +pursued. Current v7 packaged qualification is the relevant runtime gate; neither CI +host establishes representative-device real-time factor or memory behavior. True microphone streaming and a neural VAD remain outside this change. ## Playback-first sparse jobs -An explicit Generate action in the player now creates a version-3 -`overlap-sparse-v1` job. Its 26-second cores and two-second halos bound normal +An explicit Generate action in the player creates a version-3 +`overlap-sparse-v2` job. Its 26-second cores and two-second halos bound normal MOSS inputs to 30 seconds. The current playhead selects the next missing core; seeks change that priority after the current inference finishes. Each completed core is checkpointed once and reused in the same job as the queue fills the @@ -173,7 +170,7 @@ routine queue reads do not reload the complete window hypotheses. The player measures decode plus warm inference time for each finished **non-silent** core, excluding first-time model download/preparation and exact-zero cores that bypass MOSS, and estimates how long it will take to build a 26-second caption lead. The estimate is updated -as more windows finish; before the first window it says that it is estimating. +as more speech windows finish; before the first non-silent timing sample it says that it is estimating. If inference takes longer than one core of playback, the UI says captions may need to buffer again. Viewers can wait or choose **Play without captions**. This is a rolling estimate, not a promise of sustained real-time transcription. @@ -200,9 +197,10 @@ job unpublished. Older provisional jobs without audio proofs cannot use this recovery path. Version-3 scheduling, early seam repair, accepted-cue preservation, and the -browser controls have deterministic and Chromium tests. Natural Japanese -boundary quality, real-WASM throughput, device memory, and suspended-tab -recovery have not yet been qualified for this new policy. +browser controls have deterministic and Chromium tests. One pinned real-WASM +Japanese seam case is qualified below; broader natural-Japanese boundary quality, +representative-device throughput/memory, and suspended-tab recovery remain +separate release evidence. One targeted real-WASM Japanese check now covers the sparse seam. The pinned single-thread v7 runtime and Q5_0 model processed a 35.68-second sequence made From 6fa456e433739d64be78d8a863ae5ce8f51bb37b Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 22:35:24 -0400 Subject: [PATCH 239/273] refine(tracker): compact history actions at enlarged text --- .../book-reading-tracker-menu.svelte | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte index 0e58f39a3a..e65ded1da7 100644 --- a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte +++ b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte @@ -450,17 +450,22 @@ title="Revert Item" onclick={() => dispatch('revertStatistic', trackingHistoryItem)} > - Revert Item + Revert - + + {trackingHistoryItem.saved ? 'Saved' : 'Not saved yet'} {trackingHistoryItem.saved ? 'Saved to database' : 'Not saved yet'}{trackingHistoryItem.saved ? ' to database' : ''}
From 29df36515e47df7f97f57f2374bfbbd4d3fcef0f Mon Sep 17 00:00:00 2001 From: Alex Ehlke Date: Thu, 1 Oct 2026 22:35:57 -0400 Subject: [PATCH 240/273] refine(tracker): keep history revert on one line --- .../book-reading-tracker/book-reading-tracker-menu.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte index e65ded1da7..811a20833d 100644 --- a/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte +++ b/apps/web/src/lib/components/book-reader/book-reading-tracker/book-reading-tracker-menu.svelte @@ -445,7 +445,7 @@