diff --git a/.github/workflows/media-player.yml b/.github/workflows/media-player.yml index 858a2033ab..759a13b212 100644 --- a/.github/workflows/media-player.yml +++ b/.github/workflows/media-player.yml @@ -7,6 +7,29 @@ on: description: 'Also reproduce the documented Chromium 153 Incognito handle crash (fails on affected build)' type: boolean default: false + push: + branches: [main] + paths: + - 'apps/web/src/lib/media/**' + - 'apps/web/src/lib/manabi/media-*.ts' + - 'apps/web/src/routes/videos/**' + - 'apps/web/src/lib/search/**' + - 'tests/browser/test_unified_search.py' + - 'apps/web/src/lib/components/book-reader/reader-appearance.svelte' + - 'apps/web/src/lib/appearance/**' + - 'apps/web/src/lib/data/*font*' + - 'apps/web/src/lib/data/reader-typography.ts' + - 'apps/web/src/lib/data/store.ts' + - 'apps/web/src/lib/functions/reader-font-layout.ts' + - 'tests/media/**' + - 'tests/browser/test_static_reader.py' + - 'tools/media/**' + - 'apps/web/package.json' + - 'apps/web/svelte.config.js' + - 'package.json' + - 'pnpm-lock.yaml' + - '.github/workflows/media-player.yml' + pull_request: paths: - 'apps/web/src/lib/media/**' @@ -125,7 +148,15 @@ jobs: sudo apt-get update -qq sudo apt-get install -y ffmpeg espeak python -m pip install playwright==1.63.0 - python -m playwright install --with-deps chromium + python -m playwright install --with-deps chromium webkit + - name: Cross-browser Videos application shell + run: | + status=0 + for engine in chromium webkit; do + python tests/media/app-shell-browser.py --engine "$engine" \ + --output "test-results/media/app-shell/$engine" || status=1 + done + exit "$status" - name: Install qualified storage browser run: bash tools/media/install-qualified-chromium.sh test-results/media/browser - name: Generate short fixture and run media regressions diff --git a/CLEAN_ROOM_APPROVALS.md b/CLEAN_ROOM_APPROVALS.md new file mode 100644 index 0000000000..cdd15a4061 --- /dev/null +++ b/CLEAN_ROOM_APPROVALS.md @@ -0,0 +1,325 @@ +# Clean-room feature approval gate + +Status: CLOSED BY DEFAULT +Revision: 2026-11-08 docs-only consolidation + +Historical research baseline: 2026-10-03. + +This file is the authorization gate for work derived from the clean-room competitive-reader program. + +## Default rule + +**No feature, acceptance suite, benchmark-driven fix, fixture suite, or product change is approved for implementation merely because it appears in this branch or PR #260.** + +The clean-room documents are research/specification inputs. They are not a standing work order. + +Unless an approval is recorded below, a worker may only: + +- review and refine the clean-room research/specification documents; +- deduplicate or clarify requirements; +- inspect authorized Manabi target code to identify overlap when the user explicitly asks for review; +- report what would need approval. + +Without an approval, a worker must not: + +- add CR-derived test fixtures to the product test suite; +- add CR-derived automated/browser/device tests; +- modify product/runtime code; +- implement a `CR-OPP-*` feature; +- open an implementation PR based on this program; +- infer approval from a previous worker's activity. + +## Approval levels + +An approval must identify a bounded feature or CR ID set and one of these levels. + +### DISCOVERY_ONLY + +Default state. Research/spec refinement only. No product/test mutation is authorized. + +### APPROVED_FOR_DESIGN + +Authorizes only target-side product/design exploration for the named feature/CR IDs, such as: + +- target-owned UX flows; +- wire-level behavior descriptions; +- target architecture impact analysis; +- data/privacy decisions; +- acceptance-criteria refinement. + +It does **not** authorize adding product fixtures/tests, changing production behavior, or opening an implementation PR. + +### APPROVED_FOR_TESTS + +Authorizes only independently authored fixtures and tests for the named feature/CR IDs. + +It does **not** authorize production behavior changes, even if tests fail. + +### APPROVED_FOR_IMPLEMENTATION + +Authorizes production changes only for the named feature/CR IDs and only within the stated scope. + +It includes the minimum tests needed for that implementation unless the approval explicitly says otherwise. + +### APPROVED_FOR_INTEGRATION + +Authorizes integration/merge work for the named implementation PR or bounded feature change. + +This does not authorize unrelated features. + +## What counts as explicit per-feature approval + +A valid approval must come from the user/project owner and must unambiguously identify the feature. + +Preferred forms: + +- `Approve CR-OPP-001 for implementation.` +- `Approve CR-OPP-003 and CR-OPP-149 for design exploration only.` +- `Approve the chapter-preflight feature (CR-OPP-001) for implementation in Manabi Reader Web.` +- `Approve CR-AT-001..006 for tests only; do not change production code.` + +A named feature may be accepted without the literal CR ID only when the mapping is unique and the worker records the mapped CR ID before starting. + +## What does not count as approval + +None of the following authorizes implementation: + +- the feature appearing in this branch; +- the feature being marked MUST/SHOULD/MAY; +- the feature being described as high value, strong, important, or a candidate; +- a benchmark or acceptance test failing; +- a prior worker creating research/spec text; +- a prior worker creating PR #260; +- approval of a neighboring or related feature; +- approval of the same feature in another repository/platform; +- generic instructions such as “continue,” “go deeper,” “review,” “refine,” “finish the clean-room work,” or “work through the backlog”; +- a request to investigate or compare a feature; +- an implementation worker deciding that a feature is easy or obviously beneficial. + +Approval is non-transitive and non-inferential. + +## Approval scope requirements + +Each approval record must state: + +- approval ID; +- date; +- feature/CR IDs; +- approval level; +- target repository/platform; +- bounded deliverable; +- approval basis: relevant CR IDs plus the sanitized spec blob/revision, or equivalent explicit scope text; +- explicit exclusions or constraints; +- status: active, completed, revoked, or superseded. + +If any of those materially affect what can be changed and are unspecified, use the narrowest reasonable interpretation and do not expand scope. + +## Research-document integration status + +On 2026-11-08, Alex authorized docs-only consolidation of this research under the request to advance all drafts and all relevant PRs. This authorizes integrating and finalizing the research documentation; it grants no CR feature design, tests, implementation, or feature integration approval. GitHub merge/closure status must be reported from integration evidence, not inferred from this document. + +Research-document finalization is separate from completing the clean-room feature program. All per-feature approval requirements below remain in force. + +## Active approvals + +**None.** + +Therefore, at this revision: + +- no `CR-OPP-*` feature is approved for tests or implementation; +- no correctness/acceptance suite is approved for target-code mutation under this program; +- no CR-derived implementation PR is authorized. + +## Recording a future approval + +Append a record in this format: + +```text +Approval ID: CR-AUTH-001 +Date: YYYY-MM-DD +Feature/CR IDs: ... +Level: APPROVED_FOR_DESIGN | APPROVED_FOR_TESTS | APPROVED_FOR_IMPLEMENTATION | APPROVED_FOR_INTEGRATION +Target: ... +Deliverable: ... +Approval basis: CR IDs + spec blob/revision, or explicit bounded scope text +Exclusions: ... +Status: active +Evidence of approval: concise paraphrase of the explicit user/project-owner instruction +``` + +Do not include competitor provenance in an approval record. + +## Revocation and completion + +The user/project owner may revoke or narrow approval at any time. + +When a bounded approved feature is completed, mark that approval record completed. Completion does not authorize the next feature. + +A new feature requires a new explicit approval. + +## Approval validation checklist + +Before target-side work, a worker must validate all of the following: + +1. the approval record exists in this file; +2. its status is active; +3. the requested CR ID/feature is explicitly covered; +4. the requested action is permitted by the approval level; +5. the target repository/platform matches; +6. the requested deliverable fits the bounded deliverable text; +7. no exclusion forbids the requested change; +8. the approval has not been superseded by a narrower/later record. + +If any check fails, target-side work is not authorized. + +## Per-feature scope packet + +Before starting an approved feature, the worker should state a compact scope packet in its implementation PR or working notes: + +- Approval ID +- CR IDs +- target repo/platform +- existing target primitive(s) reused +- user-visible behavior being changed +- data/storage migrations, if any +- privacy/network effect, if any +- test/benchmark IDs in scope +- explicit non-goals +- adjacent CR IDs discovered but not approved + +The scope packet is derived only from the sanitized handoff plus authorized target code. + +## Minimal shared-primitive rule + +An approved feature may require a shared target-owned primitive. + +That does not create authority to implement other features that could also use the primitive. + +A worker may add/refine a shared primitive only when all of these are true: + +- it is necessary for the approved behavior; +- its API/scope is the minimum coherent target-owned abstraction needed; +- it does not expose unrelated new user-visible features; +- it does not pre-implement unapproved feature-specific behavior; +- its tests are limited to the primitive's contract and the approved feature; +- adjacent opportunities are recorded for later approval rather than bundled in. + +A broad refactor justified mainly by future unapproved CR-OPP entries requires separate approval. + +## No batch approval by implication + +Even if several CR entries share one subsystem, approval remains per named feature/suite. + +For example, approval of one audio mode does not authorize every `CR-OPP-070..` media feature; approval of one OCR feature does not authorize the entire OCR opportunity section. + +A user/project owner may explicitly approve a bounded bundle, but the bundle must be named or enumerated. Workers may not construct the bundle themselves. + +## Approval-ledger mutation rule + +Workers are not authorized to create, broaden, reactivate, or upgrade an approval record on their own. + +An approval record may be added or changed to `active` only when the current user/project-owner instruction explicitly grants that approval. + +A worker must not mutate this ledger merely because: + +- a task was assigned by another worker; +- an issue/PR says a feature should be implemented; +- a project document recommends the feature; +- CI/test output suggests a fix; +- a previous assistant claimed approval existed; +- the feature appears in an implementation branch; +- the worker believes approval is implied. + +When recording a new approval, the worker must be able to point to the explicit owner instruction in the current conversational/task context. If that evidence is absent, leave the ledger unchanged and report that approval is missing. + +A worker may update an existing record to `completed`, `revoked`, or `superseded` only when: + +- the bounded approved work has actually completed; or +- the user/project owner explicitly revokes/supersedes it. + +Completion may never broaden scope. + +## Approval precedence + +When approval records overlap: + +1. explicit revocation wins over earlier approval; +2. a later narrower approval constrains an earlier broader one when it says it supersedes it; +3. explicit exclusions win over general deliverable language; +4. repository/platform-specific scope wins over generic scope; +5. the lower work level wins when ambiguity remains. + +If precedence cannot be resolved deterministically, stop and request explicit owner clarification before target-side work. + +## Prerequisite and bug-fix boundary + +An approved feature may expose an unrelated bug, missing prerequisite, migration, refactor opportunity, or infrastructure weakness. + +The worker may fix it under the existing approval only when the change is both: + +- necessary to deliver the approved user-visible behavior safely; and +- the smallest coherent change that does not add unrelated user-visible capability. + +Otherwise it requires separate approval. + +In particular, these are not automatic scope: + +- broad cleanup/refactoring; +- framework migrations; +- “while here” performance work; +- unrelated accessibility fixes; +- unrelated security hardening; +- new telemetry/analytics; +- new data migrations for future features; +- generalized provider abstractions primarily justified by unapproved future work. + +If a severe unrelated security/data-loss issue is discovered, report it immediately and follow the repository's normal emergency process; do not use the clean-room feature approval as implied authorization. + +## Design-to-implementation handoff + +An `APPROVED_FOR_DESIGN` result may recommend implementation, tests, or a changed architecture. That recommendation is not an approval upgrade. + +The worker must stop after the approved design deliverable and obtain a new approval level before target fixtures/tests or production changes. + +## Spec-change invalidation rule + +Approval applies to the behavior/scope that existed when it was granted. + +If a later research/spec edit materially expands an approved CR entry or changes its behavior, data model, privacy implications, platform reach, migration requirements, or acceptance surface, the prior approval does not automatically cover the new material. + +Use this rule: + +- editorial clarification with no scope change: approval remains valid; +- stricter test wording for the same approved behavior: approval may remain valid at the same work level; +- material behavior/scope expansion: new approval required; +- new CR ID split out of an approved feature: not approved unless the approval explicitly covered the broader named feature and the new ID is only a non-expanding subdivision; +- merged/broadened CR IDs: require reapproval when scope increases. + +When in doubt, treat the changed portion as unapproved. + +## Approval evidence sources + +Explicit approval may be recorded from: + +- the user's direct instruction in the current ChatGPT/task context; +- an explicit GitHub comment/review from the project owner that clearly grants the feature/work level; +- another authenticated project-owner channel only when its content is directly available to the worker and unambiguous. + +A recommendation, review approval, emoji/reaction, label, assignment, milestone, branch name, mergeability state, or CI status is not per-feature clean-room approval by itself. + +## Delegation rule + +A project owner may explicitly delegate approval authority to another named person/role for this program. + +Absent explicit delegation, another worker/agent/contributor cannot approve features on the owner's behalf. + +Delegation must itself be recorded with: + +- delegator; +- delegate; +- allowed approval levels; +- allowed repositories/platforms; +- allowed feature scope; +- expiration/revocation rule if any. + +There is currently no delegated approval authority recorded. diff --git a/CLEAN_ROOM_COMPETITIVE_RESEARCH.md b/CLEAN_ROOM_COMPETITIVE_RESEARCH.md new file mode 100644 index 0000000000..a86b34b8e7 --- /dev/null +++ b/CLEAN_ROOM_COMPETITIVE_RESEARCH.md @@ -0,0 +1,194 @@ +# Competitive clean-room research protocol + +Status: implementation-side policy. + +This repository may accept independently implemented features that are informed by observable product behavior. Competitive research must use a strict observer/implementer split whenever the observed product contains GPL or other source that is not authorized for reuse in Manabi-owned code. + +## Roles + +### Observer + +The observer may inspect only public user-facing material: + +- README files and end-user documentation +- changelogs and release notes +- store listings, screenshots, and demo videos +- public issues or feature requests, limited to the described user-visible behavior +- ordinary black-box behavior of released applications and hosted demos + +The observer must not copy, summarize, transform, or transmit competitor source code, source-level identifiers, comments, patches, diffs, decompilation, binary inspection, or implementation explanations. + +If a public issue or release page contains code or a patch, the observer records only the externally stated input, user action, and visible result. The code or implementation discussion is ignored. + +### Sanitizer + +The sanitizer converts observer evidence into an independently written product contract. The contract may contain: + +- capabilities +- user journeys +- state transitions +- independently authored sample inputs +- visible expected outputs +- edge-case classes +- externally measurable performance budgets +- accessibility requirements +- acceptance tests + +The contract must not contain competitor names as provenance for individual requirements, source links, quotations from release notes, source symbols, source file names, comments, patches, diffs, or descriptions of how another product implements the behavior. + +### Implementer + +The implementer receives only the sanitized specification, this policy, the approval gate, and authorized target-repository material. + +**Receipt of the clean-room handoff is not authorization to implement anything.** Before creating fixtures/tests or modifying target product code, the implementer must read `CLEAN_ROOM_APPROVALS.md` and confirm that the exact feature/CR IDs and requested work level are actively approved. + +An implementer may inspect and modify Manabi-owned or otherwise authorized target code only within an active approval, subject to the repository's existing licensing boundaries. + +The implementer must not: + +- open the observer dossier +- browse competitor repositories +- search competitor source +- read competitor patches or source-bearing PRs/issues +- use source symbols, comments, or implementation descriptions from a competitor +- mechanically reproduce a competitor's UI assets or copyrighted expression + +If the specification is insufficient, the implementer must ask for a behavior-level clarification. A clarification must be answered by the observer/sanitizer without exposing source-derived material. + +## Separation + +Named source provenance and observation notes are stored outside this implementation branch. This branch intentionally contains only implementation-side policy plus the sanitized specification. + +The observer record is not an implementation dependency and must not be copied into this repository, linked from implementation comments, or attached to implementation issues. + +## Acceptance evidence + +An implementation PR derived from this program should record: + +1. the sanitized spec revision used; +2. which acceptance-test IDs are implemented or already satisfied; +3. externally observable before/after behavior; +4. benchmark results using the specification's reference workloads; +5. an implementer attestation that no prohibited competitor implementation material was consulted. + +The attestation is process evidence, not a claim that automation can prove copyright provenance. + +## Existing third-party boundaries + +This protocol does not replace the repository's existing license notices, contribution provenance rules, or dictionary-provider boundary. Third-party components already present in the target remain governed by their own licenses and repository policy. + +This document defines the additional separation required for competitive behavior research. + +## Evidence classification + +Observer notes must distinguish how a behavior was learned: + +- **documented** — explicitly stated in public end-user documentation, store copy, or release notes; +- **reported** — described by a user or maintainer as externally visible behavior in a public issue; +- **observed** — reproduced through ordinary black-box use of a released build or hosted product; +- **inconclusive** — attempted but not reliably reproducible or blocked by environment/device/account requirements. + +A documented or reported behavior must never be rewritten as “observed” unless a black-box run actually reproduced it. + +The sanitizer may promote an edge case into an acceptance requirement even when it is only documented/reported, but the implementation contract must describe the independently chosen desired behavior rather than claiming the external product actually demonstrated it. + +## Screenshot and video rule + +Screenshots and demo videos may be used by the observer to understand: + +- available controls; +- user-visible state transitions; +- information hierarchy; +- interaction sequence; +- error/empty/loading states; +- responsive or device-specific behavior. + +They must not be used to reproduce distinctive visual expression. The sanitizer must translate screenshot evidence into functional requirements and generic usability constraints, not pixel dimensions, proprietary icons, exact copy, distinctive animation choreography, artwork, or a copied menu hierarchy. + +An implementation should follow the target product's own design system even when the behavior was prompted by screenshot evidence. + +## Black-box test boundary + +Ordinary-user testing may exercise public controls and inputs, create synthetic content, record externally visible output, and measure wall-clock latency. + +The observer must not use: + +- decompilation or package extraction; +- debugger or symbol inspection; +- source maps intended for development rather than ordinary users; +- private/internal APIs discovered by reverse engineering; +- DOM/source inspection whose purpose is to reveal implementation rather than verify visible semantics; +- network interception to infer private internal protocols. + +Publicly documented interoperability APIs may be tested as APIs, but their request/response contract must be recorded separately from any client implementation. + +## Observation record minimum fields + +Each observer record should contain: + +1. evidence ID; +2. product/build/version when known; +3. platform/browser/device; +4. evidence class; +5. public source or black-box preconditions; +6. user-visible input; +7. user action; +8. visible output; +9. uncertainty/limitations; +10. sanitized acceptance-family IDs, if any. + +Implementation workers must not receive this record. + +## Taint handling + +If prohibited implementation material is accidentally exposed to an observer note: + +1. mark that note contaminated; +2. do not sanitize from it; +3. independently reacquire the behavior from an allowed user-facing source or black-box run; +4. create a new observation record without copying language from the contaminated note; +5. only then derive or restore the sanitized acceptance requirement. + +If an implementer is exposed to prohibited competitor implementation material for a feature, that worker must not continue as the clean-room implementer for that feature. Preserve target-side work only if its independent provenance can be established by project owners/review. + +## Clarification firewall + +Implementer questions must reference sanitized requirement IDs and ask only about desired observable behavior, for example: + +- “For CR-AT-104, should punctuation remain part of sentence context?” +- “For CR-SYNC-006, should a same-revision conflict prefer local, remote, or explicit user choice?” + +The observer/sanitizer response must not name the motivating competitor or explain its mechanism. It should answer with a target-owned behavioral decision or state that the requirement remains unspecified. + +## Similarity review + +Before merging a competitively motivated UI change, reviewers should separately check: + +- the functional requirement is traceable to the sanitized contract; +- wording is target-authored; +- visual treatment follows the target design system; +- icons/artwork are target-owned or properly licensed; +- control grouping is justified by target workflows rather than copied arrangement; +- test fixtures and example content are independently authored. + +Clean-room process protects implementation provenance; it is not permission to copy protected visual expression. + +## Authorization is separate from specification severity + +Normative words in the sanitized specifications describe desired behavior **if and when that feature or qualification scope is approved**. + +They do not authorize work: + +- MUST does not mean “implement now”; +- a failing acceptance test does not authorize a fix; +- a benchmark target does not authorize optimization work; +- an optional opportunity does not authorize a prototype; +- a feature being already partially present does not authorize completion. + +`CLEAN_ROOM_APPROVALS.md` is the sole branch-local record of approval state for this program. When it says no active approvals, no target test or product mutation is authorized by these clean-room documents. + +## Research-document integration status + +On 2026-11-08, Alex authorized docs-only consolidation of this research under the request to advance all drafts and all relevant PRs. This authorizes integrating and finalizing the research documentation; it grants no CR feature design, tests, implementation, or feature integration approval. GitHub merge/closure status must be reported from integration evidence, not inferred from this document. + +The historical research remains a specification input. Its consolidation does not complete the feature program or change its approval ledger. diff --git a/CLEAN_ROOM_HANDOFF.md b/CLEAN_ROOM_HANDOFF.md new file mode 100644 index 0000000000..395a564cc4 --- /dev/null +++ b/CLEAN_ROOM_HANDOFF.md @@ -0,0 +1,147 @@ +# Clean-room implementation handoff manifest + +Status: CONSOLIDATED RESEARCH HANDOFF — NO ACTIVE FEATURE APPROVALS +Revision: 2026-11-08 docs-only consolidation + +Historical research baseline: 2026-10-03 approval-gated refinement 3. + +This manifest identifies clean research documents a future worker may read. **It does not authorize that worker to design, implement, test, prototype, integrate, or finish any feature.** + +## Approval gate comes first + +Before doing any CR-derived target work, read: + +| Path | Git blob SHA | Bytes | Purpose | +| ------------------------- | ------------------------------------------ | ----- | ---------------------------------------------------- | +| `CLEAN_ROOM_APPROVALS.md` | `cdd15a40610e43b7026e14cdc77edeac85ad8140` | 13254 | explicit per-feature/work-level authorization ledger | + +At this revision, `CLEAN_ROOM_APPROVALS.md` states **Active approvals: None** and records **no delegated approval authority**. + +Therefore no CR-derived target design, fixtures/tests, production changes, implementation PRs, or feature integration are authorized by this clean-room program. The separate docs-only consolidation authority is recorded below. + +## Sanitized research inputs + +Subject to the approval gate above, a future worker may receive these documents plus ordinary authorized target-repository material: + +| Path | Git blob SHA | Bytes | Purpose | +| ------------------------------------------------------ | ------------------------------------------ | ----- | -------------------------------------------------------------------------- | +| `CLEAN_ROOM_COMPETITIVE_RESEARCH.md` | `a86b34b8e7ecc362456b8bd60b0fea4387138ccf` | 10072 | process boundary, evidence rules, taint handling, authorization separation | +| `specs/clean-room-reader-competitive-spec.md` | `fd1269b0426ce7b526a99f985c15b4192634fcdd` | 38666 | behavior contracts, fixtures, acceptance tests, benchmarks | +| `specs/clean-room-reader-adversarial-qualification.md` | `b4249481022cb010cfcee89d5263c3766201208b` | 30518 | adversarial, sync, cache, fuzz, soak, cross-engine qualification | +| `specs/clean-room-reader-feature-opportunities.md` | `61383888e92c7d56959ed70d71d8a54230c60be8` | 56918 | DISCOVERY_ONLY optional feature registry | + +Research reviewers may also use: + +| Path | Git blob SHA | Bytes | Purpose | +| ---------------------- | ------------------------------------------ | ----- | ------------------------------------------ | +| `CLEAN_ROOM_REVIEW.md` | `78c9f31c12b5eb7ad520bea92712d59ca9da1cfb` | 9497 | research-only consistency/review checklist | + +The review checklist is not an implementation authority or approval source. + +## Default worker authority + +With no active approval, a worker may only do research/specification work that the user explicitly requests on these documents, such as: + +- review wording; +- deduplicate requirements; +- identify target-side overlap; +- refine acceptance criteria; +- audit approval/manifest consistency; +- report which feature/CR IDs would need approval. + +The worker must not create target design deliverables, fixtures/tests, or modify product/runtime code from these documents. + +## Approval levels + +Only `CLEAN_ROOM_APPROVALS.md` defines authority. Current levels are: + +- `DISCOVERY_ONLY` +- `APPROVED_FOR_DESIGN` +- `APPROVED_FOR_TESTS` +- `APPROVED_FOR_IMPLEMENTATION` +- `APPROVED_FOR_INTEGRATION` + +A higher level is not inferred from a lower one. Design does not authorize tests; tests do not authorize production fixes; implementation does not authorize integration. + +## Per-feature approval rule + +A target-side action requires an active approval that names: + +- the feature/CR IDs; +- approval level; +- target repository/platform; +- bounded deliverable; +- approval basis/spec revision or equivalent explicit scope; +- exclusions/constraints. + +Approval is non-transitive and cannot be self-created by a worker. + +In particular: + +- `CR-OPP-*` remains DISCOVERY_ONLY until individually selected; +- MUST/SHOULD language is not authorization; +- a failing test/benchmark is not authorization; +- approval of tests is not approval of fixes; +- approval of one feature is not approval of an adjacent feature; +- approval on one platform is not approval on another; +- a generic instruction such as “continue,” “go deeper,” “review,” “refine,” “finish,” or “work through the backlog” is not per-feature implementation approval; +- a later material spec expansion is not automatically covered by an older approval. + +## Research-document integration status + +On 2026-11-08, Alex authorized docs-only consolidation of this research under the request to advance all drafts and all relevant PRs. This authorizes integrating and finalizing the research documentation; it grants no CR feature design, tests, implementation, or feature integration approval. GitHub merge/closure status must be reported from integration evidence, not inferred from this document. + +All `CR-OPP-*` entries remain DISCOVERY_ONLY. Active feature approvals and delegated approval authority remain None. + +## Not authorized + +The worker must not receive or request: + +- observer dossiers or evidence ledgers; +- named-source provenance; +- external implementation repositories; +- external source code, patches, diffs, comments or source-level identifiers; +- contaminated observation notes; +- copied third-party fixtures or distinctive UI assets. + +The worker must not independently research the external products that motivated the sanitized requirements. + +## Worker startup checklist + +Before any target-side work: + +1. verify the approval-ledger blob SHA and read it; +2. verify the sanitized research blob SHAs above; +3. confirm an active approval exactly covers the requested CR IDs and work level; +4. verify that the approval basis still matches the current relevant spec revision/scope; +5. if no matching approval exists, stop target-side execution and report the required approval; +6. do not perform external competitor research; +7. inspect current target-owned architecture for overlap only within the user's requested review/approved scope; +8. preserve existing working primitives rather than rebuilding them to resemble another product. + +## Approved-work execution + +Only after a matching approval exists: + +1. restate the approval ID, CR IDs, work level, target, approval basis, deliverable and exclusions; +2. if approved for design, stop after the bounded design deliverable; +3. if approved for tests, create only independently authored fixtures/tests and stop at reported failures; +4. if approved for implementation, make only the bounded target-owned changes needed for the approved IDs; +5. if adjacent unapproved work is discovered, report it rather than “finishing it while here”; +6. obey the minimal-shared-primitive rule in the approval ledger; +7. run only qualification/benchmark/device work included in approval; +8. mark the approval record completed when the bounded work is done. + +## Worker completion attestation + +An implementation PR for an approved feature should include a statement equivalent to: + +> I implemented and qualified only the approved CR scope using the sealed clean-room handoff and authorized target-repository material. I did not consult prohibited external implementation material or the observer-side provenance record, and I did not expand into unapproved adjacent features. + +## Manifest updates + +Any change to the approval ledger, research-review checklist, or one of the four sanitized research documents changes its blob SHA and requires a new manifest revision before handoff. + +A stale manifest is invalid for clean implementation handoff. + +This manifest itself contains no external source provenance and may be supplied to a future worker. diff --git a/CLEAN_ROOM_REVIEW.md b/CLEAN_ROOM_REVIEW.md new file mode 100644 index 0000000000..78c9f31c12 --- /dev/null +++ b/CLEAN_ROOM_REVIEW.md @@ -0,0 +1,282 @@ +# Clean-room research PR review checklist + +Status: research-review aid only +Revision: 2026-11-08 docs-only consolidation + +Historical research baseline: 2026-10-03. + +This checklist is for reviewing PR #260 as a research/specification artifact. + +It is not an implementation plan, approval record, or completion signal. + +## 1. Research-document integration state + +On 2026-11-08, Alex authorized docs-only consolidation of this research under the request to advance all drafts and all relevant PRs. This authorizes integrating and finalizing the research documentation; it grants no CR feature design, tests, implementation, or feature integration approval. GitHub merge/closure status must be reported from integration evidence, not inferred from this document. + +Verify: + +- integration contains only the selected research/specification documents and bounded governance corrections from #260; +- PR descriptions distinguish research integration from feature completion; +- actual GitHub merge/closure status is supported by integration evidence; +- no implementation work or new feature approval is attributed to these documents. + +## 2. Approval gate + +Read `CLEAN_ROOM_APPROVALS.md` before interpreting any CR document. + +Verify: + +- active approvals are exactly what explicit owner instructions support; +- workers have not self-created/broadened approval; +- approval levels match the allowed deliverable; +- approval basis still matches the current relevant spec revision/scope; +- completed/revoked/superseded records cannot be reused as active authority; +- no implicit delegation exists. + +When Active approvals is None, no CR-derived target tests, fixtures, product changes, implementation PRs, or feature integration are authorized. + +## 3. Separation of authority and quality language + +Check that: + +- MUST/SHOULD/MAY only express quality inside approved scope; +- failed tests do not imply permission to fix; +- benchmarks do not imply optimization authority; +- a feature being easy/high-value does not imply approval; +- an opportunity being detailed does not imply priority; +- optional opportunity entries remain DISCOVERY_ONLY. + +Search for newly added wording that could accidentally read like: + +- “implement next”; +- “worker should now build”; +- “finish these phases”; +- “release blocker” without approval context; +- “strong candidates” as implied queue; +- “all remaining work”. + +Repair ambiguous authority language before expanding the research. + +## 4. Per-feature boundary + +For any active approval, verify: + +- exact CR IDs or uniquely mapped named feature; +- approval level; +- target repository/platform; +- bounded deliverable; +- approval basis/spec revision; +- exclusions; +- status. + +Check that adjacent work is listed as unapproved rather than bundled. + +Check the minimal-shared-primitive rule: + +- required for approved behavior; +- minimum coherent abstraction; +- no unrelated user-visible capability; +- no speculative preimplementation; +- no broad future-facing refactor hidden inside the approved change. + +## 5. Observer / implementer firewall + +Implementation-side files must contain no named-source provenance. + +Verify: + +- no motivating product/vendor names; +- no external source URLs; +- no external GitHub links; +- no copied screenshots/assets; +- no source symbols/file paths from competitors; +- no implementation descriptions from external projects; +- no observer evidence IDs that reveal named provenance. + +The observer dossier/evidence ledger must remain outside the implementation repository. + +A clean implementation worker must not receive those observer artifacts. + +## 6. Evidence hygiene + +Observer-side review should distinguish: + +- documented; +- reported; +- observed; +- inconclusive. + +Do not promote release-note or issue claims into black-box observations. + +If prohibited material contaminated an observation: + +- quarantine it; +- reacquire from allowed behavior/user-facing evidence; +- sanitize from the new clean observation only. + +## 7. CR namespace integrity + +For the three CR specification files: + +- every CR definition heading is unique; +- references may repeat IDs, but definitions must not; +- intentional numeric gaps are acceptable; +- counts in PR prose must describe actual entries accurately; +- adding/splitting/merging CR IDs must not silently change approval scope. + +The opportunity registry currently uses topical numeric bands, so the largest CR-OPP number is not the number of entries. + +## 8. Target overlap + +Before calling an opportunity “new,” inspect authorized target-owned architecture. + +Classify it as: + +1. already satisfied; +2. qualification/test gap; +3. UX exposure of existing primitive; +4. bounded extension of existing primitive; +5. genuinely new primitive. + +Do not create a second implementation of an existing target primitive to mirror external products. + +Keep overlap notes target-side and source-clean. + +## 9. Opportunity backlog quality + +Each CR-OPP should: + +- describe user value; +- remain implementation-neutral; +- state important privacy/durability constraints; +- avoid distinctive copied UI wording; +- avoid bundling several unrelated features into one approval unit; +- be separable enough for per-feature approval; +- identify when it is an extension of existing target architecture. + +If two opportunities cannot realistically be approved independently, consider merging or explicitly declaring their dependency. + +## 10. Correctness-spec quality + +Acceptance requirements should be: + +- externally observable; +- deterministic where practical; +- independent of competitor implementation; +- testable with project-owned fixtures; +- explicit about optional/platform-specific behavior; +- careful about Unicode and semantic-vs-visual boundaries; +- explicit about cancellation/stale async state; +- explicit about destructive/sync conflict behavior. + +Avoid turning one product's historical bug wording into a permanent target requirement unless the desired behavior independently makes sense for Manabi. + +## 11. Benchmark quality + +Benchmark targets should: + +- measure the product boundary; +- state environment/fixture; +- separate cold/warm; +- report median/p95/max where appropriate; +- avoid pretending one machine threshold is universal; +- distinguish provider/network latency from local application latency; +- never create approval to optimize merely because a threshold is missed. + +## 12. Data, privacy, and migration review + +For any opportunity/spec change involving data: + +- identify durable vs derived state; +- define deletion semantics; +- define account/profile scope; +- define exportability where relevant; +- identify network processing; +- define migration/backward compatibility implications; +- avoid making a derived cache authoritative. + +Any material new privacy/network/migration implication invalidates prior approval unless already included in its bounded scope. + +## 13. Platform review + +Do not treat: + +- browser emulation as physical-device qualification; +- web approval as Android approval; +- Android approval as iOS approval; +- desktop input assumptions as touch/controller behavior. + +Platform expansion requires explicit scope. + +## 14. Research-PR shape + +PR #260 should remain research/specification only. + +If product code, target test fixtures, implementation workflows, generated binary assets, or feature-specific runtime changes appear in this PR, treat that as a scope violation unless the project owner explicitly re-scoped PR #260 itself. + +Prefer separate approved implementation PRs for target changes. + +## 15. Handoff manifest + +After any authorized research-document change: + +1. recompute/fetch changed Git blob SHAs; +2. update `CLEAN_ROOM_HANDOFF.md`; +3. verify the approval-ledger SHA first; +4. verify sanitized research hashes; +5. rerun contamination checks; +6. update the pinned handoff PR comment. + +A stale manifest must not be used for implementation handoff. + +## 16. PR description / handoff comment + +Verify they state: + +- research-document integration status and its evidence; +- Active approvals; +- no implied implementation authority; +- per-feature approval requirement; +- exact current manifest/approved input identity; +- opportunity count accurately; +- no competitor provenance; +- no product code changes; +- adjacent work stop rule. + +Old handoff comments should be superseded rather than leaving conflicting current instructions. + +## 17. Feature-completion boundary + +Research refinement has no autonomous “complete the whole backlog” step. + +A future worker may finish only the bounded research task explicitly requested in its turn. + +It must not: + +- implement the backlog to make the PR “complete”; +- mark every CR as handled; +- infer merge authority from this checklist alone; +- convert research recommendations into a roadmap without explicit owner direction. + +A passing review means only that the research artifact is internally consistent at that revision. + +## 18. Review record template + +For a research review, record: + +- PR head SHA: +- research-document integration status/evidence: +- approval-ledger SHA: +- active approvals: +- handoff-manifest SHA: +- CR definition duplicate check: +- contamination scan: +- target-overlap changes: +- authority-language findings: +- stale-hash findings: +- research-only file-shape check: +- corrections made: +- unresolved questions: +- result: CONSISTENT / NEEDS_REFINEMENT + +Distinguish a consistent research review, an authorized docs-only integration, and separately approved feature completion. Record each only when supported by its own evidence. diff --git a/apps/web/package.json b/apps/web/package.json index c17d1d5c57..5419306847 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -51,6 +51,7 @@ "fake-indexeddb": "6.2.5", "fast-xml-parser": "5.11.1", "idb": "8.0.3", + "marked": "17.0.6", "mediabunny": "1.59.1", "onnxruntime-web": "1.29.0", "p-limit": "7.3.2", diff --git a/apps/web/src/features/statistics/StatisticsScreen.tsx b/apps/web/src/features/statistics/StatisticsScreen.tsx index bfaeda1a7f..8a29eefbd5 100644 --- a/apps/web/src/features/statistics/StatisticsScreen.tsx +++ b/apps/web/src/features/statistics/StatisticsScreen.tsx @@ -9,7 +9,7 @@ import { AppFrame } from '../../shared-ui/AppFrame'; import { UiIcon } from '../../shared-ui/UiIcon'; import { RouteBack } from '../../shared-ui/RouteBack'; import { UiText as Text } from '../../shared-ui/Typography'; -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState, type ComponentRef } from 'react'; import { ActivityIndicator, ScrollView, View, StyleSheet, useWindowDimensions } from 'react-native'; import { ActionButton, @@ -31,6 +31,7 @@ import { useStatisticsPort } from './ports'; import { useStatisticsController } from './use-statistics'; import { StatisticsSettings } from './StatisticsSettings'; import { StatisticsSummary } from './StatisticsSummary'; +import { usePagerKeyboardFocus } from '../../shared-ui/usePagerKeyboardFocus'; import { StatisticsHeatmap } from './StatisticsHeatmap'; import { StatisticsTitleFilter, StatisticsTitleFilterFooter } from './StatisticsTitleFilter'; import { ShortcutListener } from '../../shared-ui/ShortcutListener'; @@ -93,7 +94,16 @@ export function StatisticsView({ const { colors } = useUiTheme(); const { width, height, fontScale } = useWindowDimensions(); const [optionsOpen, setOptionsOpen] = useState(false); + const optionsTrigger = useRef | null>(null); const [newDayBook, setNewDayBook] = useState(''); + // Page reads temporarily replace Summary with loading UI. Focus ownership + // belongs to the retained route, so it survives that loading transition. + const previousPage = useRef | null>(null); + const nextPage = useRef | null>(null); + const choosePage = useRef | null>(null); + const pagerControls = { previous: previousPage, next: nextPage, choose: choosePage }; + const capturePageFocus = usePagerKeyboardFocus(state.query.page, state.busy, pagerControls); + const pager = { ...pagerControls, captureFocus: capturePageFocus }; const pageSize = summaryPageSize(width, height, fontScale); useEffect(() => { if (state.query.pageSize !== pageSize && !state.busy && !state.editor) @@ -103,6 +113,8 @@ export function StatisticsView({ const maxWidth = width >= 1536 ? 1152 : width >= 1024 && width < 1280 ? 896 : undefined; const beginSettings = () => { setOptionsOpen(false); + // The menu item unmounts; retain a connected return target for the sheet. + optionsTrigger.current?.focus(); void dispatch({ type: 'settings', open: true }); }; return ( @@ -151,6 +163,7 @@ export function StatisticsView({ variant="ghost" size="icon-lg" shape="circle" + ref={optionsTrigger} accessibilityLabel="Statistics options" title="Statistics options" aria-haspopup="menu" @@ -322,7 +335,7 @@ export function StatisticsView({ Loading statistics… ) : state.view === 'summary' ? ( - + ) : ( <> @@ -349,6 +362,7 @@ export function StatisticsView({ visible={state.settingsOpen} onClose={() => void dispatch({ type: 'settings', open: false })} title="Statistics options" + stickyChrome description="Choose your date range, measurements, and export format." closeLabel="Close statistics options" closeDisabled={state.busy} diff --git a/apps/web/src/features/statistics/StatisticsSummary.tsx b/apps/web/src/features/statistics/StatisticsSummary.tsx index e43a2b4cd6..03804de58d 100644 --- a/apps/web/src/features/statistics/StatisticsSummary.tsx +++ b/apps/web/src/features/statistics/StatisticsSummary.tsx @@ -7,7 +7,7 @@ import { AnchoredPopover } from '../../shared-ui/AnchoredPopover'; import { UiIcon } from '../../shared-ui/UiIcon'; import { UiText as Text } from '../../shared-ui/Typography'; -import { useState, type ComponentRef } from 'react'; +import { useState, type ComponentRef, type RefObject } from 'react'; import { FlatList, Pressable, View, StyleSheet, useWindowDimensions } from 'react-native'; import { ActionButton, @@ -31,7 +31,17 @@ import { type StatisticsViewProps } from './view-model'; -export function StatisticsSummary({ state, dispatch }: StatisticsViewProps) { +export type StatisticsSummaryPager = { + previous: RefObject | null>; + next: RefObject | null>; + choose: RefObject | null>; + captureFocus(source: unknown, preferred?: 'previous' | 'next' | 'choose'): void; +}; +export function StatisticsSummary({ + state, + dispatch, + pager +}: StatisticsViewProps & { pager: StatisticsSummaryPager }) { const { colors } = useUiTheme(); const { width } = useWindowDimensions(); const [details, setDetails] = useState<{ @@ -129,7 +139,7 @@ export function StatisticsSummary({ state, dispatch }: StatisticsViewProps) { title="Click to select/sort by this Attribute" disabled={!!editor || state.busy} onPress={() => sort(column.key)} - size="icon-sm" + size="icon-lg" shape="rounded" style={{ paddingHorizontal: 4 }} > @@ -246,7 +256,7 @@ export function StatisticsSummary({ state, dispatch }: StatisticsViewProps) { 1 && ( + + Page {q.page} of {data?.pages} + void dispatch({ type: 'query', patch: { page: q.page - 1 } })} + onPress={(event) => { + pager.captureFocus(event.currentTarget); + void dispatch({ type: 'query', patch: { page: q.page - 1 } }); + }} > { @@ -391,9 +415,14 @@ export function StatisticsSummary({ state, dispatch }: StatisticsViewProps) { = (data?.pages ?? 1)} - onPress={() => void dispatch({ type: 'query', patch: { page: q.page + 1 } })} + onPress={(event) => { + pager.captureFocus(event.currentTarget); + void dispatch({ type: 'query', patch: { page: q.page + 1 } }); + }} > @@ -445,9 +474,11 @@ export function StatisticsSummary({ state, dispatch }: StatisticsViewProps) { { + style={{ height: 44, minHeight: 44, paddingVertical: 0 }} + onPress={(event) => { + pager.captureFocus(event.currentTarget, 'choose'); setPagesOpen(false); void dispatch({ type: 'query', patch: { page } }); }} diff --git a/apps/web/src/lib/components/book-export/book-export-selection.svelte b/apps/web/src/lib/components/book-export/book-export-selection.svelte index 530fa924b4..c8a32ca1b8 100644 --- a/apps/web/src/lib/components/book-export/book-export-selection.svelte +++ b/apps/web/src/lib/components/book-export/book-export-selection.svelte @@ -41,55 +41,55 @@
Export content
-
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 210bf5f32f..d1279ad355 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 @@ -1,4 +1,5 @@ - -
-
+ +
+
-

Contents

-

{bookTitle}

+

Contents

- {#if currentChapter} -
-

Current chapter

-

- {currentChapter.label || `Chapter ${currentChapterIndex + 1}`} -

- {#if currentChapterProgress !== undefined} -
+
+

+ {bookTitle} +

+ {#if currentChapter} +
+

Current chapter

+

+ {currentChapter.label || `Chapter ${currentChapterIndex + 1}`} +

+ {#if currentChapterProgress !== undefined}
-
- {/if} -

- {currentChapterProgress === undefined - ? 'Progress unavailable' - : `${Number(currentChapterProgress.toFixed(2))}%`} - {#if characterProgress} - · {characterProgress.read} / {characterProgress.total} characters + class="mt-3 h-1 overflow-hidden rounded-full bg-foreground/10" + role="progressbar" + aria-label="Chapter progress" + aria-valuemin={0} + aria-valuemax={100} + aria-valuenow={currentChapterProgress} + > +

+
{/if} -

-
- {/if} -
+ {/if} + +
+ + - - {chapter.label || `Chapter ${index + 1}`} - - {#if chapter.progress === 100}{:else if index === currentChapterIndex}{/if} - - {:else} -

No chapters available for this book.

- {/each} - -
- - -
+
+
diff --git a/apps/web/src/lib/components/statistics/statistics-settings.svelte b/apps/web/src/lib/components/statistics/statistics-settings.svelte index 46b0b96eae..1dee069cee 100644 --- a/apps/web/src/lib/components/statistics/statistics-settings.svelte +++ b/apps/web/src/lib/components/statistics/statistics-settings.svelte @@ -65,157 +65,213 @@
- -
- Statistics options - dispatch('close')} - /> +
+ +
+ Statistics options + dispatch('close')} + /> +
+ Choose your date range, measurements, and export format.
- Choose your date range, measurements, and export format. -
- Date range -
-
- - -
-
- - -
-
- - - dispatch('statisticsDateChange', { - isStartDate: true, - dateString: event.currentTarget.value - })} - /> +
+
+ Date range +
+
+ + +
+
+ + +
+
+ + + dispatch('statisticsDateChange', { + isStartDate: true, + dateString: event.currentTarget.value + })} + /> +
+
+ + + dispatch('statisticsDateChange', { + isStartDate: false, + dateString: event.currentTarget.value + })} + /> +
-
- - +
+
-
-
- - - -
-
-
- Measurements -

- Choose which values appear in the summary and how the reading data is grouped. -

-
-
- - + dateString: selectedStatisticsStartDate + })}>Use start date for both + +
-
- - +
+
+ Measurements +

+ Choose which values appear in the summary and how the reading data is grouped. +

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
-
- - +
+
+ Export history +

+ Raw history preserves book identities, unresolved legacy days, and migration receipts for + recovery; it is not a TTU import file. The TTU ZIP exports use titles and cannot preserve + book identities. +

+
+ + +
-
- - +
+
+ Manage history + + + +
+ +
-
-
-
- Export history -

- Raw history preserves book identities, unresolved legacy days, and migration receipts for - recovery; it is not a TTU import file. The TTU ZIP exports use titles and cannot preserve - book identities. -

-
- - - -
-
-
- Manage history - - - -
- - -
-
+ +
diff --git a/apps/web/src/lib/snippets/database.ts b/apps/web/src/lib/snippets/database.ts index b36f34fb17..16d6bbb6d5 100644 --- a/apps/web/src/lib/snippets/database.ts +++ b/apps/web/src/lib/snippets/database.ts @@ -11,6 +11,7 @@ import { integrationDB, equal } from '../manabi/persistence'; import { commitTransaction } from '$lib/data/database/books-db/commit-transaction.mjs'; import { requestPersistentStorageOnce } from '$lib/data/window/navigator/persistent-storage'; import type { SourceDescriptor } from '../library/catalog'; +import { sourceKey } from '../library/organization-keys'; import { canonical, retainRemoteAncestor, @@ -214,7 +215,9 @@ export async function acceptRemote( owner: string, document: SnippetDocument, location: Location, - guard: Guard + guard: Guard, + activeSources?: ReadonlySet, + authoritativeAbsentSources?: ReadonlySet ) { location = { ...location, observedRevision: document.revision, missing: false }; return mutateRecord(owner, document.id, guard, (current) => { @@ -234,27 +237,77 @@ export async function acceptRemote( locations = [...current.locations.filter((item) => locationKey(item) !== key), location]; const previous = current.locations.find((item) => locationKey(item) === current.primary); const primaryMissing = previous?.missing && !current.transfer && !current.conflicts.length; - const relocated = - primaryMissing || current.primary === key - ? { - primary: key, - destination: location, - remoteRevision: document.revision, - issue: undefined - } - : {}; - // Discovery cannot adopt provider changes while a move or exact upload owns the document. + const incomingActive = activeSources?.has(sourceKey(location.source)) ?? false; + const primaryUnavailable = + !!activeSources && + !!authoritativeAbsentSources && + incomingActive && + !!previous && + authoritativeAbsentSources.has(sourceKey(previous.source)); + const uploadUnavailable = + !!authoritativeAbsentSources && + !!current.upload && + authoritativeAbsentSources.has(sourceKey(current.upload.destination.source)); + const rebindable = + !current.transfer && + (!current.upload || uploadUnavailable) && + !current.conflicts.length && + (primaryMissing || primaryUnavailable || current.primary === key); + const relocated = rebindable + ? { + primary: key, + destination: location, + remoteRevision: document.revision, + issue: undefined + } + : {}; + + // A move owns source/destination identity until its journal settles. if (current.transfer) return { ...current, locations }; - if (current.upload && canonical(current.upload.document) === canonical(document)) + + // A pending immutable upload to a still-active source owns its exact retry. + if ( + current.upload && + !uploadUnavailable && + canonical(current.upload.document) === canonical(document) + ) return { ...current, locations }; + if (canonical(current.document) === canonical(document)) - return { ...current, ...relocated, locations }; + return { + ...current, + ...relocated, + ...(rebindable + ? { + upload: uploadUnavailable ? undefined : current.upload, + dirty: false + } + : {}), + locations + }; + + // A reconnected location can contain the last acknowledged ancestor while + // this browser has a newer local descendant. Bind that remote ancestor as + // the expected revision, preserve the local document, and republish it. + if ( + rebindable && + (primaryMissing || primaryUnavailable) && + current.document.parents.includes(document.revision) + ) + return { + ...current, + ...relocated, + upload: uploadUnavailable ? undefined : current.upload, + dirty: true, + locations + }; + + // Bounded ancestry may no longer contain the acknowledged revision. if (primaryMissing && current.dirty && document.revision === current.remoteRevision) return { ...current, ...relocated, locations }; - // A causally newer copy is the same logical snippet, regardless of which - // provider happened to be scanned first in this browser. The primary home - // is local metadata and cannot make a stale ancestor win after reinstall. - // Concurrent siblings still become explicit conflicts. + + // A causally newer clean copy is the same logical snippet regardless of + // provider discovery order. Concurrent siblings remain explicit conflicts. if ( !current.dirty && !current.transfer && @@ -271,6 +324,7 @@ export async function acceptRemote( remoteRevision: document.revision, issue: undefined }; + if (current.document.parents.includes(document.revision)) return { ...current, locations }; const conflicts = current.conflicts.filter((other) => canonical(other) !== canonical(document)); if (conflicts.length >= 8) diff --git a/apps/web/src/lib/snippets/document.ts b/apps/web/src/lib/snippets/document.ts index 17774c277b..a7c7cf8996 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); @@ -155,7 +171,7 @@ export function validateContent(value: unknown): asserts value is TextNode { fail(); if ( attrs.start !== undefined && - (!Number.isInteger(attrs.start) || Number(attrs.start) < 1 || Number(attrs.start) > 1000000) + (!Number.isInteger(attrs.start) || Number(attrs.start) < 0 || Number(attrs.start) > 1000000) ) fail(); if (attrs.type != null && !['1', 'a', 'A', 'i', 'I'].includes(String(attrs.type))) fail(); @@ -192,6 +208,9 @@ export function validateContent(value: unknown): asserts value is TextNode { fail(); if (mark.attrs.target != null && !['_blank', '_self'].includes(String(mark.attrs.target))) fail(); + // Version 1 already permits bounded authored rel metadata, including + // empty and opener values. Preserve its portable identity on read; + // rendering and editor DOM enforce safe link relationships separately. if (mark.attrs.rel != null && !validText(mark.attrs.rel, 120)) fail(); if ( mark.attrs.class != null || diff --git a/apps/web/src/lib/snippets/editor.ts b/apps/web/src/lib/snippets/editor.ts index 0080c343dc..9234d3697d 100644 --- a/apps/web/src/lib/snippets/editor.ts +++ b/apps/web/src/lib/snippets/editor.ts @@ -10,24 +10,56 @@ import { generateJSON, getSchema, type Extensions, - type JSONContent + type JSONContent, + type Mark } from '@tiptap/core'; import StarterKit from '@tiptap/starter-kit'; import RubyText from '@tiptap/extension-ruby-text'; import UniqueID from '@tiptap/extension-unique-id'; import { Markdown, MarkdownManager } from '@tiptap/markdown'; +import { Marked, marked } from 'marked'; import DOMPurify from 'dompurify'; +import { snippetLinkPresentation } from './presentation.ts'; import { identifyBlocks, MAX_SNIPPET_BYTES, plainContent, validateContent, type TextNode -} from './document'; +} from './document.ts'; + +function isolatedMarked(): typeof marked { + // TipTap's option type names the callable singleton, but MarkdownManager only + // consumes its Marked-instance surface (defaults/Lexer/use/setOptions). Upstream + // recommends a private Marked instance to avoid global tokenizer accumulation. + return new Marked() as unknown as typeof marked; +} + +// Keep the canonical mark attributes in the editor model. Only their DOM +// projection is hardened, including marks introduced after editor creation. +const DisplaySafeStarterKit = StarterKit.extend({ + addExtensions() { + return (this.parent?.() ?? []).map((extension) => + extension.name === 'link' + ? (extension as Mark).extend({ + renderHTML(properties) { + if (!this.parent) throw new Error('Snippet link renderer is unavailable.'); + const { HTMLAttributes } = properties; + // Preserve the upstream renderer's URI checks and configured attrs. + return this.parent({ + ...properties, + HTMLAttributes: { ...HTMLAttributes, ...snippetLinkPresentation(HTMLAttributes) } + }); + } + }) + : extension + ); + } +}); export function extensions(): Extensions { return [ - StarterKit.configure({ + DisplaySafeStarterKit.configure({ link: { openOnClick: false, autolink: false, @@ -49,13 +81,13 @@ export function extensions(): Extensions { 'horizontalRule' ] }), - Markdown + Markdown.configure({ marked: isolatedMarked() }) ]; } export function cleanHTML(html: string): string { if (new TextEncoder().encode(html).length > MAX_SNIPPET_BYTES) throw new Error('Pasted content exceeds the 2 MiB limit.'); - return DOMPurify.sanitize(html, { + const sanitized = DOMPurify.sanitize(html, { ALLOWED_TAGS: [ 'p', 'div', @@ -87,9 +119,10 @@ 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'], + // These are validated link metadata, never URL-bearing attributes. + ADD_URI_SAFE_ATTR: ['data-id', 'start', 'type', 'title', 'target', 'rel'], FORBID_TAGS: [ 'style', 'script', @@ -104,18 +137,33 @@ export function cleanHTML(html: string): string { ], ALLOWED_URI_REGEXP: /^(?:https?:|mailto:)/i }); + // This fragment is detached and already sanitized. Avoid process-global + // DOMPurify hooks; paste and HTML export get the same safe DOM attributes. + const fragment = document.createElement('template'); + fragment.innerHTML = sanitized; + for (const anchor of fragment.content.querySelectorAll('a')) { + const link = snippetLinkPresentation({ + target: anchor.getAttribute('target'), + rel: anchor.getAttribute('rel') + }); + anchor.setAttribute('target', link.target); + anchor.setAttribute('rel', link.rel); + } + return fragment.innerHTML; +} +export function markdownHTML(value: string): string { + // TipTap 3.31.x registers an experimental ordered-list tokenizer which treats + // alphabetic/roman sentence prefixes (for example "Hi. there") as list markers. + // Import only needs CommonMark -> HTML, so use an isolated vanilla Marked lexer. + // Never share its tokenizer registry with an editor or another import. + return new Marked().parse(value, { async: false }); } export function importContent(value: string, format: 'text' | 'html' | 'markdown'): TextNode { if (new TextEncoder().encode(value).length > MAX_SNIPPET_BYTES) throw new Error('Pasted content exceeds the 2 MiB limit.'); if (format === 'text') return plainContent(value); // Markdown HTML also goes through the same DOM sanitization boundary. - const html = - format === 'html' - ? value - : (new MarkdownManager({ extensions: extensions() }).instance.parse(value, { - async: false - }) as string); + const html = format === 'html' ? value : markdownHTML(value); const content = identifyBlocks(generateJSON(cleanHTML(html), extensions()) as TextNode, true); validateContent(content); getSchema(extensions()).nodeFromJSON(content).check(); @@ -123,14 +171,46 @@ export function importContent(value: string, format: 'text' | 'html' | 'markdown } export function renderContent(content: TextNode): string { validateContent(content); - return cleanHTML(generateHTML(content as JSONContent, extensions())); + return cleanHTML(generateHTML(structuredClone(content) as JSONContent, extensions())); +} +export function requiresHTMLMarkdown(content: TextNode): boolean { + // CommonMark/GFM has no lossless syntax for ruby or underline. It also cannot + // represent HTML ordered-list marker styles, and TipTap 3.31.x rewrites a + // valid zero start to one. Raw HTML is valid Markdown, so prefer that over + // silently erasing authored semantics. + if (content.marks?.some((mark) => mark.type === 'rubyText' || mark.type === 'underline')) + return true; + if ( + content.type === 'orderedList' && + (content.attrs?.start === 0 || + (content.attrs?.type !== undefined && + content.attrs?.type !== null && + content.attrs?.type !== '1')) + ) + return true; + // A non-default imported HTML link has semantics Markdown cannot carry. + if ( + content.marks?.some( + (mark) => + mark.type === 'link' && + (mark.attrs?.target === '_self' || + (mark.attrs?.rel !== undefined && + mark.attrs?.rel !== null && + mark.attrs?.rel !== 'noopener noreferrer nofollow')) + ) + ) + return true; + return content.content?.some(requiresHTMLMarkdown) ?? false; } export function exportMarkdown(content: TextNode): string { - // CommonMark has no ruby construct. Raw HTML is valid Markdown and preserves it losslessly. - const hasRuby = JSON.stringify(content).includes('"rubyText"'); - return hasRuby + // CommonMark has no ruby construct. TipTap 3.31.x also serializes a valid + // zero-start ordered list as starting at one. Raw HTML is valid Markdown and + // is the lossless representation for either case. + return requiresHTMLMarkdown(content) ? renderContent(content) + '\n' - : new MarkdownManager({ extensions: extensions() }).serialize(content as JSONContent); + : new MarkdownManager({ extensions: extensions(), marked: isolatedMarked() }).serialize( + content as JSONContent + ); } export function createEditor( element: HTMLElement, @@ -143,7 +223,8 @@ export function createEditor( return new Editor({ element, extensions: configured, - content: content as JSONContent, + // TipTap owns this working copy; read/render must not mutate saved JSON. + content: structuredClone(content) as JSONContent, editorProps: { attributes: { class: 'snippet-editable', diff --git a/apps/web/src/lib/snippets/presentation.ts b/apps/web/src/lib/snippets/presentation.ts index b8a6bd84f7..62c772dac4 100644 --- a/apps/web/src/lib/snippets/presentation.ts +++ b/apps/web/src/lib/snippets/presentation.ts @@ -4,7 +4,13 @@ * All rights reserved. */ -import { safeLink, validateContent, type TextNode, type SnippetLocator, isUUID } from './document'; +import { + safeLink, + validateContent, + type TextNode, + type SnippetLocator, + isUUID +} from './document.ts'; import type { SnippetRecord } from './database'; import type { SnippetSummary } from './summary'; @@ -13,6 +19,26 @@ const escape = (text: unknown) => /[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]! ); +/** Display attributes never become a migration of the portable document. + * Keep inert authored relationships, but a new tab must never retain an opener. */ +export function snippetLinkPresentation(attrs: Record | undefined) { + const target = attrs?.target === '_self' ? '_self' : '_blank'; + const rel = typeof attrs?.rel === 'string' ? attrs.rel : target === '_blank' ? 'nofollow' : ''; + const tokens = rel.split(/\s+/).filter((token) => token && token.toLowerCase() !== 'opener'); + if (target === '_blank') { + const safe = ['noopener', 'noreferrer']; + for (const token of tokens) { + if (['noopener', 'noreferrer'].includes(token.toLowerCase())) continue; + // Keep exported HTML re-importable within v1's metadata bound. Whole + // optional tokens may be omitted from this display projection only; + // the canonical document and editor model retain their original rel. + if ([...safe, token].join(' ').length <= 120) safe.push(token); + } + return { target, rel: safe.join(' ') }; + } + return { target, rel: tokens.join(' ') }; +} + /** Closed-schema rendering does not load the editor, accept arbitrary HTML, or save reader decorations. */ export function readerHTML(content: TextNode): string { validateContent(content); @@ -29,8 +55,10 @@ export function readerHTML(content: TextNode): string { if (tag) html = `<${tag}>${html}`; else if (mark.type === 'rubyText') html = `${html}${escape(mark.attrs?.rt)}`; - else if (mark.type === 'link' && safeLink(mark.attrs?.href)) - html = `${html}`; + else if (mark.type === 'link' && safeLink(mark.attrs?.href)) { + const link = snippetLinkPresentation(mark.attrs); + html = `${html}`; + } } return html; } diff --git a/apps/web/src/lib/snippets/service.ts b/apps/web/src/lib/snippets/service.ts index 468dcd3422..fb0de1a8cb 100644 --- a/apps/web/src/lib/snippets/service.ts +++ b/apps/web/src/lib/snippets/service.ts @@ -13,6 +13,7 @@ import { librarySource, scanCatalog, sourceDescriptors, + sourceSnapshot, type Catalog, type SourceDescriptor } from '../library/catalog'; @@ -191,8 +192,32 @@ export async function refreshSnippets( budget = 16 * 1024 * 1024, processed = 0; try { - const sources = await sourceDescriptors(); + const snapshot = await sourceSnapshot(); selected.guard(); + const sources = snapshot.sources; + const activeSources = new Set(sources.map(sourceKey)); + const known = await summaries(selected.owner); + selected.guard(); + const authoritativeAbsentSources = new Set(); + for (const record of known) { + // Summaries omit the immutable upload journal, including persisted older summaries. + // Read pending saves from the durable record before classifying their source. + const pending = record.dirty ? await getRecord(selected.owner, record.id) : undefined; + selected.guard(); + const candidates = [ + ...record.locations.map((location) => location.source), + ...(record.destination ? [record.destination.source] : []), + ...(pending?.upload ? [pending.upload.destination.source] : []) + ]; + for (const candidate of candidates) { + const key = sourceKey(candidate); + if ( + !activeSources.has(key) && + (candidate.owner === null || snapshot.cloudAuthoritative) + ) + authoritativeAbsentSources.add(key); + } + } const db = await integrationDB(); for (let sourceIndex = 0; sourceIndex < sources.length; sourceIndex++) { const source = sources[sourceIndex]; @@ -279,7 +304,9 @@ export async function refreshSnippets( selected.owner, remote.document, remote.location, - selected.guard + selected.guard, + activeSources, + authoritativeAbsentSources ); } catch (error) { selected.guard(); @@ -369,7 +396,15 @@ export async function appendToSnippet( ); return { ...current, document, dirty: !!current.destination, issue: undefined }; }); - await reloadSnippets(selected); + + // The IndexedDB mutation above is authoritative and records the capture + // receipt atomically. A presentation refresh failure after that point must + // not report the append as failed and invite a duplicate retry. + try { + await reloadSnippets(selected); + } catch { + /* The committed mutation already broadcast its change. A later refresh can republish summaries. */ + } } export async function duplicateSnippet(id: string, selected = scope()) { const record = await getRecord(selected.owner, id); diff --git a/apps/web/src/lib/snippets/storage.ts b/apps/web/src/lib/snippets/storage.ts index cbf4069d7e..10e6fd9508 100644 --- a/apps/web/src/lib/snippets/storage.ts +++ b/apps/web/src/lib/snippets/storage.ts @@ -5,10 +5,10 @@ */ import { currentUser, IntegrationError, request } from '../manabi/client'; -import { integrationDB, exclusive } from '../manabi/persistence'; +import { integrationDB, exclusive, type LocalLibrary } from '../manabi/persistence'; import { librarySource, type SourceDescriptor } from '../library/catalog'; import { openDirectory, safePath } from '../library/file-operations'; -import { sha256, type LibraryEntry } from '../manabi/sources'; +import { sha256, withLocalLibraryConnection, type LibraryEntry } from '../manabi/sources'; import { davSource, withDavSourceLock } from '../webdav/source'; import { davChild, davRoot, strongEtag, decodeDavText } from '../webdav/client'; import type { Destination, Guard, Location } from './database'; @@ -85,21 +85,29 @@ function reply(value: DocumentReply, source: SourceDescriptor, expected?: string const document = parseSnippet(canonical(value.document)); return { document, location: { ...value.location, source } as Location }; } -async function local(source: SourceDescriptor, guard: Guard, write = false) { +async function localSnapshot(source: SourceDescriptor, guard: Guard) { sourceGuard(source, guard); if (source.provider !== 'local' || source.owner !== null || source.root !== '') throw new Error('Invalid local folder source.'); const item = await (await integrationDB()).get('localLibraries', source.id); guard(); if (!item) throw new Error('This folder is no longer connected.'); - if ( - (write && !item.writable) || - (await item.handle.queryPermission({ mode: write ? 'readwrite' : 'read' })) !== 'granted' - ) - throw new IntegrationError('permission_required'); - guard(); return item; } +async function withLocal( + source: SourceDescriptor, + guard: Guard, + write: boolean, + work: (library: LocalLibrary) => Promise +): Promise { + const admitted = await localSnapshot(source, guard); + return withLocalLibraryConnection(admitted, write, async (current) => { + guard(); + const result = await work(current); + guard(); + return result; + }); +} function childName(name: string, folder = false) { // Keep all providers within one portable filename contract. @@ -132,9 +140,13 @@ async function optionalFile(directory: FileSystemDirectoryHandle, name: string) throw error; } } -async function localRead(source: SourceDescriptor, fileId: string, guard: Guard) { - const origin = await local(source, guard), - { parent, name } = parts(fileId); +async function localReadConnected( + source: SourceDescriptor, + origin: LocalLibrary, + fileId: string, + guard: Guard +) { + const { parent, name } = parts(fileId); const handle = await (await openDirectory(origin.handle, parent)).getFileHandle(name), file = await handle.getFile(); guard(); @@ -146,6 +158,11 @@ async function localRead(source: SourceDescriptor, fileId: string, guard: Guard) guard(); return { document, location: { source, fileId, parent, name, token } as Location }; } +async function localRead(source: SourceDescriptor, fileId: string, guard: Guard) { + return withLocal(source, guard, false, (origin) => + localReadConnected(source, origin, fileId, guard) + ); +} async function davRead(source: SourceDescriptor, fileId: string, guard: Guard) { const adapter = await davSource(source.id); guard(); @@ -191,11 +208,10 @@ export async function capability( : 'Enable write-back in WebDAV connection settings to save snippet documents here.' }; } - const entry = await local(source, guard); - return { + return withLocal(source, guard, false, async (entry) => ({ write: entry.writable && (await entry.handle.queryPermission({ mode: 'readwrite' })) === 'granted' - }; + })); } export async function folders(source: SourceDescriptor, parent: string, guard: Guard) { sourceGuard(source, guard); @@ -272,12 +288,13 @@ export async function makeFolder( guard(); return id; }); - const entry = await local(source, guard, true), - directory = await openDirectory(entry.handle, parent); - guard(); - await directory.getDirectoryHandle(name, { create: true }); - guard(); - return join(parent, name); + return withLocal(source, guard, true, async (entry) => { + const directory = await openDirectory(entry.handle, parent); + guard(); + await directory.getDirectoryHandle(name, { create: true }); + guard(); + return join(parent, name); + }); } export async function readDocument( source: SourceDescriptor, @@ -370,54 +387,57 @@ export async function writeDocument( throw new IntegrationError('conflict'); return confirmed.location; }); - return exclusive(`snippet-file:${source.id}:${join(parent, name)}`, async () => { - const entry = await local(source, guard, true), - directory = await openDirectory(entry.handle, parent); - let handle = await optionalFile(directory, name); - guard(); - let before: Awaited> | undefined; - const id = join(parent, name); - if (handle) { - const existing = await handle.getFile(); + return withLocal(source, guard, true, (entry) => + exclusive(`snippet-file:${source.id}:${join(parent, name)}`, async () => { + const directory = await openDirectory(entry.handle, parent); + let handle = await optionalFile(directory, name); guard(); - // File System Access creates the directory entry before a writable stream - // is committed. A crash/abort during a first create can therefore leave a - // zero-byte placeholder. Only reclaim the deterministic filename for this - // exact logical document; corrupt/non-empty external files remain conflicts. - const recoverablePlaceholder = - !expected && existing.size === 0 && name === filename(document); - if (!recoverablePlaceholder) { - before = await localRead(source, id, guard); - if (!permitUpdate(before.document, document, expected, before.location)) - return before.location; - } - } else if (expected) throw new IntegrationError('not_found', 404); - handle ??= await directory.getFileHandle(name, { create: true }); - guard(); - const stream = await handle.createWritable(); - try { - await stream.write(raw); + let before: Awaited> | undefined; + const id = join(parent, name); + if (handle) { + const existing = await handle.getFile(); + guard(); + // File System Access creates the directory entry before a writable stream + // is committed. A crash/abort during a first create can therefore leave a + // zero-byte placeholder. Only reclaim the deterministic filename for this + // exact logical document; corrupt/non-empty external files remain conflicts. + const recoverablePlaceholder = + !expected && existing.size === 0 && name === filename(document); + if (!recoverablePlaceholder) { + before = await localReadConnected(source, entry, id, guard); + if (!permitUpdate(before.document, document, expected, before.location)) + return before.location; + } + } else if (expected) throw new IntegrationError('not_found', 404); + handle ??= await directory.getFileHandle(name, { create: true }); guard(); - // A browser cannot exclude external editors. Recheck immediately before committing. - const latest = await handle.getFile(); - guard(); - if ( - before - ? (await sha256(await latest.arrayBuffer())) !== before.location.token - : latest.size !== 0 - ) + const stream = await handle.createWritable(); + try { + await stream.write(raw); + guard(); + // A browser cannot exclude external editors. Recheck immediately before committing. + const latest = await handle.getFile(); + guard(); + if ( + before + ? (await sha256(await latest.arrayBuffer())) !== before.location.token + : latest.size !== 0 + ) + throw new IntegrationError('conflict'); + if ((await entry.handle.queryPermission({ mode: 'readwrite' })) !== 'granted') + throw new IntegrationError('permission_required'); + guard(); + await stream.close(); + } catch (error) { + await stream.abort().catch(() => undefined); + throw error; + } + const confirmed = await localReadConnected(source, entry, id, guard); + if (canonical(confirmed.document) !== canonical(document)) throw new IntegrationError('conflict'); - await local(source, guard, true); - await stream.close(); - } catch (error) { - await stream.abort().catch(() => undefined); - throw error; - } - const confirmed = await localRead(source, id, guard); - if (canonical(confirmed.document) !== canonical(document)) - throw new IntegrationError('conflict'); - return confirmed.location; - }); + return confirmed.location; + }) + ); } /** Only cloud providers expose a qualified native move here; other sources use the transfer journal. */ export async function moveWithinSource( @@ -459,26 +479,30 @@ export async function removeDocument(location: Location, document: SnippetDocume if (value.removed !== true) throw new IntegrationError('invalid_response'); return; } - const remove = async () => { - const current = await readDocument(source, fileId, guard); - if (current.location.token !== token || canonical(current.document) !== canonical(document)) - throw new IntegrationError('conflict'); - if (source.provider === 'webdav') { + if (source.provider === 'webdav') + return withDavSourceLock(source.id, async () => { + const current = await readDocument(source, fileId, guard); + if (current.location.token !== token || canonical(current.document) !== canonical(document)) + throw new IntegrationError('conflict'); const adapter = await davSource(source.id); guard(); await (await adapter.documentClient(true)).remove(fileId, token); guard(); - } else { - const entry = await local(source, guard, true), - { parent, name } = parts(fileId), + }); + return withLocal(source, guard, true, (entry) => + exclusive(`snippet-file:${source.id}:${fileId}`, async () => { + const current = await localReadConnected(source, entry, fileId, guard); + if (current.location.token !== token || canonical(current.document) !== canonical(document)) + throw new IntegrationError('conflict'); + const { parent, name } = parts(fileId), directory = await openDirectory(entry.handle, parent); - const again = await localRead(source, fileId, guard); + const again = await localReadConnected(source, entry, fileId, guard); if (again.location.token !== token) throw new IntegrationError('conflict'); + if ((await entry.handle.queryPermission({ mode: 'readwrite' })) !== 'granted') + throw new IntegrationError('permission_required'); + guard(); await directory.removeEntry(name); guard(); - } - }; - return source.provider === 'webdav' - ? withDavSourceLock(source.id, remove) - : exclusive(`snippet-file:${source.id}:${fileId}`, remove); + }) + ); } diff --git a/apps/web/src/lib/snippets/workspace.svelte b/apps/web/src/lib/snippets/workspace.svelte index 872477bb6f..bd07f8284f 100644 --- a/apps/web/src/lib/snippets/workspace.svelte +++ b/apps/web/src/lib/snippets/workspace.svelte @@ -1,5 +1,5 @@ \n\n' + + '[unsafe](javascript:alert(1))\n\n' + + '\n\n' + + '**safe text remains**' + ) + }); + const hostileEditor = page.getByRole('textbox', { name: 'Snippet text', exact: true }); + await expect(hostileEditor).toContainText('safe text remains'); + await expect(hostileEditor.locator('script, iframe, [href^="javascript:"]')).toHaveCount(0); + assert.equal( + await page.evaluate(() => window.__snippetMarkdownExecuted), + undefined, + 'Markdown raw HTML must be sanitized before it can execute' + ); + await page.getByRole('button', { name: 'Cancel', exact: true }).click(); + markdownLeave = page.getByRole('dialog', { name: 'Keep this draft?' }); + await expect(markdownLeave).toBeVisible(); + await markdownLeave.getByRole('button', { name: 'Discard draft and leave', exact: true }).click(); + passed('Markdown import retains the shared HTML sanitization boundary'); + await local.ctx.close(); const cloud = await context('alice'); diff --git a/test/snippets/run.mjs b/test/snippets/run.mjs index 750ab917b9..61ebc329b1 100644 --- a/test/snippets/run.mjs +++ b/test/snippets/run.mjs @@ -21,10 +21,11 @@ let generation=0; export const changeUser=(id)=>{generation++;account.set({status:'available',session:id?{user:{id,username:id}}:null});}; export const accountScope=()=>({userId:currentUser()?.id,generation}); export class IntegrationError extends Error {constructor(code,status=0){super(code);this.code=code;this.status=status;}} -export const memory={files:new Map(),writes:[],states:new Map(),sources:[],dropReply:false,beforeWrite:null,beforeStateWrite:null,failRemove:false,readCount:0,scanCount:0,beforeScan:null}; +export const memory={files:new Map(),writes:[],states:new Map(),sources:[],cloudAuthoritative:true,dropReply:false,beforeWrite:null,beforeStateWrite:null,failRemove:false,readCount:0,scanCount:0,beforeScan:null}; export function sameSource(a,b){return a.id===b.id&&a.owner===b.owner&&a.root===b.root;} export const capability=async()=>({write:true}); export const sourceDescriptors=async()=>memory.sources; +export const sourceSnapshot=async()=>({sources:memory.sources,cloudAuthoritative:memory.cloudAuthoritative}); export const scanCatalog=async(_adapter,source,signal)=>{memory.scanCount++;const entries=[...memory.files].filter(([,x])=>sameSource(x.location.source,source)).map(([id,x])=>({id,name:x.location.name,kind:'file'}));if(memory.beforeScan)await memory.beforeScan();signal?.throwIfAborted();return {source,entries,names:{},warnings:[],scannedAt:Date.now()};}; export const librarySource=async(source)=>({source,state:async(key)=>memory.states.get(source.id+key)??{value:null,revision:'0'},write:async(key,value,revision)=>{if(memory.beforeStateWrite)await memory.beforeStateWrite(source,key,value);const name=source.id+key,current=memory.states.get(name)??{revision:'0'};if(current.revision!==revision)throw new IntegrationError('conflict');const result={value:structuredClone(value),revision:String(Number(revision)+1)};memory.states.set(name,result);return result;}}); export const prepareDestination=async(dest,doc)=>({...dest,name:doc.id+'.manabi-snippet.json',createId:dest.createId??crypto.randomUUID()}); diff --git a/test/snippets/unit.test.mjs b/test/snippets/unit.test.mjs index f3b881539c..6b1ae10ab9 100644 --- a/test/snippets/unit.test.mjs +++ b/test/snippets/unit.test.mjs @@ -22,11 +22,13 @@ import { MAX_SNIPPET_BYTES, MAX_SNIPPET_SEARCH_CODEPOINTS, snippetSearchTooLong, + truncateValidText, validateContent } from '../../apps/web/src/lib/snippets/document.ts'; import { saveDocument, getRecord, + mutateRecord, saveDraft, drafts, deleteDraft, @@ -40,6 +42,7 @@ import { transfers } from '../../apps/web/src/lib/snippets/database.ts'; import { integrationDB, setMetadata } from '../../apps/web/src/lib/manabi/persistence.ts'; +import { sourceKey } from '../../apps/web/src/lib/library/organization-keys.ts'; import { readerHTML, parseLocator, @@ -113,6 +116,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), '東京へ行く。'); @@ -438,6 +456,364 @@ test('causal descendant preserves portable trash state instead of resurrecting s assert.equal(record.conflicts.length, 0); }); +test('reconnected source with identical bytes replaces an unavailable old primary', async () => { + const who = owner(), + doc = document('same bytes'), + oldSource = source('old-source'), + newSource = source('new-source'), + oldLocation = { + source: oldSource, + parent: '', + name: 'same.manabi-snippet.json', + fileId: 'same-old', + token: 'old-token' + }, + newLocation = { + source: newSource, + parent: '', + name: 'same.manabi-snippet.json', + fileId: 'same-new', + token: 'new-token' + }; + await acceptRemote(who, doc, oldLocation, guard); + await acceptRemote( + who, + doc, + newLocation, + guard, + new Set([sourceKey(newSource)]), + new Set([sourceKey(oldSource)]) + ); + const current = await getRecord(who, doc.id); + assert.equal(current.primary, locationKey(newLocation)); + assert.equal(current.destination.source.id, newSource.id); + assert.equal(current.remoteRevision, doc.revision); + assert.equal(current.dirty, false); + assert.equal(current.conflicts.length, 0); + assert.equal(current.locations.length, 2); +}); + +test('exact replacement copy clears stale dirty state without an upload journal', async () => { + const who = owner(), + doc = document('already durable elsewhere'), + oldSource = source('old-source'), + newSource = source('new-source'), + oldLocation = { + source: oldSource, + parent: '', + name: 'same.manabi-snippet.json', + fileId: 'same-old', + token: 'old-token' + }, + newLocation = { + source: newSource, + parent: '', + name: 'same.manabi-snippet.json', + fileId: 'same-new', + token: 'new-token' + }; + await acceptRemote(who, doc, oldLocation, guard); + await mutateRecord(who, doc.id, guard, (current) => ({ + ...current, + dirty: true, + upload: undefined + })); + await acceptRemote( + who, + doc, + newLocation, + guard, + new Set([sourceKey(newSource)]), + new Set([sourceKey(oldSource)]) + ); + const current = await getRecord(who, doc.id); + assert.equal(current.primary, locationKey(newLocation)); + assert.equal(current.destination.source.id, newSource.id); + assert.equal(current.remoteRevision, doc.revision); + assert.equal(current.dirty, false); + assert.equal(current.upload, undefined); + assert.equal(current.conflicts.length, 0); +}); + +test('reconnected source republishes a clean newer descendant over its remote ancestor', async () => { + const who = owner(), + original = document('provider ancestor'), + newer = editSnippet(original, plainContent('newer cached descendant'), ''), + oldSource = source('old-source'), + newSource = source('new-source'), + oldLocation = { + source: oldSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'old-file', + token: 'old-token' + }, + newLocation = { + source: newSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'new-file', + token: 'new-token' + }; + await acceptRemote(who, newer, oldLocation, guard); + await acceptRemote( + who, + original, + newLocation, + guard, + new Set([sourceKey(newSource)]), + new Set([sourceKey(oldSource)]) + ); + const current = await getRecord(who, original.id); + assert.equal(current.document.revision, newer.revision); + assert.equal(passages(current.document.content)[0].text, 'newer cached descendant'); + assert.equal(current.primary, locationKey(newLocation)); + assert.equal(current.destination.source.id, newSource.id); + assert.equal(current.remoteRevision, original.revision); + assert.equal(current.dirty, true); + assert.equal(current.conflicts.length, 0); +}); + +test('reconnected source binds a remote ancestor under newer dirty local edits', async () => { + const who = owner(), + original = document('provider copy'), + edited = editSnippet(original, plainContent('newer local edit'), ''), + oldSource = source('old-source'), + newSource = source('new-source'), + oldLocation = { + source: oldSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'old-file', + token: 'old-token' + }, + newLocation = { + source: newSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'new-file', + token: 'new-token' + }; + await acceptRemote(who, original, oldLocation, guard); + await mutateRecord(who, original.id, guard, (current) => ({ + ...current, + document: edited, + dirty: true, + upload: { + document: structuredClone(edited), + destination: oldLocation, + expected: oldLocation + } + })); + await acceptRemote( + who, + original, + newLocation, + guard, + new Set([sourceKey(newSource)]), + new Set([sourceKey(oldSource)]) + ); + const current = await getRecord(who, original.id); + assert.equal(current.document.revision, edited.revision); + assert.equal(passages(current.document.content)[0].text, 'newer local edit'); + assert.equal(current.primary, locationKey(newLocation)); + assert.equal(current.destination.source.id, newSource.id); + assert.equal(current.remoteRevision, original.revision); + assert.equal(current.dirty, true); + assert.equal(current.upload, undefined); + assert.equal(current.conflicts.length, 0); +}); + +test('reconnection never promotes a sibling over dirty local edits', async () => { + const who = owner(), + base = document('base'), + local = editSnippet(base, plainContent('local branch'), ''), + remote = editSnippet(base, plainContent('remote branch'), ''), + oldSource = source('old-source'), + newSource = source('new-source'), + oldLocation = { + source: oldSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'old-file', + token: 'old-token' + }, + newLocation = { + source: newSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'new-file', + token: 'new-token' + }; + await acceptRemote(who, base, oldLocation, guard); + await mutateRecord(who, base.id, guard, (current) => ({ + ...current, + document: local, + dirty: true + })); + await acceptRemote( + who, + remote, + newLocation, + guard, + new Set([sourceKey(newSource)]), + new Set([sourceKey(oldSource)]) + ); + const current = await getRecord(who, base.id); + assert.equal(current.document.revision, local.revision); + assert.equal(current.primary, locationKey(oldLocation)); + assert.equal(current.conflicts.length, 1); + assert.equal(current.conflicts[0].revision, remote.revision); +}); + +test('offline cached cloud absence cannot rebind a storage home', async () => { + changeUser('alice'); + const selected = scope(), + doc = document('cloud cached copy'), + oldSource = { + id: crypto.randomUUID(), + owner: 'alice', + provider: 'dropbox', + root: 'old-root', + name: 'Old Dropbox' + }, + newSource = { + id: crypto.randomUUID(), + owner: 'alice', + provider: 'dropbox', + root: 'new-root', + name: 'New Dropbox' + }, + oldLocation = { + source: oldSource, + parent: 'old-root', + name: doc.id + '.manabi-snippet.json', + fileId: 'old-file', + token: 'old-token' + }, + newLocation = { + source: newSource, + parent: 'new-root', + name: doc.id + '.manabi-snippet.json', + fileId: 'new-file', + token: 'new-token' + }, + previousSources = memory.sources, + previousAuthority = memory.cloudAuthoritative; + try { + await acceptRemote(selected.owner, doc, oldLocation, selected.guard); + memory.sources = [newSource]; + memory.files.set(doc.id, { document: doc, location: newLocation }); + + memory.cloudAuthoritative = false; + await refreshSnippets(selected, true); + let current = await getRecord(selected.owner, doc.id); + assert.equal(current.primary, locationKey(oldLocation)); + assert.equal(current.locations.length, 2); + + memory.cloudAuthoritative = true; + await refreshSnippets(selected, true); + current = await getRecord(selected.owner, doc.id); + assert.equal(current.primary, locationKey(newLocation)); + assert.equal(current.destination.source.id, newSource.id); + assert.equal(current.conflicts.length, 0); + } finally { + memory.files.delete(doc.id); + memory.sources = previousSources; + memory.cloudAuthoritative = previousAuthority; + changeUser(null); + } +}); + +test('discovery retires an exact stale upload whose own source disappeared', async () => { + const selected = { owner: owner(), guard }, + doc = document('stale upload source'), + activeSource = source('active-home'), + deadUploadSource = source('dead-upload-home'), + activeLocation = { + source: activeSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'active-file', + token: 'active-token' + }, + deadUploadLocation = { + source: deadUploadSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'dead-file', + token: 'dead-token' + }, + previousSources = memory.sources; + await acceptRemote(selected.owner, doc, activeLocation, guard); + await mutateRecord(selected.owner, doc.id, guard, (current) => ({ + ...current, + dirty: true, + upload: { + document: structuredClone(doc), + destination: deadUploadLocation, + expected: deadUploadLocation + } + })); + memory.sources = [activeSource]; + memory.files.set(doc.id, { document: doc, location: activeLocation }); + try { + await refreshSnippets(selected, true); + const current = await getRecord(selected.owner, doc.id); + assert.equal(current.primary, locationKey(activeLocation)); + assert.equal(current.destination.source.id, activeSource.id); + assert.equal(current.upload, undefined); + assert.equal(current.dirty, false); + assert.equal(current.conflicts.length, 0); + } finally { + memory.files.delete(doc.id); + memory.sources = previousSources; + } +}); + +test('an active upload to a still-present source cannot be stolen by discovery', async () => { + const who = owner(), + doc = document('upload owner'), + primarySource = source('primary-source'), + otherSource = source('other-source'), + primary = { + source: primarySource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'primary', + token: '1' + }, + other = { + source: otherSource, + parent: '', + name: 'doc.manabi-snippet.json', + fileId: 'other', + token: '2' + }; + await acceptRemote(who, doc, primary, guard); + await mutateRecord(who, doc.id, guard, (current) => ({ + ...current, + dirty: true, + upload: { + document: structuredClone(current.document), + destination: primary, + expected: primary + } + })); + await acceptRemote( + who, + doc, + other, + guard, + new Set([sourceKey(primarySource), sourceKey(otherSource)]), + new Set() + ); + const current = await getRecord(who, doc.id); + assert.equal(current.primary, locationKey(primary)); + assert.equal(current.upload.destination.source.id, primarySource.id); + assert.equal(current.locations.length, 2); +}); + test('divergent remote edits are retained rather than last-write-wins', async () => { const who = owner(), doc = document(), @@ -1156,6 +1532,57 @@ test('restoring the same durable locator does not manufacture a newer position u assert.deepEqual(after.progress, locator); }); +test('discovery rebinds dirty local edits when the same document returns under a new source ID', async () => { + const selected = { owner: owner(), guard }, + original = document('remote ancestor'), + edited = editSnippet(original, plainContent('offline local descendant'), ''), + oldSource = source('disconnected-source'), + newSource = source('reconnected-source'), + oldLocation = { + source: oldSource, + fileId: 'same-file-old', + name: original.id + '.manabi-snippet.json', + parent: '', + token: 'old-token' + }, + newLocation = { + source: newSource, + fileId: 'same-file-new', + name: original.id + '.manabi-snippet.json', + parent: '', + token: 'new-token' + }, + previousSources = memory.sources; + await acceptRemote(selected.owner, original, oldLocation, guard); + await mutateRecord(selected.owner, original.id, guard, (current) => ({ + ...current, + document: edited, + dirty: true, + upload: { + document: structuredClone(edited), + destination: oldLocation, + expected: oldLocation + } + })); + memory.sources = [newSource]; + memory.files.set(original.id, { document: original, location: newLocation }); + try { + await refreshSnippets(selected, true); + const after = await getRecord(selected.owner, original.id); + assert.equal(after.primary, locationKey(newLocation)); + assert.equal(after.destination.source.id, newSource.id); + assert.equal(after.document.revision, edited.revision); + assert.equal(passages(after.document.content)[0].text, 'offline local descendant'); + assert.equal(after.remoteRevision, original.revision); + assert.equal(after.dirty, true); + assert.equal(after.upload, undefined); + assert.equal(after.conflicts.length, 0); + } finally { + memory.files.delete(original.id); + memory.sources = previousSources; + } +}); + test('a stale listing snapshot cannot mark a location created during that scan as missing', async () => { const selected = { owner: owner(), guard }, src = source(), diff --git a/tests/browser/test_control_refinement.py b/tests/browser/test_control_refinement.py index dc72b0a496..11d3048dee 100644 --- a/tests/browser/test_control_refinement.py +++ b/tests/browser/test_control_refinement.py @@ -222,7 +222,19 @@ def test_notes_panel_keeps_sticky_dismissal_reachable_at_200_percent_text(self): trigger.focus() trigger.press('Enter') panel = self.page.get_by_role('dialog').last - expect(panel.get_by_role('heading', name='Bookmarks & Notes', exact=True)).to_be_visible() + heading = panel.get_by_role('heading', name='Bookmarks & Notes', exact=True) + expect(heading).to_be_visible() + heading_box = heading.bounding_box() + self.assertGreaterEqual(heading_box['width'], 240) + self.assertEqual('normal', heading.evaluate('e => getComputedStyle(e).overflowWrap')) + self.assertEqual('normal', heading.evaluate('e => getComputedStyle(e).wordBreak')) + words = heading.locator('[data-annotations-title-word]') + expect(words).to_have_count(2) + for word in words.all(): + box = word.bounding_box() + line_height = word.evaluate('e => parseFloat(getComputedStyle(e).lineHeight)') + self.assertLessEqual(box['width'], heading_box['width'] + 1) + self.assertLessEqual(box['height'], line_height * 1.15) add = panel.get_by_role('button', name='Add Bookmark', exact=True) self.assertGreaterEqual(add.bounding_box()['height'], 43.99) add.click() diff --git a/tests/browser/test_epub_publication.py b/tests/browser/test_epub_publication.py index 9260780069..8aa9dbc51c 100644 --- a/tests/browser/test_epub_publication.py +++ b/tests/browser/test_epub_publication.py @@ -60,6 +60,64 @@ 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() + filler = ''.join( + f'

前の文章を読みます。まだ目的の位置ではありません。

' + for index in range(260) + ) + chapter = ( + 'Second' + '' + '

第二章の先頭

' + filler + + '

深いリンク先

' + '戻る' + ) + with zipfile.ZipFile(io.BytesIO(resource_epub())) as source, zipfile.ZipFile( + output, 'w', zipfile.ZIP_DEFLATED + ) as target: + for entry in source.infolist(): + data = source.read(entry) + if entry.filename == 'EPUB/two.xhtml': + data = chapter.encode() + target.writestr(entry, data) + return output.getvalue() + + def rtl_language_epub(): output = io.BytesIO() with zipfile.ZipFile(io.BytesIO(resource_epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: @@ -71,6 +129,22 @@ def rtl_language_epub(): return output.getvalue() +def rtl_long_epub(): + output = io.BytesIO() + filler = ''.join( + f'

右から左へページを読み進めます。段落 {index}。

' for index in range(180) + ).encode() + with zipfile.ZipFile(io.BytesIO(rtl_language_epub())) as source, zipfile.ZipFile( + output, 'w', zipfile.ZIP_DEFLATED + ) as target: + for entry in source.infolist(): + data = source.read(entry) + if entry.filename == 'EPUB/one.xhtml': + data = data.replace(b'', filler + b'') + target.writestr(entry, data) + return output.getvalue() + + def resource_semantics_epub(): output = io.BytesIO() with zipfile.ZipFile(io.BytesIO(resource_epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: @@ -84,6 +158,50 @@ def resource_semantics_epub(): return output.getvalue() +def ltr_pages_rtl_content_epub(): + output = io.BytesIO() + with zipfile.ZipFile(io.BytesIO(resource_semantics_epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: + for entry in source.infolist(): + data = source.read(entry) + if entry.filename == 'EPUB/book.opf': + data = data.replace(b'', b'') + target.writestr(entry, data) + return output.getvalue() + + +def malformed_root_semantics_epub(): + output = io.BytesIO() + with zipfile.ZipFile(io.BytesIO(resource_epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: + for entry in source.infolist(): + data = source.read(entry) + if entry.filename == 'EPUB/book.opf': + data = data.replace(b'ja', b'en') + elif entry.filename == 'EPUB/one.xhtml': + data = data.replace( + b'', + b'' + ) + data = data.replace( + b'', + b'' + ) + target.writestr(entry, data) + return output.getvalue() + + +def css_direction_epub(): + output = io.BytesIO() + with zipfile.ZipFile(io.BytesIO(resource_epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: + for entry in source.infolist(): + data = source.read(entry) + if entry.filename == 'EPUB/book.opf': + data = data.replace(b'', b'') + elif entry.filename == 'EPUB/one.css': + data = b'body{direction:rtl;unicode-bidi:isolate}' + data + target.writestr(entry, data) + return output.getvalue() + + def linear_epub(): output = io.BytesIO() with zipfile.ZipFile(io.BytesIO(resource_epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: @@ -144,9 +262,10 @@ def setUpClass(cls): cls.playwright = sync_playwright().start() cls.browser = getattr(cls.playwright, os.environ.get('SLIDE_BROWSER', 'chromium')).launch(**launch_options((getattr(cls.playwright, os.environ.get('SLIDE_BROWSER', 'chromium'))).name)) - def open_resource_book(self, view='paginated', malformed=False, payload=None): + def open_resource_book(self, view='paginated', malformed=False, payload=None, foliate=True, ready_selector='#same'): settings = { - 'manabi-dev-foliate-epub': 'true', 'viewMode': view, 'writingMode': 'horizontal-tb', + 'manabi-dev-foliate-epub': 'true' if foliate else 'false', + 'viewMode': view, 'writingMode': 'horizontal-tb', 'hideFurigana': 'false', 'hideSpoilerImage': 'false' } self.context.add_init_script('if (location.origin === ' + json.dumps(self.origin) + ') {' @@ -157,11 +276,151 @@ def open_resource_book(self, view='paginated', malformed=False, payload=None): 'name': 'resources.epub', 'mimeType': 'application/epub+zip', 'buffer': resource_epub(malformed) if payload is None else payload }) self.page.get_by_role('button', name='Read ' + TITLE, exact=True).click(timeout=30000) - if view == 'paginated': - self.page.wait_for_function(f"() => {P}?.getContents?.()[0]?.doc?.querySelector('#same')") + if view == 'paginated' and foliate: + self.page.wait_for_function(f"() => {P}?.getContents?.()[0]?.doc?.querySelector({json.dumps(ready_selector)})") + elif view == 'paginated': + expect(self.page.locator('.book-content-container').locator(ready_selector)).to_be_visible(timeout=30000) + expect(self.page.locator('.book-content')).to_have_attribute('aria-busy', 'false', timeout=30000) 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(), ready_selector='#to-image') + 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 + && document.querySelector('.book-content')?.getAttribute('aria-busy') === 'false'""") + 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 + && document.querySelector('.book-content')?.getAttribute('aria-busy') === 'false'""") + 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 { + const section=document.querySelector('.book-content-container'); + const host=document.querySelector('.book-content'); + const target=section?.querySelector('#same'); + const start=section?.querySelector('#chapter-start'); + if (section?.dataset.manabiSpineIndex !== '1' || + host?.getAttribute('aria-busy') !== 'false' || !target || !start) return false; + const h=host.getBoundingClientRect(), t=target.getBoundingClientRect(), + first=start.getBoundingClientRect(); + const intersects=r=>r.right>h.left && r.lefth.top && r.top { + const host=document.querySelector('.book-content'); + const target=document.querySelector('.book-content-container #same'); + const start=document.querySelector('.book-content-container #chapter-start'); + const intersects=(element) => { + const r=element.getBoundingClientRect(), h=host.getBoundingClientRect(); + return r.right > h.left && r.left < h.right && r.bottom > h.top && r.top < h.bottom; + }; + return { + target:intersects(target), + start:intersects(start), + scrollLeft:host.scrollLeft, + transform:getComputedStyle(document.querySelector('.book-content-container')).transform + }; + }""") + self.assertTrue(visible['target'], visible) + self.assertFalse(visible['start'], visible) + self.assertTrue(visible['scrollLeft'] > 0 or visible['transform'] != 'none', visible) + self.assertEqual([], StaticHandler.probes) + self.assertEqual([], self.errors) + + def test_legacy_paginated_horizontal_rtl_uses_imported_page_progression(self): + self.page.set_viewport_size({'width': 390, 'height': 844}) + self.open_resource_book(payload=rtl_long_epub(), foliate=False) + host = self.page.locator('.book-content') + container = self.page.locator('.book-content-container') + self.assertEqual('0', container.get_attribute('data-manabi-spine-index')) + before = self.page.evaluate("""() => ({ + left: document.querySelector('.book-content').scrollLeft, + transform: getComputedStyle(document.querySelector('.book-content-container')).transform + })""") + + # In a horizontal RTL publication, the physical-left key advances the + # logical reading order. The LTR fallback used to treat this as "previous" + # and remain at the first page. + self.page.keyboard.press('ArrowLeft') + self.page.wait_for_function("""before => { + const host=document.querySelector('.book-content'); + const transform=getComputedStyle(document.querySelector('.book-content-container')).transform; + return host.scrollLeft !== before.left || transform !== before.transform; + }""", arg=before) + advanced = self.page.evaluate("""() => ({ + left: document.querySelector('.book-content').scrollLeft, + transform: getComputedStyle(document.querySelector('.book-content-container')).transform + })""") + self.assertNotEqual(before, advanced) + + self.page.keyboard.press('ArrowRight') + self.page.wait_for_function("""before => { + const host=document.querySelector('.book-content'); + const transform=getComputedStyle(document.querySelector('.book-content-container')).transform; + return host.scrollLeft === before.left && transform === before.transform; + }""", arg=before) + self.assertEqual(before, self.page.evaluate("""() => ({ + left: document.querySelector('.book-content').scrollLeft, + transform: getComputedStyle(document.querySelector('.book-content-container')).transform + })""")) + self.assertEqual([], StaticHandler.probes) + self.assertEqual([], self.errors) + def test_framed_reader_receives_imported_language_and_page_direction(self): self.open_resource_book(payload=rtl_language_epub()) actual = self.page.evaluate(f"""() => {{ @@ -187,6 +446,59 @@ def test_framed_reader_receives_imported_language_and_page_direction(self): self.assertEqual(actual, again) self.assertEqual([], self.errors) + def test_rtl_missing_resource_keeps_current_document_direction_and_can_retry(self): + self.open_resource_book(payload=rtl_language_epub()) + 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, + text:p.getContents()[0].doc.body.textContent, + bookDir:p.bookDir, + turnDir:p.pageTurnDirection, + hostDir:p.getAttribute('dir') + }}; + section.load=async()=>null; + const failed=await p.goTo({{index:1}}); + const afterFailure={{ + index:p.getContents()[0].index, + text:p.getContents()[0].doc.body.textContent, + bookDir:p.bookDir, + turnDir:p.pageTurnDirection, + hostDir:p.getAttribute('dir') + }}; + section.load=load; + const retry=await p.goTo({{index:1}}); + const afterRetry={{ + index:p.getContents()[0].index, + text:p.getContents()[0].doc.body.textContent, + bookDir:p.bookDir, + turnDir:p.pageTurnDirection, + hostDir:p.getAttribute('dir') + }}; + return {{failed,retry,errors,before,afterFailure,afterRetry}}; + }}""") + self.assertFalse(result['failed']) + self.assertTrue(result['retry']) + self.assertEqual(1, result['errors']) + self.assertEqual(result['before'], result['afterFailure']) + self.assertEqual('rtl', result['afterRetry']['bookDir']) + self.assertEqual('rtl', result['afterRetry']['turnDir']) + self.assertEqual('rtl', result['afterRetry']['hostDir']) + self.assertEqual(1, result['afterRetry']['index']) + self.assertIn('別の章', result['afterRetry']['text']) + self.assertEqual([], self.errors) + + def test_resource_without_language_inherits_package_language(self): + self.open_resource_book() + self.assertTrue(self.page.evaluate(f"async()=>await {P}.goTo({{index:1}})")) + self.page.wait_for_function(f"() => {P}.getContents()[0]?.index === 1") + self.assertEqual( + 'ja', + self.page.evaluate(f"{P}.getContents()[0].doc.documentElement.lang") + ) + self.assertEqual([], self.errors) + def test_resource_language_and_text_direction_override_package_fallbacks(self): self.open_resource_book(payload=resource_semantics_epub()) actual = self.page.evaluate(f"""() => {{ @@ -197,6 +509,48 @@ def test_resource_language_and_text_direction_override_package_fallbacks(self): self.assertEqual({'lang':'ja','rootDir':'rtl','bodyDir':'rtl'}, actual) self.assertEqual([], self.errors) + def test_ltr_page_progression_does_not_override_rtl_chapter_text(self): + self.open_resource_book(payload=ltr_pages_rtl_content_epub()) + actual = self.page.evaluate(f"""() => {{ + const p={P}, doc=p.getContents()[0].doc, view=doc.defaultView; + return {{bookDir:p.bookDir,turnDir:p.pageTurnDirection,hostDir:p.getAttribute('dir'), + rootDir:view.getComputedStyle(doc.documentElement).direction, + bodyDir:view.getComputedStyle(doc.body).direction}}; + }}""") + self.assertEqual({ + 'bookDir':'ltr','turnDir':'ltr','hostDir':'ltr', + 'rootDir':'ltr','bodyDir':'rtl' + }, actual) + self.assertEqual([], self.errors) + + def test_invalid_body_semantics_fall_back_to_valid_authored_root_values(self): + self.open_resource_book(payload=malformed_root_semantics_epub()) + actual = self.page.evaluate(f"""() => {{ + const p={P}, doc=p.getContents()[0].doc, view=doc.defaultView; + return {{lang:doc.documentElement.lang, + rootDir:view.getComputedStyle(doc.documentElement).direction, + bodyDir:view.getComputedStyle(doc.body).direction}}; + }}""") + self.assertEqual({'lang':'ja','rootDir':'rtl','bodyDir':'rtl'}, actual) + self.assertEqual([], self.errors) + + def test_scoped_publisher_bidi_css_survives_without_changing_page_progression(self): + self.open_resource_book(payload=css_direction_epub()) + actual = self.page.evaluate(f"""() => {{ + const p={P}, doc=p.getContents()[0].doc, view=doc.defaultView; + const content=doc.querySelector('.ttu-book-body-wrapper'); + return {{bookDir:p.bookDir,turnDir:p.pageTurnDirection,hostDir:p.getAttribute('dir'), + rootDir:view.getComputedStyle(doc.documentElement).direction, + bodyDir:view.getComputedStyle(doc.body).direction, + contentDir:view.getComputedStyle(content).direction, + unicodeBidi:view.getComputedStyle(content).unicodeBidi}}; + }}""") + self.assertEqual({ + 'bookDir':'ltr','turnDir':'ltr','hostDir':'ltr', + 'rootDir':'ltr','bodyDir':'rtl','contentDir':'rtl','unicodeBidi':'isolate' + }, actual) + self.assertEqual([], self.errors) + def test_non_linear_spine_hint_is_persisted_without_changing_current_reading_order(self): self.open_resource_book(payload=linear_epub()) metadata = self.metadata() diff --git a/tests/browser/test_foliate_slide.py b/tests/browser/test_foliate_slide.py index 26fdda387e..67752640f6 100644 --- a/tests/browser/test_foliate_slide.py +++ b/tests/browser/test_foliate_slide.py @@ -144,6 +144,12 @@ def toggle_controls(self): bounds = self.page.evaluate("window.slideRoot.querySelector('#top .page-indicator').getBoundingClientRect().toJSON()") self.page.mouse.click(bounds['x'] + bounds['width']/2, bounds['y'] + bounds['height']/2) + def set_controls(self, expanded): + controls = self.page.locator('.reader-controls') + if (controls.get_attribute('aria-expanded') == 'true') != expanded: + self.toggle_controls() + expect(controls).to_have_attribute('aria-expanded', str(expanded).lower()) + def open_numbered_book(self): self.page.set_viewport_size({'width': 390, 'height': 844}) title, archive = numbered_epub() @@ -230,7 +236,9 @@ def test_global_counts_match_rendered_chapters_and_recompute_on_resize(self): def test_unknown_counts_progress_from_percent_to_current_to_total(self): self.open_numbered_book() self.page.evaluate(f"async () => await {P}.goTo({{index:2}})") - self.toggle_controls() + self.page.evaluate('document.activeElement?.blur()') + self.page.mouse.move(195, 600) + self.set_controls(False) self.page.evaluate(f"""() => {{ window.countGates={{}}; for (const index of [0,3]) {{ @@ -257,7 +265,7 @@ def test_unknown_counts_progress_from_percent_to_current_to_total(self): # every chapter is measured, the exact current page is known but the # compact indicator intentionally withholds the total until expanded. self.assertEqual(self.indicator(), str(1 + sum(counts[:2]))) - self.toggle_controls() + self.set_controls(True) self.assertEqual(self.indicator(), f'{1 + sum(counts[:2])} of {sum(counts)}') self.screenshot('page-number-total-ready') @@ -448,6 +456,68 @@ 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_page_progression_direction_restores_authored_styles_after_layout_changes(self): + self.open_numbered_book() + result = self.page.evaluate("""() => { + const p = """ + P + """, doc = p.getContents()[0].doc; + p.bookDir = 'ltr'; + p.render(); + doc.documentElement.style.setProperty('direction', 'ltr', 'important'); + doc.body.style.setProperty('direction', 'ltr'); + const styles = () => [doc.documentElement, doc.body].map(element => ({ + value: element.style.getPropertyValue('direction'), + priority: element.style.getPropertyPriority('direction') + })); + const authored = styles(); + p.bookDir = 'rtl'; + p.render(); + const separated = styles(); + p.setAttribute('flow', 'scrolled'); + p.render(); + const scrolled = styles(); + p.removeAttribute('flow'); + p.render(); + p.bookDir = 'ltr'; + p.render(); + return { authored, separated, scrolled, aligned: styles(), + sameDocument: p.getContents()[0].doc === doc }; + }""") + self.assertTrue(result['sameDocument']) + self.assertEqual(result['separated'][0], {'value': 'rtl', 'priority': 'important'}) + self.assertEqual(result['separated'][1], {'value': 'ltr', 'priority': 'important'}) + self.assertEqual(result['scrolled'], result['authored']) + self.assertEqual(result['aligned'], result['authored']) + self.assertEqual([], self.errors) + + 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 () => {{ diff --git a/tests/browser/test_library_grid_labels.py b/tests/browser/test_library_grid_labels.py index 6539f01b0d..c68abb824b 100644 --- a/tests/browser/test_library_grid_labels.py +++ b/tests/browser/test_library_grid_labels.py @@ -41,7 +41,16 @@ def assert_grid_geometry(self, title, author): title:{left:title.left,right:title.right,top:title.top,bottom:title.bottom,height:title.height}, author:{left:author.left,right:author.right,top:author.top,bottom:author.bottom}, card:{left:card.left,right:card.right}, - pageOverflow:document.documentElement.scrollWidth-innerWidth + pageOverflow:document.documentElement.scrollWidth-innerWidth, + overflowCandidates: document.documentElement.scrollWidth > innerWidth + 1 + ? [...document.querySelectorAll('body *')].map(element => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + return { tag: element.tagName, className: String(element.className).slice(0, 160), + left: rect.left, right: rect.right, overflowX: style.overflowX, + position: style.position }; + }).filter(element => element.left < -1 || element.right > innerWidth + 1).slice(0, 16) + : [] }; }''') self.assertGreaterEqual(geometry['title']['top'], geometry['cover']['bottom'] + 4, geometry) diff --git a/tests/browser/test_library_parity.py b/tests/browser/test_library_parity.py index 8a3e407eab..18f4a525eb 100644 --- a/tests/browser/test_library_parity.py +++ b/tests/browser/test_library_parity.py @@ -122,6 +122,13 @@ def test_compact_selection_toolbar_reflows_at_200_percent_text(self): self.assertGreaterEqual(box['height'], 43.99) self.assertGreaterEqual(box['x'], -1) self.assertLessEqual(box['x'] + box['width'], 321) + self.assertGreaterEqual(box['y'], -1) + 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)); + }''')) select_all.click() expect(toolbar.get_by_role('status')).to_have_text('3 selected') diff --git a/tests/browser/test_modal_controls.py b/tests/browser/test_modal_controls.py index ec48f1ef47..d9583e40c6 100644 --- a/tests/browser/test_modal_controls.py +++ b/tests/browser/test_modal_controls.py @@ -158,6 +158,25 @@ def test_long_dialog_keeps_dismissal_reachable_after_own_scroll(self): # The entire dialog is the scroll owner. Dismissal must track that # scroll rather than moving off the visual viewport with its content. close = self.check_modal(panel) + overlap = panel.evaluate('''panel => { + const close = panel.querySelector('[data-modal-dismiss]').getBoundingClientRect(); + const details = panel.querySelector('dl'); + const collisions = []; + const walker = document.createTreeWalker(details, NodeFilter.SHOW_TEXT); + while (walker.nextNode()) { + if (!walker.currentNode.textContent.trim()) continue; + const range = document.createRange(); + range.selectNodeContents(walker.currentNode); + for (const box of range.getClientRects()) { + if ( + Math.min(box.right, close.right) - Math.max(box.left, close.left) > 1 && + Math.min(box.bottom, close.bottom) - Math.max(box.top, close.top) > 1 + ) collisions.push(walker.currentNode.textContent.trim()); + } + } + return collisions; + }''') + self.assertEqual([], overlap, overlap) self.capture('modal-book-info-post-scroll-200') close.focus() expect(close).to_be_focused() @@ -338,9 +357,15 @@ def test_export_dialog_uses_native_targets_and_reflows_at_200_percent_text(self) self.assertEqual(5, checkboxes.count()) for checkbox in checkboxes.all(): label = checkbox.locator('xpath=ancestor::label') + text = label.locator('span') self.assertGreaterEqual(label.bounding_box()['height'], 43.99) self.assertLessEqual(label.evaluate('e => e.scrollWidth - e.clientWidth'), 1) self.assertLessEqual(label.locator('span').evaluate('e => e.scrollWidth - e.clientWidth'), 1) + box, copy = checkbox.bounding_box(), text.bounding_box() + self.assertAlmostEqual(box['width'], 20, delta=0.5) + self.assertAlmostEqual(box['height'], 20, delta=0.5) + self.assertAlmostEqual(copy['x'] - (box['x'] + box['width']), 12, delta=1) + self.assertEqual('normal', text.evaluate('e => getComputedStyle(e).overflowWrap')) checkbox.uncheck() start = panel.get_by_role('button', name='Start export', exact=True) expect(start).to_be_disabled() diff --git a/tests/browser/test_panel_usability.py b/tests/browser/test_panel_usability.py index d3b514d556..60dff85b0f 100644 --- a/tests/browser/test_panel_usability.py +++ b/tests/browser/test_panel_usability.py @@ -1,4 +1,5 @@ """Custom-panel focus, occlusion, and calendar geometry in the built application.""" +import re import unittest from pathlib import Path from playwright.sync_api import expect @@ -166,16 +167,34 @@ def test_tracker_history_paginates_without_stranding_keyboard_focus(self): expect(first.get_by_text('Time change:', exact=True)).to_be_visible() expect(first.get_by_text('Character change:', exact=True)).to_be_visible() revert = first.get_by_role('button', name='Revert history item', exact=True) - self.assertGreaterEqual(revert.bounding_box()['height'], 43.99) + revert_box = revert.bounding_box() + self.assertGreaterEqual(revert_box['height'], 43.99) + self.assertLessEqual(revert_box['height'], 64) + expect(revert.get_by_text('Revert', exact=True)).to_be_visible() + self.assertEqual('nowrap', revert.evaluate('e => getComputedStyle(e).whiteSpace')) + self.assertLessEqual(revert.locator('svg').bounding_box()['width'], 18.5) self.assert_unoccluded(revert) - state_text = first.locator('.sr-only').all_text_contents() + save_state = first.locator('[data-tracker-save-state]') + expect(save_state).to_be_visible() + self.assertGreaterEqual(save_state.bounding_box()['height'], 43.99) + self.assertLessEqual(save_state.locator('svg').bounding_box()['width'], 18.5) + state_text = save_state.inner_text() self.assertTrue( - any(value in ('Saved to database', 'Not saved yet') for value in state_text), + 'Saved' in state_text or 'Not saved yet' in state_text, state_text ) 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() @@ -205,6 +224,120 @@ def test_tracker_history_paginates_without_stranding_keyboard_focus(self): expect(trigger).to_be_focused() self.page.evaluate('document.documentElement.style.fontSize = ""') + def test_summary_privacy_targets_and_paging_hold_at_200_percent_text(self): + self.seed_statistics() + self.page.evaluate(reader_fixture('''() => { + localStorage.setItem('lastStatisticsTab', 'Summary'); + localStorage.setItem('lastStatisticsRangeTemplate', 'This Year'); + localStorage.setItem('lastPrimaryReadingDataAggregationMode', 'None'); + localStorage.setItem('lastBlurredTrackerItems', '["readingTime"]'); + }''')) + self.page.set_viewport_size({'width': 320, 'height': 568}) + self.statistics() + self.page.evaluate('document.documentElement.style.fontSize = "200%"') + summary = self.page.get_by_role('group', name='Statistics view').get_by_role( + 'button', name='Summary', exact=True) + expect(summary).to_have_attribute('aria-pressed', 'true') + + summary_root = self.page.get_by_test_id('statistics-summary') + page_trigger = self.page.get_by_role('button', name='Choose statistics page', exact=True) + expect(page_trigger).to_contain_text('PAGE 1 / 61') + self.assertGreaterEqual(page_trigger.bounding_box()['height'], 43.99) + self.assertLessEqual(self.page.evaluate('document.documentElement.scrollWidth - innerWidth'), 1) + table = self.page.get_by_role('table', name='Reading statistics', exact=True) + self.assertLessEqual(summary_root.evaluate('e => e.scrollWidth - e.clientWidth'), 1) + self.assertLessEqual(table.evaluate('e => e.scrollWidth - e.clientWidth'), 1) + + title_control = self.page.get_by_role('button', name='Show full title Panel title 000', exact=True) + for control in ( + self.page.get_by_role('button', name='Delete row Panel title 000', exact=True), + self.page.get_by_role('button', name='Edit row Panel title 000', exact=True), + title_control, + self.page.get_by_role('button', name='Sort by Total Time', exact=True), + ): + control.scroll_into_view_if_needed() + self.assertGreaterEqual(control.bounding_box()['height'], 43.99) + self.assert_unoccluded(control) + + metric = self.page.get_by_role( + 'button', name=re.compile(r'^Total Time for Panel title 000(?:,|:)') + ) + metric.scroll_into_view_if_needed() + self.assertGreaterEqual(metric.bounding_box()['height'], 43.99) + self.assert_unoccluded(metric) + hidden_value = metric.locator('[aria-hidden="true"]').first + expect(hidden_value).to_have_text('••••') + hidden_label = metric.get_attribute('aria-label') + self.assertIn('value hidden', hidden_label) + self.assertNotIn('1 min', hidden_label) + + metric.focus() + metric.press('Enter') + expect(metric).to_have_attribute( + 'aria-label', + re.compile(r'Total Time for Panel title 000: 1 min\. Activate to view details\.') + ) + expect(self.page.get_by_role('dialog', name='Measurement details', exact=True)).to_have_count(0) + metric.press('Enter') + details = self.page.get_by_role('dialog', name='Measurement details', exact=True) + expect(details).to_be_visible() + expect(details).to_contain_text('Time: 1 min') + close = details.get_by_role('button', name='Close measurement details', exact=True) + expect(close).to_be_focused() + self.assertGreaterEqual(close.bounding_box()['height'], 43.99) + self.assert_unoccluded(close) + close.press('Enter') + expect(details).to_have_count(0) + expect(metric).to_be_focused() + + previous = self.page.get_by_role('button', name='Previous statistics page', exact=True) + next_page = self.page.get_by_role('button', name='Next statistics page', exact=True) + expect(previous).to_be_disabled() + expect(next_page).to_be_enabled() + self.assertGreaterEqual(previous.bounding_box()['height'], 43.99) + self.assertGreaterEqual(next_page.bounding_box()['height'], 43.99) + next_page.focus() + next_page.press('Enter') + expect(page_trigger).to_contain_text('PAGE 2 / 61') + expect(next_page).to_be_focused() + + def choose_page(number): + page_trigger.click() + picker = self.page.get_by_role('dialog', name='Statistics pages', exact=True) + expect(picker).to_be_visible() + picker.evaluate('''(dialog, target) => { + const list = [...dialog.querySelectorAll('*')] + .find(node => node.scrollHeight > node.clientHeight); + if (!list) throw new Error('Statistics page list has no scrollport'); + list.scrollTop = target; + }''', (number - 1) * 44) + choice = picker.get_by_role('button', name=str(number), exact=True) + expect(choice).to_be_visible() + choice.scroll_into_view_if_needed() + self.assertGreaterEqual(choice.bounding_box()['height'], 43.99) + choice.focus() + choice.press('Enter') + expect(picker).to_have_count(0) + expect(page_trigger).to_contain_text(f'PAGE {number} / 61') + expect(page_trigger).to_be_focused() + + choose_page(60) + next_page.focus() + next_page.press('Enter') + expect(page_trigger).to_contain_text('PAGE 61 / 61') + expect(next_page).to_be_disabled() + expect(previous).to_be_focused() + expect(summary_root.get_by_role('status')).to_have_text('Page 61 of 61') + choose_page(2) + previous.focus() + previous.press('Enter') + expect(page_trigger).to_contain_text('PAGE 1 / 61') + expect(previous).to_be_disabled() + expect(next_page).to_be_focused() + + self.capture('summary-privacy-paging-200') + self.page.evaluate('document.documentElement.style.fontSize = ""') + def test_heatmap_popup_close_has_its_own_space_and_restores_day_focus(self): self.seed_statistics() for mode in ('light', 'dark'): diff --git a/tests/browser/test_reader_navigation_panels.py b/tests/browser/test_reader_navigation_panels.py index 93d96e3ebb..6b6cf13138 100644 --- a/tests/browser/test_reader_navigation_panels.py +++ b/tests/browser/test_reader_navigation_panels.py @@ -66,11 +66,14 @@ def test_contents_keep_one_scroll_owner_with_enlarged_text_in_short_viewports(se const r=e.getBoundingClientRect(); return e.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2)); }''')) + scroll = panel.locator('[data-toc-scroll]') + expect(scroll).to_have_count(1) + self.assertEqual('auto', scroll.evaluate('e => getComputedStyle(e).overflowY')) footer = panel.get_by_role('button', name='Next Chapter', exact=True) - panel.evaluate('e => e.scrollTop = e.scrollHeight') + footer.scroll_into_view_if_needed() self.assert_box_in_viewport(footer) close = panel.get_by_role('button', name='Close Table of Contents', exact=True) - panel.evaluate('e => e.scrollTop = 0') + scroll.evaluate('e => e.scrollTop = 0') self.assert_hit_target_in_viewport(close) expect(close).to_have_attribute('data-shape', 'circle') self.capture(f'contents-refined-{width}-{height}') diff --git a/tests/browser/test_rhea_ui.py b/tests/browser/test_rhea_ui.py index 6cb4f5b26c..e1fe0c2088 100644 --- a/tests/browser/test_rhea_ui.py +++ b/tests/browser/test_rhea_ui.py @@ -22,12 +22,13 @@ from browser_launch import launch_options -def chaptered_epub(): +def chaptered_epub(title=TITLE): output = io.BytesIO() with zipfile.ZipFile(io.BytesIO(epub())) as source, zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) as target: for item in source.infolist(): value = source.read(item) if item.filename == 'content.opf': + value = value.replace(TITLE.encode(), title.encode()) value = value.replace(b'', b'') value = value.replace(b'', b'').replace(b'', b'') target.writestr(item.filename, value) @@ -156,9 +157,26 @@ def assert_target(control): self.assertLessEqual(menu_box['x'] + menu_box['width'], 321) self.assertLessEqual(menu_box['y'] + menu_box['height'], 321) self.assertLessEqual(menu.evaluate('e => e.scrollWidth - e.clientWidth'), 1) - for item in menu.get_by_role('menuitem').all(): + items = menu.get_by_role('menuitem') + for item in items.all(): box = item.bounding_box() self.assertGreaterEqual(box['height'], 43.99) + # The short menu intentionally scrolls. Keyboard navigation must bring + # its final action completely into view instead of merely exposing a + # clipped label at the viewport edge. + items.first.focus() + for _ in range(items.count() - 1): + self.page.keyboard.press('ArrowDown') + last = items.last + expect(last).to_be_focused() + last_box = last.bounding_box() + self.assertGreaterEqual(last_box['y'], -1) + self.assertLessEqual(last_box['y'] + last_box['height'], 321) + self.assertTrue(last.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)); + }''')) self.page.screenshot(path='test-results/reader-toolbar-enlarged-short.png') self.page.keyboard.press('Escape') expect(menu).to_have_count(0) @@ -167,6 +185,61 @@ def assert_target(control): expect(toolbar).to_have_count(0) expect(self.page.locator('.book-content')).to_be_visible() + def test_short_enlarged_reading_tools_keyboard_scrolls_every_action_fully_into_view(self): + self.open_book() + self.wait_for_fonts() + self.page.set_viewport_size({'width': 320, 'height': 320}) + self.page.evaluate('document.documentElement.style.fontSize = "200%"') + reveal_reader_controls(self.page) + + tools = self.page.get_by_role('button', name='Reading tools', exact=True) + tools.focus() + tools.press('Enter') + menu = self.page.get_by_role('menu') + expect(menu).to_be_visible() + self.assertLessEqual(menu.evaluate('e => e.scrollWidth-e.clientWidth'), 1) + self.assertGreater(menu.evaluate('e => e.scrollHeight-e.clientHeight'), 1) + + labels = menu.get_by_role('menuitem').all_text_contents() + self.assertIn('Save Reading Position', labels) + self.assertIn('Jump to Position', labels) + self.assertIn('Browse Book', labels) + self.assertIn('Search Book', labels) + self.assertIn('Settings', labels) + self.assertIn('Dictionary Setup', labels) + self.assertIn('Statistics', labels) + self.assertIn('User guide', labels) + + # Content owns initial focus. Native menu ArrowDown traversal must reveal + # each item; a merely mounted/clipped row does not count as reachable. + menu.focus() + for expected_label in labels: + self.page.keyboard.press('ArrowDown') + focused = menu.locator('[role="menuitem"]:focus') + expect(focused).to_have_count(1) + self.assertEqual(expected_label, focused.inner_text().strip()) + box = focused.bounding_box() + self.assertGreaterEqual(box['height'], 43.99) + self.assertGreaterEqual(box['x'], -1) + self.assertGreaterEqual(box['y'], -1, (expected_label, box)) + self.assertLessEqual(box['x'] + box['width'], 321, (expected_label, box)) + self.assertLessEqual(box['y'] + box['height'], 321, (expected_label, box)) + self.assertTrue(focused.evaluate('''e => { + const r=e.getBoundingClientRect(); + const x=r.left+r.width/2, y=r.top+r.height/2; + const hit=document.elementFromPoint(x,y); + return !!hit && (hit===e || e.contains(hit)); + }'''), (expected_label, box)) + + # Traversing beyond the final item wraps or remains within the owned + # menu; focus must never fall behind the portal or onto body. + self.page.keyboard.press('ArrowDown') + self.assertTrue(menu.evaluate('e => e.contains(document.activeElement)')) + self.page.screenshot(path='test-results/reader-tools-enlarged-keyboard-scroll.png') + self.page.keyboard.press('Escape') + expect(menu).to_have_count(0) + expect(tools).to_be_focused() + def test_reduced_motion_eliminates_reader_toolbar_entrance_motion(self): self.open_book(font='Klee One') self.wait_for_fonts() @@ -350,6 +423,44 @@ def test_touch_reading_appearance_fits_and_outside_dismissal_restores_controls(s profile.cleanup() self.context, self.page = original_context, original_page + def test_contents_long_title_keeps_chapters_and_dismissal_reachable_at_200_percent(self): + long_title = ('A deliberately long book title ' * 8).strip() + self.page.goto(self.origin + reader_fixture('/reader-web/manage')) + expect(self.page.locator('input[type=file][webkitdirectory]')).to_be_attached() + self.page.locator('input[type=file][accept*=".epub"]').first.set_input_files({ + 'name': 'long-title.epub', 'mimeType': 'application/epub+zip', + 'buffer': chaptered_epub(long_title)}) + self.page.get_by_role('button', name='Read ' + long_title.strip(), exact=True).click(timeout=30000) + expect(self.page.locator('.book-content')).to_have_attribute('aria-busy', 'false') + self.wait_for_fonts() + self.page.set_viewport_size({'width': 320, 'height': 320}) + self.page.evaluate('document.documentElement.style.fontSize = "200%"') + reveal_reader_controls(self.page) + self.page.get_by_role('button', name='Contents', exact=True).click() + panel = self.page.get_by_role('dialog', name='Table of contents', exact=True) + scroll = panel.locator('[data-toc-scroll]') + self.assertGreater(scroll.evaluate('e => e.clientHeight'), 44) + self.assertGreater(scroll.evaluate('e => e.scrollHeight - e.clientHeight'), 100) + close = panel.get_by_role('button', name='Close Table of Contents', exact=True) + before = close.bounding_box() + chapters = panel.get_by_role('navigation', name='Chapters', exact=True) + for name in ('The journey begins', 'A new morning'): + chapter = chapters.get_by_role('button', name=name, exact=True) + chapter.scroll_into_view_if_needed() + bounds = chapter.bounding_box() + self.assertGreaterEqual(bounds['height'], 43.99) + self.assertTrue(chapter.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)); + }''')) + self.assertAlmostEqual(close.bounding_box()['y'], before['y'], delta=1) + close.click(trial=True) + chapters.get_by_role('button', name='A new morning', exact=True).click() + expect(panel).to_have_count(0) + expect(self.page.locator('.book-content')).to_contain_text('A new morning') + self.page.evaluate('document.documentElement.style.fontSize = ""') + def test_contents_navigation_reflows_and_returns_focus_at_phone_and_desktop(self): self.context.add_init_script(reader_fixture("if (location.pathname.endsWith('/manage')) { localStorage.setItem('fontFamilyGroupOne', 'Klee One'); localStorage.setItem('viewMode', 'paginated'); }")) self.page.goto(self.origin + reader_fixture('/reader-web/manage')) @@ -359,6 +470,62 @@ def test_contents_navigation_reflows_and_returns_focus_at_phone_and_desktop(self self.page.get_by_role('button', name='Read ' + TITLE, exact=True).click(timeout=30000) expect(self.page.locator('.book-content')).to_have_attribute('aria-busy', 'false') self.wait_for_fonts() + + self.page.set_viewport_size({'width': 320, 'height': 360}) + self.page.evaluate('document.documentElement.style.fontSize = "200%"') + reveal_reader_controls(self.page) + self.page.get_by_role('button', name='Contents', exact=True).click() + enlarged = self.page.get_by_role('dialog', name='Table of contents', exact=True) + heading = enlarged.get_by_role('heading', name='Contents', exact=True) + close = enlarged.get_by_role('button', name='Close Table of Contents', exact=True) + expect(heading).to_be_visible() + self.assertEqual('nowrap', heading.evaluate('e => getComputedStyle(e).whiteSpace')) + heading_box, close_box = heading.bounding_box(), close.bounding_box() + self.assertLessEqual(heading_box['height'], float( + heading.evaluate('e => parseFloat(getComputedStyle(e).lineHeight)')) + 1) + self.assertLessEqual(heading_box['x'] + heading_box['width'], close_box['x'] - 1) + self.assertGreaterEqual(close_box['width'], 43.99) + self.assertGreaterEqual(close_box['height'], 43.99) + self.assertLessEqual(close_box['x'] + close_box['width'], 321) + self.assertLessEqual(close_box['y'] + close_box['height'], 361) + self.assertTrue(close.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)); + }''')) + + scroll = enlarged.locator('[data-toc-scroll]') + self.page.wait_for_function( + 'e => e.scrollHeight > e.clientHeight', + arg=scroll.element_handle() + ) + scroll.evaluate('e => e.scrollTop = e.scrollHeight') + self.page.wait_for_function('e => e.scrollTop > 0', arg=scroll.element_handle()) + self.assertEqual('hidden', enlarged.evaluate('e => getComputedStyle(e).overflowY')) + for control_name in ('Close Table of Contents', 'Previous Chapter', 'Next Chapter'): + control = enlarged.get_by_role('button', name=control_name, exact=True) + control.scroll_into_view_if_needed() + bounds = control.bounding_box() + self.assertGreaterEqual(bounds['height'], 43.99) + self.assertGreaterEqual(bounds['x'], -1) + self.assertGreaterEqual(bounds['y'], -1) + self.assertLessEqual(bounds['x'] + bounds['width'], 321) + self.assertLessEqual(bounds['y'] + bounds['height'], 361) + if control.is_enabled(): + 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)); + }'''), control_name) + else: + # Disabled chapter navigation intentionally has pointer-events:none. + expect(control).to_be_disabled() + + self.page.screenshot(path='test-results/contents-enlarged-word-intact.png') + close.click() + expect(enlarged).to_have_count(0) + self.page.evaluate('document.documentElement.style.fontSize = ""') + for width in (320, 390, 1440): self.page.set_viewport_size({'width': width, 'height': 844}) reveal_reader_controls(self.page) @@ -1108,29 +1275,123 @@ def test_statistics_navigation_and_options_sheet(self): self.page.keyboard.press('Escape') expect(panel).to_have_count(0) + def test_statistics_options_close_stays_reachable_after_enlarged_body_scroll(self): + self.page.goto(self.origin + reader_fixture('/reader-web/statistics')) + self.page.set_viewport_size({'width': 320, 'height': 320}) + self.page.evaluate('document.documentElement.style.fontSize = "200%"') + + trigger = self.page.get_by_role('button', name='Statistics options', exact=True) + trigger.click() + self.page.get_by_role('menuitem', name='Statistics Settings', exact=True).click() + panel = self.page.get_by_role('dialog', name='Statistics options', exact=True) + expect(panel).to_be_visible() + # The shared sheet owns its scrollport and keeps bounded chrome sticky. + scroll = panel + expect(panel.locator('[data-sticky-header]')).to_have_css('position', 'sticky') + self.page.wait_for_function('e => e.scrollHeight > e.clientHeight', arg=scroll.element_handle()) + scroll.evaluate('e => e.scrollTop = e.scrollHeight') + self.page.wait_for_function('e => e.scrollTop > 0', arg=scroll.element_handle()) + + close = panel.get_by_role('button', name='Close statistics options', exact=True) + box = close.bounding_box() + viewport = self.page.evaluate('''() => { + const v = visualViewport; + return { + left: v?.offsetLeft ?? 0, + top: v?.offsetTop ?? 0, + right: (v?.offsetLeft ?? 0) + (v?.width ?? innerWidth), + bottom: (v?.offsetTop ?? 0) + (v?.height ?? innerHeight) + }; + }''') + self.assertGreaterEqual(box['width'], 43.99) + self.assertGreaterEqual(box['height'], 43.99) + self.assertGreaterEqual(box['x'], viewport['left'] - 1) + self.assertGreaterEqual(box['y'], viewport['top'] - 1) + self.assertLessEqual(box['x'] + box['width'], viewport['right'] + 1) + self.assertLessEqual(box['y'] + box['height'], viewport['bottom'] + 1) + center_hit = '''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)); + }''' + try: + self.page.wait_for_function(center_hit, arg=close.element_handle(), timeout=2000) + except Exception as error: + diagnostics = close.evaluate('''e => { + const r = e.getBoundingClientRect(); + const x = r.left + r.width / 2; + const y = r.top + r.height / 2; + const hit = document.elementFromPoint(x, y); + const describe = node => node && ({ + tag: node.tagName, id: node.id, className: String(node.className || ''), + role: node.getAttribute('role'), text: (node.textContent || '').trim().slice(0, 100), + rect: (() => { const b = node.getBoundingClientRect(); return {x:b.x,y:b.y,width:b.width,height:b.height}; })() + }); + return { point: {x, y}, close: describe(e), hit: describe(hit), + stack: document.elementsFromPoint(x, y).slice(0, 6).map(describe), + panel: describe(e.closest('[role="dialog"]')) }; + }''') + self.fail(f'Close control center hit-test did not settle: {diagnostics}; {error}') + self.assertEqual('auto', panel.evaluate('e => getComputedStyle(e).overflowY')) + + Path('test-results').mkdir(exist_ok=True) + self.page.screenshot( + path='test-results/statistics-options-post-scroll-200.png' + ) + close.focus() + expect(close).to_be_focused() + close.press('Enter') + expect(panel).to_have_count(0) + expect(trigger).to_be_focused() + self.page.evaluate('document.documentElement.style.fontSize = ""') + def test_statistics_raw_recovery_download_preserves_ambiguous_days(self): self.page.goto(self.origin + reader_fixture('/reader-web/statistics')) expect(self.page.get_by_test_id('shared-statistics-screen')).to_be_visible() expect(self.page.get_by_role('button', name='Statistics options', exact=True)).to_be_visible() # The header can render before the application's database upgrade. A # bare open here would create an empty v1 database if it wins that race. - # Observe the real schema, never create or upgrade it from this fixture. - self.page.wait_for_function(reader_fixture('''() => new Promise((resolve, reject) => { - const open = indexedDB.open('books'); - let absent = false; - open.onupgradeneeded = () => { absent = true; open.transaction.abort(); }; - open.onerror = () => absent ? resolve(false) : reject(open.error); - open.onsuccess = () => { - const db = open.result; - const ready = ['statistic', 'readerStatistic', 'readerStatisticMigration'] - .every(name => db.objectStoreNames.contains(name)); - db.close(); - resolve(ready); + # Wait on the real schema with one bounded Promise loop; do not rely on + # wait_for_function polling an async predicate or upgrade from the fixture. + self.page.evaluate(reader_fixture('''() => new Promise((resolve, reject) => { + const required = ['statistic', 'readerStatistic', 'readerStatisticMigration']; + const deadline = performance.now() + 15000; + const retry = () => { + if (performance.now() >= deadline) { + reject(new Error('Statistics schema did not become ready')); + return; + } + setTimeout(check, 50); }; + const check = () => { + const open = indexedDB.open('books'); + let absent = false; + open.onupgradeneeded = () => { + absent = true; + open.transaction.abort(); + }; + open.onerror = () => { + if (absent) retry(); + else reject(open.error); + }; + open.onsuccess = () => { + const db = open.result; + const ready = required.every(name => db.objectStoreNames.contains(name)); + db.close(); + if (ready) resolve(); + else retry(); + }; + }; + check(); })''')) self.page.evaluate(reader_fixture('''() => new Promise((resolve, reject) => { const deadline = setTimeout(() => reject(new Error('Statistics seed transaction stalled')), 15000); const open = indexedDB.open('books'); + open.onupgradeneeded = () => { + open.transaction.abort(); + clearTimeout(deadline); + reject(new Error('Statistics database disappeared before seeding')); + }; open.onerror = () => { clearTimeout(deadline); reject(open.error); }; open.onsuccess = () => { const db = open.result; diff --git a/tests/browser/test_unified_search.py b/tests/browser/test_unified_search.py index 92c9fe5887..b1371396db 100644 --- a/tests/browser/test_unified_search.py +++ b/tests/browser/test_unified_search.py @@ -683,7 +683,11 @@ def test_video_titles_and_published_transcripts_join_unified_search_without_medi # library usable, explain the reconnect requirement, and never invent a # source merely because the global search result was actionable. expect(self.page.get_by_role('heading', name='Videos', exact=True)).to_be_visible() - expect(self.page.get_by_role('status')).to_contain_text( + expect( + self.page.get_by_role('status').filter( + has_text='Reopen this video to reconnect its local file' + ) + ).to_contain_text( 'Reopen this video to reconnect its local file, or sign in to reconnect its cloud folder.', timeout=30000, ) diff --git a/tests/browser/test_voice_pitch.py b/tests/browser/test_voice_pitch.py index e1c4d32d03..0931c78750 100644 --- a/tests/browser/test_voice_pitch.py +++ b/tests/browser/test_voice_pitch.py @@ -20,7 +20,7 @@ First gated cue 2 -00:00:12,000 --> 00:00:14,000 +00:00:20,000 --> 00:00:22,000 Second gated cue ''' @@ -60,7 +60,11 @@ class VoicePitchBrowser(existing.WhispersyncBrowser): @classmethod def setUpClass(cls): OUTPUT.mkdir(parents=True, exist_ok=True) + cls.browser = None + cls.playwright = None + cls.thread = None cls.server = ThreadingHTTPServer(('127.0.0.1', 0), PitchHandler) + cls.addClassCleanup(cls._close_resources) cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) cls.thread.start() cls.origin = f'http://127.0.0.1:{cls.server.server_port}' @@ -71,10 +75,31 @@ def setUpClass(cls): cls.browser = getattr(cls.playwright, existing.BROWSER_OPTIONS.browser).launch(**launch_options((getattr(cls.playwright, existing.BROWSER_OPTIONS.browser)).name, **launch)) cls.wav = voice_fixture() + @classmethod + def _close_resources(cls): + try: + if cls.browser is not None: + cls.browser.close() + finally: + try: + if cls.playwright is not None: + cls.playwright.stop() + finally: + if cls.thread is not None and cls.thread.is_alive(): + cls.server.shutdown() + cls.server.server_close() + if cls.thread is not None: + cls.thread.join() + + @classmethod + def tearDownClass(cls): + # unittest runs registered class cleanups after success or setup failure. + pass + def setUp(self): super().setUp() self.context.add_init_script('''(() => { - window.__pitchQA = {created: 0, terminated: 0, analysisSent: 0, results: [], errors: []} + window.__pitchQA = {created: 0, terminated: 0, analysisSent: 0, analysisTimes: [], results: [], errors: []} const NativeWorker = window.Worker window.Worker = class extends NativeWorker { constructor(url, options) { @@ -93,7 +118,10 @@ def setUp(self): } } postMessage(message, transfer) { - if (this.pitch && message?.type === 'analyze') __pitchQA.analysisSent++ + if (this.pitch && message?.type === 'analyze') { + __pitchQA.analysisSent++; + __pitchQA.analysisTimes.push(document.querySelector('audio')?.currentTime); + } return transfer === undefined ? super.postMessage(message) : super.postMessage(message, transfer) @@ -203,7 +231,7 @@ def test_voice_pitch_stops_sampling_between_timed_cues(self): expect(self.page.get_by_text('gapped.srt · 2 cues', exact=True)).to_be_visible() # prepare() leaves playback paused after 8 seconds: squarely inside the - # 2–12 second subtitle gap. Resume and prove that no analysis requests + # 2–20 second subtitle gap. Resume and prove that no analysis requests # are sent while the audio clock advances through background-only time. before = self.page.evaluate('__pitchQA.analysisSent') self.page.locator('.panel').get_by_role('button', name='Play', exact=True).click() @@ -212,7 +240,10 @@ def test_voice_pitch_stops_sampling_between_timed_cues(self): self.page.wait_for_function( '(t) => document.querySelector("audio").currentTime > t + .7', arg=start) self.page.wait_for_timeout(250) - self.assertEqual(before, self.page.evaluate('__pitchQA.analysisSent')) + gap_time = self.page.locator('audio').evaluate('a => a.currentTime') + self.assertLess(gap_time, 19.5, 'The observation must remain inside the authored gap') + self.assertEqual(before, self.page.evaluate('__pitchQA.analysisSent'), + self.page.evaluate('__pitchQA.analysisTimes')) # Enter the next authored cue through the real transcript control. next_cue = self.page.get_by_role('button').filter(has_text='Second gated cue').first diff --git a/tests/media/app-browser.py b/tests/media/app-browser.py index b0cc444e8f..2914ef4904 100644 --- a/tests/media/app-browser.py +++ b/tests/media/app-browser.py @@ -4,6 +4,7 @@ import json import os import pathlib +import re import sys import threading from playwright.sync_api import sync_playwright, expect @@ -147,6 +148,7 @@ def upload(): upload() shelf = page.get_by_label('Video library', exact=True) card_select = shelf.get_by_role('checkbox').first + library_card = card_select.locator('xpath=ancestor::article[1]') expect(card_select).to_be_visible() # Upload may publish a verified identity between browser round trips. # Sample the current native checkbox's label and pointer hit atomically. @@ -179,12 +181,59 @@ def upload(): 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() + expect(library_card).not_to_have_class(re.compile(r'.*\bselected\b.*')) 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() - results.append('video card selection has a native 44px keyboard and pointer target') + + select_visible.focus() + select_visible.press('Enter') + expect(card_select).to_be_checked() + expect(library_card).to_have_class(re.compile(r'.*\bselected\b.*')) + expect(selection_status).to_have_text('1 video selected') + 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') + + 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.emulate_media(forced_colors='active') + select_visible.focus() + select_visible.press('Enter') + expect(library_card).to_have_class(re.compile(r'.*\bselected\b.*')) + selected_outline = library_card.evaluate("node => getComputedStyle(node).outlineStyle") + assert selected_outline != 'none', selected_outline + page.emulate_media(forced_colors='none') + clear_selection.focus() + clear_selection.press('Enter') + + 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) @@ -371,7 +420,6 @@ def assert_reachable(control): for control in library_controls: assert_reachable(control) - library_card = page.locator('.video-card').filter(has_text='video.mp4') library_card.scroll_into_view_if_needed() expect(library_card).to_be_visible() assert library_card.evaluate("node => node.scrollWidth-node.clientWidth") <= 1 diff --git a/tests/media/app-shell-browser.py b/tests/media/app-shell-browser.py new file mode 100644 index 0000000000..ca48b1fab7 --- /dev/null +++ b/tests/media/app-shell-browser.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""Codec-independent Videos route acceptance in Chromium/WebKit. + +Uses the actual built Videos route and native browser storage. It deliberately does not +open media so Linux codec availability cannot turn a route/UI regression into a +false browser-compatibility failure. +""" +import argparse +from contextlib import ExitStack +import json +from pathlib import Path +import sys +import threading + +from playwright.sync_api import expect, sync_playwright + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'tests/browser')) +from test_static_reader import StaticHandler, ThreadingHTTPServer +from browser_launch import launch_options + + +def inside_viewport(locator, width, height, *, hit_test=True): + box = locator.bounding_box() + assert box, locator + assert box['width'] >= 43.5 and box['height'] >= 43.5, box + assert box['x'] >= -1 and box['y'] >= -1, box + assert box['x'] + box['width'] <= width + 1, box + assert box['y'] + box['height'] <= height + 1, box + if hit_test: + assert locator.evaluate("""node => { + const r=node.getBoundingClientRect(); + const hit=document.elementFromPoint(r.left+r.width/2,r.top+r.height/2); + return !!hit && (hit===node || node.contains(hit)); + }"""), box + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--engine', choices=('chromium', 'webkit'), required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=True) + + server = ThreadingHTTPServer(('127.0.0.1', 0), StaticHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + origin = f'http://127.0.0.1:{server.server_port}' + errors = [] + checks = [] + + with ExitStack() as cleanup: + cleanup.callback(thread.join) + cleanup.callback(server.server_close) + cleanup.callback(server.shutdown) + playwright = cleanup.enter_context(sync_playwright()) + browser = getattr(playwright, args.engine).launch(**launch_options(args.engine)) + cleanup.callback(browser.close) + context = browser.new_context(locale='en-CA', viewport={'width': 1280, 'height': 900}) + cleanup.callback(context.close) + page = context.new_page() + page.on('pageerror', lambda error: errors.append(str(error))) + page.set_default_timeout(15000) + try: + page.goto(origin + '/reader-web/videos') + expect(page.get_by_role('heading', name='Videos', exact=True)).to_be_visible() + media = page.locator('.manabi-media') + expect(media).to_be_visible() + nav = page.get_by_role('navigation', name='Library sections', exact=True) + expect(nav).to_be_visible() + expect(nav.locator('[aria-current="page"]')).to_have_text('Videos') + + # Empty-library controls are the first-run product surface. + controls = [ + page.get_by_role('button', name='Add videos', exact=True), + page.get_by_role('button', name='Open local folder', exact=True), + page.get_by_role('searchbox', name='Search videos', exact=True), + page.get_by_label('Sort videos', exact=True), + page.get_by_label('Filter videos', exact=True), + page.get_by_role('button', name='Select visible videos', exact=True), + page.get_by_role('button', name='Clear selection', exact=True), + page.get_by_role('button', name='Generate missing transcripts', exact=True), + ] + for control in controls: + expect(control).to_be_visible() + assert control.bounding_box()['height'] >= 43.5 + page.get_by_role('button', name='Add videos', exact=True).click(trial=True) + for name in ('Select visible videos', 'Clear selection', 'Generate missing transcripts'): + expect(page.get_by_role('button', name=name, exact=True)).to_be_disabled() + selection = page.get_by_role('group', name='Video selection actions', exact=True) + selection_status = selection.locator('[aria-live=polite]') + expect(selection_status).to_have_text('No videos selected') + expect(selection_status).to_have_attribute('aria-atomic', 'true') + checks.append('empty video library keeps unavailable selection actions disabled and announced') + + # Disclosure/settings controls must remain usable even without media. + summary = page.get_by_text('Transcription and sync', exact=True) + assert summary.bounding_box()['height'] >= 43.5 + summary.click() + sync = page.get_by_label( + 'Sign in to sync; everything remains local otherwise', exact=True + ) + expect(sync).to_be_disabled() + sync_target = sync.locator('..') + sync_box = sync_target.bounding_box() + assert sync_box and sync_box['height'] >= 43.5, sync_box + remove_model = page.get_by_role( + 'button', name='Remove cached transcription model', exact=True + ) + expect(remove_model).to_be_visible() + assert remove_model.bounding_box()['height'] >= 43.5 + checks.append('transcription disclosure exposes bounded offline-first controls') + + # Stress actual app chrome at Dynamic Type-like scaling. + page.set_viewport_size({'width': 320, 'height': 568}) + page.evaluate("document.documentElement.style.fontSize='200%'") + expect(media).to_be_visible() + assert page.evaluate('document.documentElement.scrollWidth-innerWidth') <= 1 + assert media.evaluate('node => node.scrollWidth-node.clientWidth') <= 1 + for control in controls: + control.scroll_into_view_if_needed() + inside_viewport(control, 320, 568, hit_test=control.is_enabled()) + summary.scroll_into_view_if_needed() + inside_viewport(summary, 320, 568) + sync_target.scroll_into_view_if_needed() + inside_viewport(sync_target, 320, 568) + remove_model.scroll_into_view_if_needed() + inside_viewport(remove_model, 320, 568) + + page.set_viewport_size({'width': 320, 'height': 320}) + remove_model.scroll_into_view_if_needed() + inside_viewport(remove_model, 320, 320) + summary.scroll_into_view_if_needed() + inside_viewport(summary, 320, 320) + page.set_viewport_size({'width': 320, 'height': 568}) + nav_items = nav.locator('a, [aria-current]') + for item in nav_items.all(): + item.scroll_into_view_if_needed() + inside_viewport(item, 320, 568) + assert item.evaluate("e => getComputedStyle(e).whiteSpace") == 'nowrap' + assert item.bounding_box()['height'] <= 80 + + caption_labels = page.locator('.caption-controls > label') + expect(caption_labels).to_have_count(3) + for label in caption_labels.all(): + label.scroll_into_view_if_needed() + label_box = label.bounding_box() + assert label_box['width'] >= 250, label_box + assert label_box['x'] >= -1 and label_box['x'] + label_box['width'] <= 321 + + page.screenshot(path=str(args.output / f'{args.engine}-videos-shell-200.png'), full_page=True) + checks.append('Videos route reflows at 320px / 200% text without horizontal overflow') + + # Keyboard navigation across the real Books/Videos route boundary. + books = nav.get_by_role('link', name='Books', exact=True) + books.focus() + expect(books).to_be_focused() + books.press('Enter') + expect(page).to_have_url(origin + '/reader-web/manage') + library_nav = page.get_by_role('navigation', name='Library sections', exact=True) + expect(library_nav).to_be_visible() + books_current = library_nav.get_by_role('link', name='Books', exact=True) + expect(books_current).to_have_attribute('aria-current', 'page') + assert books_current.evaluate("e => getComputedStyle(e).whiteSpace") == 'nowrap' + videos = library_nav.get_by_role('link', name='Videos', exact=True) + inside_viewport(videos, 320, 568) + assert videos.evaluate("e => getComputedStyle(e).whiteSpace") == 'nowrap' + videos.focus() + videos.press('Enter') + expect(page).to_have_url(origin + '/reader-web/videos') + expect(page.get_by_role('heading', name='Videos', exact=True)).to_be_visible() + checks.append('Books/Videos route switcher works by keyboard in enlarged mobile layout') + + assert not errors, errors + except Exception: + page.screenshot(path=str(args.output / f'{args.engine}-failure.png'), full_page=True) + (args.output / f'{args.engine}-failure.html').write_text(page.content()) + raise + finally: + (args.output / f'{args.engine}-results.json').write_text( + json.dumps( + { + 'engine': args.engine, + 'checks': checks, + 'passed': len(checks), + 'pageErrors': errors, + 'boundary': ( + 'built Videos route + native browser storage; ' + 'codec/playback/providers/ASR intentionally excluded' + ), + }, + indent=2, + ) + + '\n' + ) + + + +if __name__ == '__main__': + main() diff --git a/tests/media/sparse-transcription.test.mjs b/tests/media/sparse-transcription.test.mjs index 4f54bef717..f5a63b098f 100644 --- a/tests/media/sparse-transcription.test.mjs +++ b/tests/media/sparse-transcription.test.mjs @@ -17,6 +17,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) => ({ @@ -102,6 +103,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'); diff --git a/tests/unit/browser-migration-primitives.test.mjs b/tests/unit/browser-migration-primitives.test.mjs index 71d9672e02..7592972dec 100644 --- a/tests/unit/browser-migration-primitives.test.mjs +++ b/tests/unit/browser-migration-primitives.test.mjs @@ -519,14 +519,16 @@ test('Library section tabs preserve wrapping, text-zoom-safe spacing and subpath window.document.documentElement.style.fontSize = fontSize; const layout = window.getComputedStyle(nav); assert.equal(layout.flexWrap, 'wrap'); - assert.equal(layout.maxWidth, 'calc(100% - 48px)'); + assert.equal(layout.width, 'fit-content'); + assert.equal(layout.maxWidth, 'calc(100% - 32px)'); assert.equal(layout.gap, '6px'); - assert.equal(layout.marginLeft, '24px'); + assert.equal(layout.marginLeft, '16px'); for (const link of links) { const style = window.getComputedStyle(link); assert.equal(style.minHeight, '44px'); assert.equal(style.maxWidth, '100%'); assert.equal(style.minWidth, '0'); + assert.equal(style.whiteSpace, 'nowrap'); assert.equal(style.overflowWrap, 'anywhere'); } } diff --git a/tests/unit/fixtures/legacy-snippet-links.mjs b/tests/unit/fixtures/legacy-snippet-links.mjs new file mode 100644 index 0000000000..b676c21e30 --- /dev/null +++ b/tests/unit/fixtures/legacy-snippet-links.mjs @@ -0,0 +1,50 @@ +/** @license BSD-3-Clause */ +// Version-1 portable bytes admitted before link display hardening. Keep this +// independent of createSnippet so a changed writer cannot conceal a read regression. +export function legacySnippetLinks() { + const links = [ + { text: 'External self', target: '_self', rel: 'external' }, + { text: 'Empty self', target: '_self', rel: '' }, + { text: 'Opener blank', target: '_blank', rel: 'OpEnEr external' }, + { text: 'Noreferrer blank', target: '_blank', rel: 'noreferrer' }, + { text: 'Default opener', target: null, rel: 'opener' }, + { text: 'Default links', target: null, rel: null }, + { text: 'Bounded metadata', target: '_blank', rel: 'x'.repeat(120) } + ]; + return { + format: 'manabi-snippet', + version: 1, + id: '11111111-1111-4111-8111-111111111111', + revision: '22222222-2222-4222-8222-222222222222', + parents: ['33333333-3333-4333-8333-333333333333'], + title: { mode: 'custom', text: 'Legacy link metadata' }, + createdAt: 1000, + modifiedAt: 2000, + captures: ['44444444-4444-4444-8444-444444444444'], + source: { title: 'Original source', url: 'https://example.com/source', quote: 'Authored text' }, + content: { + type: 'doc', + content: links.map(({ text, ...attrs }, index) => ({ + type: 'paragraph', + attrs: { id: '00000000-0000-4000-8000-' + String(index + 1).padStart(12, '0') }, + content: [ + { + type: 'text', + text, + marks: [ + { + type: 'link', + attrs: { + href: 'https://example.com/legacy/' + index, + ...attrs, + class: null, + title: 'Original link' + } + } + ] + } + ] + })) + } + }; +} diff --git a/tests/unit/foliate-annotation-snapshot.test.mjs b/tests/unit/foliate-annotation-snapshot.test.mjs index ba97e42b1c..a9017035d3 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 === '$lib/state/store') return { get: () => ({ status: 'ready' }) }; if (name === '$lib/manabi/client') return { account: {}, localProfileUser: () => profile }; if (name === '$lib/manabi/operation-scope') 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); +}); diff --git a/tests/unit/foliate-publication-data.test.mjs b/tests/unit/foliate-publication-data.test.mjs index 94f1177770..5ddfa9a9c3 100644 --- a/tests/unit/foliate-publication-data.test.mjs +++ b/tests/unit/foliate-publication-data.test.mjs @@ -294,3 +294,15 @@ 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 + ); +}); diff --git a/tests/unit/indexeddb-transaction-lifetime.test.mjs b/tests/unit/indexeddb-transaction-lifetime.test.mjs new file mode 100644 index 0000000000..0fccf2554f --- /dev/null +++ b/tests/unit/indexeddb-transaction-lifetime.test.mjs @@ -0,0 +1,439 @@ +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'); +}); + +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 + }) + } + }, + '$lib/state/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); +}); + +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, []); +}); diff --git a/tests/unit/library-reader-write-ownership.test.mjs b/tests/unit/library-reader-write-ownership.test.mjs index dccba48828..e65583f060 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 }, '$lib/state/store': { get: (value) => value.value }, '$lib/manabi/client': { account: { value: { status: 'ready' } }, diff --git a/tests/unit/library-source-snapshot.test.mjs b/tests/unit/library-source-snapshot.test.mjs new file mode 100644 index 0000000000..254eed717b --- /dev/null +++ b/tests/unit/library-source-snapshot.test.mjs @@ -0,0 +1,203 @@ +/** @license BSD-3-Clause */ +import assert from 'node:assert/strict'; +import { Buffer } from 'node:buffer'; +import { build } from 'esbuild'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const fixtureKey = 'manabi-library-source-snapshot'; +const state = { + profile: null, + current: null, + local: [], + dav: [], + cache: new Map(), + live: [], + requestError: null, + requestHook: null, + writes: [] +}; +globalThis[Symbol.for(fixtureKey)] = state; + +const mocks = { + '../snippets/document': `export const isSnippetFile = () => false;`, + './source-binding': `export const boundLibrarySource = (source) => source;`, + '$lib/manabi/client': ` + const state = globalThis[Symbol.for('manabi-library-source-snapshot')]; + export const localProfileUser = () => state.profile ? { id: state.profile } : null; + export const currentUser = () => state.current ? { id: state.current } : null; + export const request = async () => { + await state.requestHook?.(); + if (state.requestError) throw state.requestError; + return { items: state.live }; + };`, + '$lib/manabi/persistence': ` + const state = globalThis[Symbol.for('manabi-library-source-snapshot')]; + export const integrationDB = async () => ({ + getAll: async (name) => name === 'localLibraries' ? structuredClone(state.local) : [] + }); + export const metadata = async (key) => structuredClone(state.cache.get(key)); + export const setMetadata = async (key, value) => { + state.writes.push([key, structuredClone(value)]); + state.cache.set(key, structuredClone(value)); + };`, + '$lib/manabi/sources': ` + export class CloudLibrary {} + export class LocalLibrarySource {} + export const supportedBook = () => false;`, + '$lib/webdav/source': ` + const state = globalThis[Symbol.for('manabi-library-source-snapshot')]; + export const davSources = async () => structuredClone(state.dav); + export const davSource = async () => { throw new Error('unused'); };`, + './organization': `export const sourceKey = (source) => + JSON.stringify([source.owner, source.id, source.root]);`, + './series-metadata': ` + export const isSeriesMetadataFilename = () => false; + export const seriesMetadataFilename = '.manabi-reader.yaml';` +}; + +const result = await build({ + stdin: { + contents: `export { sourceSnapshot, sourceDescriptors } from './src/lib/library/catalog.ts';`, + resolveDir: fileURLToPath(new URL('../../apps/web/', import.meta.url)) + }, + bundle: true, + platform: 'node', + format: 'esm', + target: 'node24', + write: false, + plugins: [ + { + name: 'source-snapshot-fixture', + setup(builder) { + builder.onResolve({ filter: /.*/ }, (args) => + Object.hasOwn(mocks, args.path) ? { path: args.path, namespace: 'fixture' } : undefined + ); + builder.onLoad({ filter: /.*/, namespace: 'fixture' }, (args) => ({ + contents: mocks[args.path], + loader: 'js' + })); + } + } + ] +}); +const { sourceSnapshot, sourceDescriptors } = await import( + 'data:text/javascript;base64,' + Buffer.from(result.outputFiles[0].text).toString('base64') +); + +function reset() { + state.profile = null; + state.current = null; + state.local = []; + state.dav = []; + state.cache.clear(); + state.live = []; + state.requestError = null; + state.requestHook = null; + state.writes = []; +} +const local = (id = 'local-1') => ({ id, name: 'Local', handle: {}, writable: true }); +const dav = (id = 'webdav-1') => ({ + id, + name: 'DAV', + url: 'https://dav.test/books/', + username: '', + writable: false +}); +const cloud = (id, provider = 'dropbox', root = 'Books') => ({ + id, + provider, + roots: [root], + needs_reconnect: false +}); + +test('no-account source snapshot is locally authoritative and unchanged for sourceDescriptors callers', async () => { + reset(); + state.local = [local()]; + state.dav = [dav()]; + const snapshot = await sourceSnapshot(); + assert.equal(snapshot.cloudAuthoritative, true); + assert.deepEqual( + snapshot.sources.map((source) => source.provider), + ['local', 'webdav'] + ); + assert.deepEqual(await sourceDescriptors(), snapshot.sources); + assert.deepEqual(state.writes, []); +}); + +test('successful live cloud refresh replaces cached sources and marks absence authoritative', async () => { + reset(); + state.profile = state.current = 'alice'; + state.cache.set('library-sources:alice', [ + { + id: 'cached', + owner: 'alice', + root: 'Old', + name: 'Old', + provider: 'dropbox' + } + ]); + state.live = [cloud('live-google', 'google', 'Drive'), cloud('live-dropbox')]; + const snapshot = await sourceSnapshot(); + assert.equal(snapshot.cloudAuthoritative, true); + assert.deepEqual( + snapshot.sources.map((source) => source.id), + ['live-google', 'live-dropbox'] + ); + assert.equal(state.writes.length, 1); + assert.deepEqual(state.cache.get('library-sources:alice'), snapshot.sources); +}); + +test('failed cloud refresh preserves cached sources but never treats their absence as authoritative', async () => { + reset(); + state.profile = state.current = 'alice'; + const cached = { + id: 'cached', + owner: 'alice', + root: 'Books', + name: 'Books', + provider: 'dropbox' + }; + state.cache.set('library-sources:alice', [cached]); + state.requestError = new Error('offline'); + const snapshot = await sourceSnapshot(); + assert.equal(snapshot.cloudAuthoritative, false); + assert.deepEqual(snapshot.sources, [cached]); + assert.deepEqual(state.writes, []); +}); + +test('profile/current-account mismatch can use cache for display but not disconnect evidence', async () => { + reset(); + state.profile = 'alice'; + state.current = 'bob'; + const cached = { + id: 'cached', + owner: 'alice', + root: 'Books', + name: 'Books', + provider: 'dropbox' + }; + state.cache.set('library-sources:alice', [cached]); + state.live = [cloud('must-not-request')]; + const snapshot = await sourceSnapshot(); + assert.equal(snapshot.cloudAuthoritative, false); + assert.deepEqual(snapshot.sources, [cached]); + assert.deepEqual(state.writes, []); +}); + +test('account change during live connection fetch suppresses cloud publication and authority', async () => { + reset(); + state.profile = state.current = 'alice'; + state.local = [local()]; + state.live = [cloud('late')]; + state.requestHook = async () => { + state.current = 'bob'; + }; + const snapshot = await sourceSnapshot(); + assert.equal(snapshot.cloudAuthoritative, false); + assert.deepEqual( + snapshot.sources.map((source) => source.provider), + ['local'] + ); + assert.deepEqual(state.writes, []); +}); diff --git a/tests/unit/react-snippet-capture.test.mjs b/tests/unit/react-snippet-capture.test.mjs new file mode 100644 index 0000000000..40ac0beb0c --- /dev/null +++ b/tests/unit/react-snippet-capture.test.mjs @@ -0,0 +1,155 @@ +/** @license BSD-3-Clause */ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { loadOfflineModule, storeBoundary, deferred } from './fixtures/offline-module.mjs'; + +function fixture() { + const { writable } = storeBoundary(); + const account = writable({ status: 'ready' }), + localUser = writable(null), + snippetItems = writable([]), + listeners = new Map(); + const saved = [], + appended = []; + let owner = null, + generation = 0, + cleanupFailure = false, + saveGate; + const scope = () => { + const captured = generation; + return { + owner: owner === null ? 'local' : 'account:' + owner, + guard() { + if (captured !== generation) throw new Error('Account changed'); + } + }; + }; + const { api } = loadOfflineModule('apps/web/src/snippets-react/capture-controller.ts', { + modules: { + react: {}, + '../lib/manabi/client': { account, localUser }, + '$app/navigation': { goto: async () => {} }, + '$app/paths': { resolve: (value) => value }, + '../lib/snippets/service': { + scope, + snippetItems, + appendToSnippet: async (id, content, session, selected) => { + selected.guard(); + appended.push({ id, content, session }); + }, + flushSnippets: async () => {} + }, + '../lib/snippets/database': { + recordKey: (owner, id) => owner + '/' + id, + saveDraft: async (value, guard) => { + if (saveGate) await saveGate.promise; + guard(); + saved.push(value); + }, + deleteDraft: async (_key, guard) => { + guard(); + if (cleanupFailure) throw new Error('Storage unavailable'); + } + }, + '../lib/snippets/editor': { + importContent: (text) => ({ + type: 'doc', + content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] + }) + } + }, + globals: { + queueMicrotask, + window: { + addEventListener(name, listener) { + listeners.set(name, listener); + }, + removeEventListener(name, listener) { + if (listeners.get(name) === listener) listeners.delete(name); + } + } + } + }); + const c = api.createCapture({}); + c.controller.prepare(); + c.controller.start(); + return { + c, + saved, + appended, + receive: (text, title = text) => + listeners.get('manabi-capture-snippet')({ detail: { html: text, title, item: text, owner } }), + changeOwner(next) { + owner = next; + generation++; + localUser.set(next ? { id: next } : null); + }, + failCleanup() { + cleanupFailure = true; + }, + delaySave() { + return (saveGate = deferred()); + } + }; +} + +test('React capture durably keeps concurrent and open-dialog selections without replacing the first dialog', async () => { + const f = fixture(); + try { + await Promise.all([f.receive('first'), f.receive('second')]); + assert.equal(f.saved.length, 2); + assert.notEqual(f.saved[0].session, f.saved[1].session); + assert.equal(f.c.document.source.title, 'first'); + assert.equal(f.c.open, true); + assert.match(f.c.status, /1 additional selection saved/); + await f.receive('third'); + assert.equal(f.saved.length, 3); + assert.equal(f.c.document.source.title, 'first'); + assert.match(f.c.status, /2 additional selections saved/); + } finally { + f.c.controller.destroy(); + } +}); + +test('React capture does not invite another append when post-commit draft cleanup fails', async () => { + const f = fixture(); + try { + await f.receive('captured'); + f.failCleanup(); + await f.c.append('destination'); + assert.equal(f.appended.length, 1); + assert.equal(f.c.open, false); + assert.equal(f.c.error, ''); + assert.match(f.c.status, /Added to snippet/); + assert.match(f.c.status, /recoverable/); + } finally { + f.c.controller.destroy(); + } +}); + +test('React capture cannot save an old-account selection after account replacement', async () => { + const f = fixture(), + gate = f.delaySave(); + try { + const pending = f.receive('old account'); + f.changeOwner('new-account'); + gate.resolve(); + await pending; + assert.equal(f.saved.length, 0); + assert.equal(f.c.open, false); + } finally { + f.c.controller.destroy(); + } +}); + +test('React capture preserves an admitted draft but cannot reopen a disposed dialog', async () => { + const f = fixture(), + gate = f.delaySave(); + const pending = f.receive('departing capture', 'a'.repeat(999) + '😀'); + f.c.controller.destroy(); + gate.resolve(); + await pending; + assert.equal(f.saved.length, 1); + assert.equal(f.saved[0].document.source.title, 'a'.repeat(999)); + assert.equal(f.c.open, false); +}); diff --git a/tests/unit/reader-chapter-lifecycle.test.mjs b/tests/unit/reader-chapter-lifecycle.test.mjs index 580c1e807c..47754314ed 100644 --- a/tests/unit/reader-chapter-lifecycle.test.mjs +++ b/tests/unit/reader-chapter-lifecycle.test.mjs @@ -12,7 +12,9 @@ const source = new URL('../../', import.meta.url).pathname; const built = await build({ stdin: { contents: `export {createPaginated} from './apps/web/src/reader-react/paginated-controller'; - export {createContinuous} from './apps/web/src/reader-react/continuous-controller';`, + export {createContinuous} from './apps/web/src/reader-react/continuous-controller'; + export {PageManagerPaginated} from './apps/web/src/lib/components/book-reader/book-reader-paginated/page-manager-paginated'; + export {BehaviorSubject, Subject} from 'rxjs';`, resolveDir: source }, bundle: true, @@ -147,6 +149,7 @@ function fixture(mode, withLanguage = true) { dom, root, controller, + modules: module.exports, events, entered, gate, @@ -300,3 +303,170 @@ for (const mode of ['paginated', 'continuous']) { } }); } + +test('paginated pending locator settles on reader teardown', async () => { + const f = fixture('paginated'); + try { + await until(() => f.controller.currentSpineIndex === 1 && !!f.controller.displayedHtml); + // A different section cannot finish rendering until its DOM is mounted. + const pending = f.controller.revealLocator({ resource: { spineIndex: 0 } }, 'book'); + f.controller.controller.destroy(); + const result = await Promise.race([pending, pause(1000).then(() => 'timeout')]); + assert.equal(result, false, 'teardown must settle the retired navigation'); + } finally { + f.gate.resolve(); + f.close(); + } +}); + +test('newer locator waits for the same in-flight chapter', async () => { + const f = fixture('paginated'); + try { + await until(() => f.controller.currentSpineIndex === 1 && !!f.controller.displayedHtml); + const first = f.controller.revealLocator({ resource: { spineIndex: 0 } }, 'book'); + let secondSettled = false; + const second = f.controller.revealLocator({ resource: { spineIndex: 0 } }, 'book'); + void second.then(() => { + secondSettled = true; + }); + assert.equal(await Promise.race([first, pause(1000).then(() => 'timeout')]), false); + await pause(20); + assert.equal(secondSettled, false, 'the replacement must wait for its section to render'); + f.controller.controller.destroy(); + assert.equal(await Promise.race([second, pause(1000).then(() => 'timeout')]), false); + } finally { + f.gate.resolve(); + f.close(); + } +}); + +test('failed pending chapter settles locator and exposes the error', async () => { + const f = fixture('paginated'); + try { + await until(() => f.controller.currentSpineIndex === 1 && !!f.controller.displayedHtml); + f.language.open = async () => { + throw new Error('Chapter could not be prepared'); + }; + const pending = f.controller.revealLocator({ resource: { spineIndex: 0 } }, 'book'); + await until(() => f.controller.currentSpineIndex === 0 && !!f.controller.displayedHtml); + f.root.innerHTML = f.controller.displayedHtml; + f.controller.onHtmlLoad(); + assert.equal(await Promise.race([pending, pause(1000).then(() => 'timeout')]), false); + assert.equal(f.controller.openingError, 'Chapter could not be prepared'); + } finally { + f.gate.resolve(); + f.close(); + } +}); + +test('paginated direct jumps clear previous physical and translated offsets', async () => { + const f = fixture('paginated'); + try { + await until(() => !!f.controller.concretePageManager); + const scroll = f.dom.window.document.getElementById('scroll'); + Object.defineProperty(scroll, 'scrollWidth', { configurable: true, value: 1200 }); + scroll.scrollTo = ({ left = 0, top = 0 } = {}) => { + scroll.scrollLeft = left; + scroll.scrollTop = top; + }; + scroll.scrollLeft = 300; + f.controller.concretePageManager.scrollTo(840, false); + assert.equal(scroll.scrollLeft, 0, 'translation must not compound the prior native scroll'); + assert.equal(f.root.style.transform, 'translateX(-840px)'); + + f.controller.concretePageManager.scrollTo(0, false); + assert.equal(f.root.style.transform, '', 'direct jumps must retire the old translation'); + } finally { + f.gate.resolve(); + f.close(); + } +}); + +for (const supersede of [false, true]) { + test(`page turn ${supersede ? 'retires when replaced' : 'ignores stale section completion'}`, async () => { + const f = fixture('paginated'); + try { + const { PageManagerPaginated, BehaviorSubject, Subject } = f.modules; + const index = new BehaviorSubject(0); + const position = new BehaviorSubject(0); + const rendered = new Subject(); + const pageChange = new Subject(); + const events = []; + pageChange.subscribe((isUser) => events.push(isUser)); + const scroll = f.dom.window.document.getElementById('scroll'); + Object.defineProperty(scroll, 'scrollWidth', { configurable: true, value: 800 }); + scroll.scrollTo = ({ left = 0, top = 0 } = {}) => { + scroll.scrollLeft = left; + scroll.scrollTop = top; + }; + const sections = [ + f.dom.window.document.createElement('div'), + f.dom.window.document.createElement('div') + ]; + const manager = new PageManagerPaginated( + f.root, + scroll, + sections, + index, + position, + 800, + 600, + 40, + false, + pageChange, + rendered + ); + manager.nextPage(); + assert.equal(index.getValue(), 1); + if (supersede) index.next(0); + rendered.next(0); + assert.deepEqual(events, [], 'unrelated completion must never advance the turn'); + rendered.next(1); + assert.deepEqual(events, supersede ? [] : [true]); + assert.equal(index.observed, false, 'settled turns must release section observation'); + } finally { + f.gate.resolve(); + f.close(); + } + }); +} + +test('page turn releases its section observer on teardown', async () => { + const f = fixture('paginated'); + try { + const { PageManagerPaginated, BehaviorSubject, Subject } = f.modules; + const index = new BehaviorSubject(0); + const position = new BehaviorSubject(0); + const rendered = new Subject(); + const pageChange = new Subject(); + const scroll = f.dom.window.document.getElementById('scroll'); + Object.defineProperty(scroll, 'scrollWidth', { configurable: true, value: 800 }); + const sections = [ + f.dom.window.document.createElement('div'), + f.dom.window.document.createElement('div') + ]; + const manager = new PageManagerPaginated( + f.root, + scroll, + sections, + index, + position, + 800, + 600, + 40, + false, + pageChange, + rendered + ); + manager.nextPage(); + assert.equal(index.observed, true); + rendered.complete(); + assert.equal(index.observed, false); + index.next(0); + manager.nextPage(); + assert.equal(index.getValue(), 0, 'closed readers must reject a new page turn'); + } finally { + f.gate.resolve(); + f.close(); + } +}); diff --git a/tests/unit/snippet-backup-lineage.test.mjs b/tests/unit/snippet-backup-lineage.test.mjs index dc6c61f8be..5480f40fbe 100644 --- a/tests/unit/snippet-backup-lineage.test.mjs +++ b/tests/unit/snippet-backup-lineage.test.mjs @@ -4,6 +4,7 @@ import { Buffer } from 'node:buffer'; import { build } from 'esbuild'; import test from 'node:test'; import { fileURLToPath } from 'node:url'; +import { legacySnippetLinks } from './fixtures/legacy-snippet-links.mjs'; import { canonical, createSnippet, @@ -22,7 +23,7 @@ globalThis[Symbol.for(fixtureKey)] = memory; const result = await build({ stdin: { - contents: `export { exportSnippets, restoreBackup } from './src/lib/snippets/portability.ts';`, + contents: `export { decodeBackup, exportSnippets, restoreBackup } from './src/lib/snippets/portability.ts';`, resolveDir: fileURLToPath(new URL('../../apps/web/', import.meta.url)) }, bundle: true, @@ -90,7 +91,7 @@ const result = await build({ } ] }); -const { exportSnippets, restoreBackup } = await import( +const { decodeBackup, exportSnippets, restoreBackup } = await import( 'data:text/javascript;base64,' + Buffer.from(result.outputFiles[0].text).toString('base64') ); @@ -315,3 +316,88 @@ test('JSON backup refuses to silently drop unresolved conflict branches', async assert.equal(current.conflicts.length, 1); assert.equal(current.conflicts[0].revision, remote.revision); }); + +test('legacy v1 link metadata survives actual backup restore and JSON/HTML export without a new identity', async () => { + reset(); + const legacy = legacySnippetLinks(); + const originalBytes = canonical(legacy) + '\n'; + assert.equal(encodeSnippet(parseSnippet(originalBytes)), originalBytes); + const rawBackup = backup(legacy); + assert.equal(await restoreBackup(rawBackup, selected), 1); + const restored = memory.records.get(key(legacy.id)); + assert.deepEqual(restored.document, legacy); + assert.equal(encodeSnippet(restored.document), originalBytes); + assert.deepEqual(restored.locations, []); + + // Keep the real download/export functions; substitute only browser I/O. + const downloads = []; + const blobs = new Map(); + const revocations = []; + const originalDocument = Object.getOwnPropertyDescriptor(globalThis, 'document'); + const originalSetTimeout = globalThis.setTimeout; + const originalCreateURL = URL.createObjectURL; + const originalRevokeURL = URL.revokeObjectURL; + let urlSequence = 0; + try { + URL.createObjectURL = (blob) => { + const url = 'blob:legacy-snippet-export-' + ++urlSequence; + blobs.set(url, blob); + return url; + }; + URL.revokeObjectURL = (url) => blobs.delete(url); + globalThis.setTimeout = (callback, delay, ...args) => { + if (delay === 60000) { + revocations.push(() => callback(...args)); + return 0; + } + return originalSetTimeout(callback, delay, ...args); + }; + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { + createElement(tag) { + assert.equal(tag, 'a'); + return { + click() { + downloads.push({ name: this.download, blob: blobs.get(this.href) }); + } + }; + } + } + }); + + await exportSnippets([legacy.id], selected, 'json'); + assert.equal(await downloads[0].blob.text(), originalBytes); + assert.equal(downloads[0].name, legacy.title.text + ' — ' + legacy.id + '.manabi-snippet.json'); + + await exportSnippets([legacy.id], selected, 'html'); + const html = await downloads[1].blob.text(); + const anchors = [...html.matchAll(/]*)>/g)].map((match) => match[1]); + assert.equal(anchors.length, 7); + assert.match(anchors[0], /target="_self"/); + assert.match(anchors[0], /rel="external"/); + assert.match(anchors[1], /rel=""/); + for (const anchor of anchors.slice(2)) { + assert.match(anchor, /target="_blank"/); + const rel = /rel="([^"]*)"/.exec(anchor)[1].toLowerCase().split(/\s+/); + assert.ok(rel.includes('noopener') && rel.includes('noreferrer')); + assert.ok(!rel.includes('opener')); + } + + const second = createSnippet(plainContent('Second backup document')); + memory.records.set(key(second.id), record(second)); + await exportSnippets([legacy.id, second.id], selected, 'json'); + const exportedBackup = decodeBackup(await downloads[2].blob.text()); + const exportedLegacy = exportedBackup.items.find((item) => item.id === legacy.id); + assert.equal(encodeSnippet(exportedLegacy), originalBytes); + assert.deepEqual(memory.records.get(key(legacy.id)), restored); + assert.equal(backup(legacy), rawBackup); + } finally { + for (const revoke of revocations) revoke(); + globalThis.setTimeout = originalSetTimeout; + URL.createObjectURL = originalCreateURL; + URL.revokeObjectURL = originalRevokeURL; + if (originalDocument) Object.defineProperty(globalThis, 'document', originalDocument); + else delete globalThis.document; + } +}); diff --git a/tests/unit/snippet-local-storage-recovery.test.mjs b/tests/unit/snippet-local-storage-recovery.test.mjs index 2b012eb619..da914ba20d 100644 --- a/tests/unit/snippet-local-storage-recovery.test.mjs +++ b/tests/unit/snippet-local-storage-recovery.test.mjs @@ -50,6 +50,22 @@ globalThis[Symbol.for(fixtureKey)] = { ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength); return createHash('sha256').update(bytes).digest('hex'); + }, + withLocalLibraryConnection: async (admitted, write, work) => { + await fixture.beforeConnect?.(); + const current = await fixture.db.get('localLibraries', admitted.id); + if ( + !current || + !(current.handle === admitted.handle || (await current.handle.isSameEntry(admitted.handle))) + ) + throw new globalThis[Symbol.for(fixtureKey)].classIntegrationError('not_found'); + if ( + (write && !current.writable) || + (await current.handle.queryPermission({ mode: write ? 'readwrite' : 'read' })) !== 'granted' + ) + throw new globalThis[Symbol.for(fixtureKey)].classIntegrationError('permission_required'); + fixture.authorityCalls.push({ id: admitted.id, write }); + return work(current); } }; @@ -61,7 +77,10 @@ const mock = { }, '../manabi/persistence': { integrationDB: 'integrationDB', exclusive: 'exclusive' }, '../library/file-operations': { openDirectory: 'openDirectory', safePath: 'safePath' }, - '../manabi/sources': { sha256: 'sha256' }, + '../manabi/sources': { + sha256: 'sha256', + withLocalLibraryConnection: 'withLocalLibraryConnection' + }, '../library/catalog': { librarySource: 'unused' }, '../webdav/source': { davSource: 'unused', withDavSourceLock: 'unused' }, '../webdav/client': { @@ -108,7 +127,7 @@ const bundled = await build({ } ] }); -const { writeDocument } = await import( +const { capability, makeFolder, readDocument, removeDocument, writeDocument } = await import( `data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}` ); @@ -120,7 +139,9 @@ async function setup() { src = source(); fixture = { fs, - db: integrationDatabase({ id: src.id, name: src.name, handle: fs.root, writable: true }) + db: integrationDatabase({ id: src.id, name: src.name, handle: fs.root, writable: true }), + authorityCalls: [], + beforeConnect: undefined }; return { fs, src }; } @@ -187,3 +208,124 @@ test('successful retry writes the exact portable document bytes', async () => { await writeDocument({ source: src, parent: '', name }, doc, undefined, guard); assert.equal(await fs.read(name), encodeSnippet(doc)); }); + +test('local snippet writes reject a replaced source before touching the stale handle', async () => { + const { fs, src } = await setup(), + doc = createSnippet(plainContent('replacement must not retarget writes')), + replacement = filesystem(); + fixture.beforeConnect = async () => { + const current = fixture.db.tables.get('localLibraries').get(src.id); + current.handle = replacement.root; + fixture.beforeConnect = undefined; + }; + await assert.rejects( + () => writeDocument({ source: src, parent: '' }, doc, undefined, guard), + (error) => error?.code === 'not_found' + ); + assert.deepEqual(fs.events, []); + assert.deepEqual(replacement.events, []); + assert.deepEqual(fixture.authorityCalls, []); +}); + +test('local snippet writes reject disconnect before physical admission', async () => { + const { fs, src } = await setup(), + doc = createSnippet(plainContent('disconnect must fence writes')); + fixture.beforeConnect = async () => { + fixture.db.tables.get('localLibraries').delete(src.id); + fixture.beforeConnect = undefined; + }; + await assert.rejects( + () => writeDocument({ source: src, parent: '' }, doc, undefined, guard), + (error) => error?.code === 'not_found' + ); + assert.deepEqual(fs.events, []); + assert.deepEqual(fixture.authorityCalls, []); +}); + +test('local snippet writes require durable write consent from the current source row', async () => { + const { fs, src } = await setup(), + doc = createSnippet(plainContent('consent must be current')); + fixture.beforeConnect = async () => { + fixture.db.tables.get('localLibraries').get(src.id).writable = false; + fixture.beforeConnect = undefined; + }; + await assert.rejects( + () => writeDocument({ source: src, parent: '' }, doc, undefined, guard), + (error) => error?.code === 'permission_required' + ); + assert.deepEqual(fs.events, []); + assert.deepEqual(fixture.authorityCalls, []); +}); + +test('normal local snippet create enters shared source authority as a write operation', async () => { + const { src } = await setup(), + doc = createSnippet(plainContent('shared source authority')); + await writeDocument({ source: src, parent: '' }, doc, undefined, guard); + assert.deepEqual(fixture.authorityCalls, [{ id: src.id, write: true }]); +}); + +test('local read, capability, folder creation and remove all enter shared source authority', async () => { + const { fs, src } = await setup(), + doc = createSnippet(plainContent('all local operations are fenced')), + location = await writeDocument({ source: src, parent: '' }, doc, undefined, guard); + fixture.authorityCalls.length = 0; + + const loaded = await readDocument(src, location.fileId, guard); + assert.equal(canonical(loaded.document), canonical(doc)); + assert.deepEqual(fixture.authorityCalls, [{ id: src.id, write: false }]); + + fixture.authorityCalls.length = 0; + assert.deepEqual(await capability(src, guard), { write: true }); + assert.deepEqual(fixture.authorityCalls, [{ id: src.id, write: false }]); + + fixture.authorityCalls.length = 0; + assert.equal(await makeFolder({ source: src, parent: '' }, 'Child', guard), 'Child'); + assert.deepEqual(fixture.authorityCalls, [{ id: src.id, write: true }]); + + fixture.authorityCalls.length = 0; + await removeDocument(location, doc, guard); + assert.deepEqual(fixture.authorityCalls, [{ id: src.id, write: true }]); + await assert.rejects(fs.read(location.fileId), { name: 'NotFoundError' }); +}); + +test('write permission revoked before commit aborts without publishing new bytes', async () => { + const { fs, src } = await setup(), + original = createSnippet(plainContent('original')), + first = await writeDocument({ source: src, parent: '' }, original, undefined, guard), + edited = { + ...original, + revision: globalThis.crypto.randomUUID(), + parents: [original.revision], + modifiedAt: original.modifiedAt + 1, + content: plainContent('new bytes must not commit') + }; + fs.hooks.write = async () => { + fs.root.queryPermission = async () => 'denied'; + }; + await assert.rejects( + () => + writeDocument({ source: src, parent: first.parent, name: first.name }, edited, first, guard), + (error) => error?.code === 'permission_required' + ); + fs.hooks.write = undefined; + fs.root.queryPermission = async () => 'granted'; + assert.equal(canonical(parseSnippet(await fs.read(first.fileId))), canonical(original)); +}); + +test('remove permission revoked before physical deletion preserves the document', async () => { + const { fs, src } = await setup(), + doc = createSnippet(plainContent('keep when permission disappears')), + location = await writeDocument({ source: src, parent: '' }, doc, undefined, guard); + let calls = 0; + fs.root.queryPermission = async ({ mode } = {}) => { + calls++; + // Shared authority admission succeeds; the explicit pre-delete check fails. + return mode === 'readwrite' && calls > 1 ? 'denied' : 'granted'; + }; + await assert.rejects( + () => removeDocument(location, doc, guard), + (error) => error?.code === 'permission_required' + ); + fs.root.queryPermission = async () => 'granted'; + assert.equal(canonical(parseSnippet(await fs.read(location.fileId))), canonical(doc)); +}); diff --git a/tests/unit/snippet-markdown-safety.test.mjs b/tests/unit/snippet-markdown-safety.test.mjs new file mode 100644 index 0000000000..3bf63ef678 --- /dev/null +++ b/tests/unit/snippet-markdown-safety.test.mjs @@ -0,0 +1,406 @@ +/** @license BSD-3-Clause */ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import test, { after } from 'node:test'; +import { JSDOM } from 'jsdom'; +const dom = new JSDOM('', { pretendToBeVisual: true }); +const browserGlobals = { + window: dom.window, + document: dom.window.document, + navigator: dom.window.navigator, + Element: dom.window.Element, + HTMLElement: dom.window.HTMLElement, + Node: dom.window.Node, + MutationObserver: dom.window.MutationObserver, + getComputedStyle: dom.window.getComputedStyle.bind(dom.window), + requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), + cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window) +}; +const globals = new Map( + Object.keys(browserGlobals).map((name) => [ + name, + Object.getOwnPropertyDescriptor(globalThis, name) + ]) +); +for (const [name, value] of Object.entries(browserGlobals)) + Object.defineProperty(globalThis, name, { configurable: true, value }); +after(() => { + dom.window.close(); + for (const [name, descriptor] of globals) { + if (descriptor) Object.defineProperty(globalThis, name, descriptor); + else delete globalThis[name]; + } +}); +const { + createEditor, + exportMarkdown, + importContent, + markdownHTML, + renderContent, + requiresHTMLMarkdown +} = await import('../../apps/web/src/lib/snippets/editor.ts'); +import { + canonical, + editSnippet, + encodeSnippet, + parseSnippet, + validateContent +} from '../../apps/web/src/lib/snippets/document.ts'; +import { readerHTML } from '../../apps/web/src/lib/snippets/presentation.ts'; +import { legacySnippetLinks } from './fixtures/legacy-snippet-links.mjs'; + +function text(html) { + return html + .replace(/<[^>]+>/g, '') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .trim(); +} + +test('Markdown import keeps ordinary alphabetic sentence prefixes as prose', () => { + for (const value of ['Hi. there', 'Ok. Next step.', 'Ex) aside', 'iv. not a list']) { + const html = markdownHTML(value); + assert.equal(text(html), value, value); + assert.match(html, /^

/, value); + assert.doesNotMatch(html, / { + const html = markdownHTML('1. one\n2. two'); + assert.match(html, /

    /); + assert.match(html, /
  1. one<\/li>/); + assert.match(html, /
  2. two<\/li>/); +}); + +test('Markdown import preserves a valid zero-start ordered list', () => { + const html = markdownHTML('0. zero\n1. one'); + assert.match(html, /
      /); + assert.match(html, /
    1. zero<\/li>/); + assert.match(html, /
    2. one<\/li>/); + assert.doesNotMatch(html, /
        /); +}); + +test('Markdown parsing stays stable after repeated editor extension construction', async () => { + const before = markdownHTML('Hi. there\n\n1. one\n2. two'); + const { extensions } = await import('../../apps/web/src/lib/snippets/editor.ts'); + for (let n = 0; n < 8; n++) extensions(); + const after = markdownHTML('Hi. there\n\n1. one\n2. two'); + assert.equal(after, before); +}); + +test('repeated Markdown serialization stays isolated and deterministic', () => { + const content = { + type: 'doc', + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [ + { type: 'text', text: 'One ' }, + { type: 'text', text: 'bold', marks: [{ type: 'bold' }] }, + { type: 'text', text: ' sentence.' } + ] + } + ] + }; + const first = exportMarkdown(content); + for (let n = 0; n < 12; n++) assert.equal(exportMarkdown(content), first); + assert.match(first, /One \*\*bold\*\* sentence\./); +}); + +test('ruby and zero-start lists select lossless HTML Markdown export', () => { + assert.equal( + requiresHTMLMarkdown({ + type: 'doc', + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [ + { + type: 'text', + text: '東京', + marks: [{ type: 'rubyText', attrs: { rt: 'とうきょう' } }] + } + ] + } + ] + }), + true + ); + assert.equal( + requiresHTMLMarkdown({ + type: 'doc', + content: [ + { + type: 'orderedList', + attrs: { id: randomUUID(), start: 0 }, + content: [] + } + ] + }), + true + ); +}); + +test('underline and non-CommonMark list/link semantics select lossless HTML export', () => { + const paragraph = (marks) => ({ + type: 'doc', + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [{ type: 'text', text: 'styled', marks }] + } + ] + }); + assert.equal(requiresHTMLMarkdown(paragraph([{ type: 'underline' }])), true); + assert.equal( + requiresHTMLMarkdown( + paragraph([ + { + type: 'link', + attrs: { + href: 'https://example.com/', + target: '_self', + rel: 'noopener', + class: null, + title: null + } + } + ]) + ), + true + ); + assert.equal( + requiresHTMLMarkdown({ + type: 'doc', + content: [ + { + type: 'orderedList', + attrs: { id: randomUUID(), start: 1, type: 'a' }, + content: [ + { + type: 'listItem', + attrs: { id: randomUUID() }, + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [{ type: 'text', text: 'alpha' }] + } + ] + } + ] + } + ] + }), + true + ); + assert.equal(requiresHTMLMarkdown(paragraph([{ type: 'bold' }])), false); +}); + +test('lossless fallback emits HTML that preserves underline and list marker type', () => { + const underlined = { + type: 'doc', + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [{ type: 'text', text: 'underlined', marks: [{ type: 'underline' }] }] + } + ] + }; + assert.match(exportMarkdown(underlined), /underlined<\/u>/); + + const alphaList = { + type: 'doc', + content: [ + { + type: 'orderedList', + attrs: { id: randomUUID(), start: 1, type: 'a' }, + content: [ + { + type: 'listItem', + attrs: { id: randomUUID() }, + content: [ + { + type: 'paragraph', + attrs: { id: randomUUID() }, + content: [{ type: 'text', text: 'alpha' }] + } + ] + } + ] + } + ] + }; + const markdown = exportMarkdown(alphaList); + assert.match(markdown, /]*type="a"/); + 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'); +}); + +function assertLegacyLinkDOM(container) { + const links = [...container.querySelectorAll('a')]; + assert.equal(links.length, 7); + assert.equal(links[0].getAttribute('target'), '_self'); + assert.equal(links[0].getAttribute('rel'), 'external'); + assert.equal(links[1].getAttribute('target'), '_self'); + assert.equal(links[1].getAttribute('rel'), ''); + for (const link of links.slice(2)) { + const rel = link.getAttribute('rel').toLowerCase().split(/\s+/); + assert.equal(link.getAttribute('target'), '_blank'); + assert.ok(rel.includes('noopener')); + assert.ok(rel.includes('noreferrer')); + assert.ok(!rel.includes('opener')); + } +} + +test('legacy v1 links remain byte-stable while reader, HTML and Markdown displays are safe', () => { + const legacy = legacySnippetLinks(); + const bytes = canonical(legacy) + '\n'; + const saved = parseSnippet(bytes); + for (const render of [readerHTML, renderContent, exportMarkdown]) { + const container = globalThis.document.createElement('div'); + container.innerHTML = render(saved.content); + assertLegacyLinkDOM(container); + assert.equal(encodeSnippet(saved), bytes); + assert.deepEqual(saved, legacy); + } + const roundTrip = importContent(exportMarkdown(saved.content), 'markdown'); + const selfLinks = roundTrip.content.slice(0, 2).map((block) => block.content[0].marks[0].attrs); + assert.equal(selfLinks[0].target, '_self'); + assert.equal(selfLinks[0].rel, 'external'); + assert.equal(selfLinks[1].target, '_self'); + assert.equal(selfLinks[1].rel, ''); +}); + +test('editor DOM hardens legacy and later link marks without mutating the saved revision', () => { + const saved = legacySnippetLinks(); + const bytes = canonical(saved) + '\n'; + const host = globalThis.document.createElement('div'); + globalThis.document.body.append(host); + const updates = []; + const editor = createEditor(host, saved.content, (content) => updates.push(content)); + try { + assertLegacyLinkDOM(host); + assert.equal(updates.length, 0, 'opening an editor cannot manufacture a save'); + assert.deepEqual( + editor.getJSON().content.map((block) => block.content[0].marks[0].attrs.rel), + saved.content.content.map((block) => block.content[0].marks[0].attrs.rel), + 'DOM safety must not rewrite the working model metadata' + ); + // Exercise the actual link renderer again after creation, rather than only + // proving that the initial content was pre-sanitized. + editor.commands.setContent(saved.content, { emitUpdate: false }); + assertLegacyLinkDOM(host); + const edited = structuredClone(saved.content); + edited.content[0].content[0].text += ' edited'; + editor.commands.setContent(edited, { emitUpdate: true }); + assert.ok(updates.length > 0); + const next = editSnippet(saved, updates.at(-1), saved.title.text); + assert.equal(next.id, saved.id); + assert.notEqual(next.revision, saved.revision); + assert.ok(next.parents.includes(saved.revision)); + assert.equal(encodeSnippet(saved), bytes); + assertLegacyLinkDOM(host); + } finally { + editor.destroy(); + host.remove(); + } +}); + +test('v1 rel remains bounded metadata and URL, class and schema guards still reject invalid content', () => { + const legacy = legacySnippetLinks(); + assert.doesNotThrow(() => validateContent(legacy.content)); + for (const attrs of [ + { rel: 'x'.repeat(121) }, + { rel: 12 }, + { rel: '\u0000' }, + { href: 'javascript:alert(1)' }, + { class: 'foreign-class' }, + { target: '_top' }, + { unknownAttribute: 'unexpected' } + ]) { + const invalid = structuredClone(legacy.content); + Object.assign(invalid.content[0].content[0].marks[0].attrs, attrs); + assert.throws(() => validateContent(invalid), JSON.stringify(attrs)); + } +}); + +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); + assert.match(html, /
        Hi\. there\n0\. zero\n<\/code><\/pre>/);
        +  assert.doesNotMatch(html, / {
        +  const valid = {
        +    type: 'doc',
        +    content: [
        +      {
        +        type: 'orderedList',
        +        attrs: { id: randomUUID(), start: 0 },
        +        content: [
        +          {
        +            type: 'listItem',
        +            attrs: { id: randomUUID() },
        +            content: [
        +              {
        +                type: 'paragraph',
        +                attrs: { id: randomUUID() },
        +                content: [{ type: 'text', text: 'zero' }]
        +              }
        +            ]
        +          }
        +        ]
        +      }
        +    ]
        +  };
        +  assert.doesNotThrow(() => validateContent(valid));
        +  const invalid = globalThis.structuredClone(valid);
        +  invalid.content[0].attrs.start = -1;
        +  assert.throws(() => validateContent(invalid));
        +});
        diff --git a/tests/unit/snippet-react-capture.test.mjs b/tests/unit/snippet-react-capture.test.mjs
        new file mode 100644
        index 0000000000..540e52405d
        --- /dev/null
        +++ b/tests/unit/snippet-react-capture.test.mjs
        @@ -0,0 +1,231 @@
        +/** @license BSD-3-Clause */
        +import assert from 'node:assert/strict';
        +import { randomUUID } from 'node:crypto';
        +import { readFileSync } from 'node:fs';
        +import { createRequire } from 'node:module';
        +import { compileFunction } from 'node:vm';
        +import test from 'node:test';
        +
        +const require = createRequire(import.meta.url);
        +const ts = require('typescript');
        +const sourceRoot = new URL('../../apps/web/src/', import.meta.url);
        +const deferred = () => {
        +  let resolve, reject;
        +  const promise = new Promise((yes, no) => {
        +    resolve = yes;
        +    reject = no;
        +  });
        +  return { promise, resolve, reject };
        +};
        +const settle = async () => {
        +  for (let i = 0; i < 8; i++) await Promise.resolve();
        +};
        +function store(value) {
        +  const listeners = new Set();
        +  return {
        +    get value() {
        +      return value;
        +    },
        +    subscribe(fn) {
        +      listeners.add(fn);
        +      fn(value);
        +      return () => listeners.delete(fn);
        +    },
        +    set(next) {
        +      value = next;
        +      for (const fn of listeners) fn(value);
        +    }
        +  };
        +}
        +function load(relative, imports = {}, window = {}) {
        +  const url = new URL(relative, sourceRoot);
        +  const compiled = ts.transpileModule(readFileSync(url, 'utf8'), {
        +    fileName: url.pathname,
        +    compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
        +    reportDiagnostics: true
        +  });
        +  assert.equal(compiled.diagnostics?.length ?? 0, 0);
        +  const module = { exports: {} };
        +  compileFunction(compiled.outputText, ['require', 'module', 'exports', 'window', 'crypto'])(
        +    (name) => {
        +      assert.ok(Object.hasOwn(imports, name), 'Unexpected dependency: ' + name);
        +      return imports[name];
        +    },
        +    module,
        +    module.exports,
        +    window,
        +    { randomUUID }
        +  );
        +  return module.exports;
        +}
        +
        +function fixture() {
        +  let user = { id: 'alice' },
        +    authGeneration = 0;
        +  const account = store({ status: 'ready' }),
        +    localUser = store(user);
        +  class IntegrationError extends Error {
        +    constructor(code) {
        +      super(code);
        +      this.code = code;
        +    }
        +  }
        +  const client = {
        +    account,
        +    localUser,
        +    localProfileUser: () => user,
        +    currentUser: () => user,
        +    accountScope: () => ({ generation: authGeneration }),
        +    IntegrationError
        +  };
        +  // Use shipping account-generation admission and document validation, not a no-op guard.
        +  const admission = load('lib/snippets/scope.ts', {
        +    '$lib/state/store': { get: (source) => source.value },
        +    '../manabi/client': client
        +  });
        +  const document = load('lib/snippets/document.ts');
        +  const lifecycle = load('reader-react/controller.ts', { react: {} });
        +  const listeners = new Map(),
        +    drafts = [],
        +    appends = [],
        +    flushes = [];
        +  const behavior = {};
        +  const window = {
        +    addEventListener(name, callback) {
        +      listeners.set(name, callback);
        +    },
        +    removeEventListener(name, callback) {
        +      if (listeners.get(name) === callback) listeners.delete(name);
        +    }
        +  };
        +  const service = {
        +    scope: admission.scope,
        +    snippetItems: store([]),
        +    async appendToSnippet(id, content, operation, selected) {
        +      selected.guard();
        +      await behavior.append?.();
        +      selected.guard();
        +      appends.push({ id, content, operation, owner: selected.owner });
        +    },
        +    async flushSnippets(selected) {
        +      selected.guard();
        +      flushes.push(selected.owner);
        +    }
        +  };
        +  const database = {
        +    recordKey: (owner, session) => owner + ':' + session,
        +    async saveDraft(record, guard) {
        +      guard();
        +      await behavior.save?.(record);
        +      guard();
        +      drafts.push(structuredClone(record));
        +    },
        +    async deleteDraft(key, guard) {
        +      guard();
        +      await behavior.remove?.(key);
        +      guard();
        +      const index = drafts.findIndex((record) => record.key === key);
        +      if (index >= 0) drafts.splice(index, 1);
        +    }
        +  };
        +  const { createCapture } = load(
        +    'snippets-react/capture-controller.ts',
        +    {
        +      '../lib/manabi/client': client,
        +      '$app/navigation': { goto: async () => behavior.goto?.() },
        +      '$app/paths': { resolve: (value) => value },
        +      '../lib/snippets/service': service,
        +      '../lib/snippets/database': database,
        +      '../lib/snippets/document': document,
        +      '../lib/snippets/editor': { importContent: (text) => document.plainContent(text) },
        +      '../reader-react/controller': lifecycle
        +    },
        +    window
        +  );
        +  const c = createCapture({});
        +  c.controller.start();
        +  return {
        +    c,
        +    behavior,
        +    drafts,
        +    appends,
        +    flushes,
        +    capture(text, details = {}) {
        +      return listeners.get('manabi-capture-snippet')({
        +        detail: {
        +          html: text,
        +          title: 'Source',
        +          item: 'book',
        +          owner: user?.id ?? null,
        +          ...details
        +        }
        +      });
        +    },
        +    switchAccount(id) {
        +      user = id ? { id } : null;
        +      authGeneration++;
        +      localUser.set(user);
        +    },
        +    retireTransport() {
        +      authGeneration++;
        +      account.set({ status: 'ready' });
        +    }
        +  };
        +}
        +
        +test('React old-account capture completion cannot replace a successor account dialog', async () => {
        +  const f = fixture(),
        +    gate = deferred();
        +  f.behavior.save = (record) => (record.owner === 'account:alice' ? gate.promise : undefined);
        +  const old = f.capture('private Alice text');
        +  await settle();
        +  f.switchAccount('bob');
        +  assert.equal(f.c.busy, false);
        +  await f.capture('Bob text');
        +  gate.resolve();
        +  await old;
        +  assert.equal(f.c.document.source.quote, 'Bob text');
        +  assert.equal(f.c.open, true);
        +  assert.equal(f.c.busy, false);
        +  assert.equal(f.c.error, '');
        +  assert.deepEqual(
        +    f.drafts.map((record) => record.owner),
        +    ['account:bob']
        +  );
        +  f.c.controller.destroy();
        +});
        +test('React old-account append rejection cannot publish an error into a new capture', async () => {
        +  const f = fixture(),
        +    gate = deferred();
        +  await f.capture('Alice text');
        +  f.behavior.append = () => gate.promise;
        +  const old = f.c.append('Alice destination');
        +  f.switchAccount('bob');
        +  await f.capture('Bob text');
        +  gate.reject(new Error('Alice destination is no longer available'));
        +  await old;
        +  assert.equal(f.c.document.source.quote, 'Bob text');
        +  assert.equal(f.c.open, true);
        +  assert.equal(f.c.error, '');
        +  assert.equal(f.c.busy, false);
        +  assert.equal(f.appends.length, 0);
        +  f.c.controller.destroy();
        +});
        +
        +test('React transport replacement retires a busy capture even when the local account stays the same', async () => {
        +  const f = fixture(),
        +    gate = deferred();
        +  let first = true;
        +  f.behavior.save = () => (first ? ((first = false), gate.promise) : undefined);
        +  const old = f.capture('retired transport');
        +  await settle();
        +  f.retireTransport();
        +  assert.equal(f.c.busy, false);
        +  await f.capture('current transport');
        +  gate.resolve();
        +  await old;
        +  assert.equal(f.c.document.source.quote, 'current transport');
        +  assert.equal(f.c.error, '');
        +  assert.equal(f.drafts.length, 1);
        +  f.c.controller.destroy();
        +});
        diff --git a/tests/unit/statistics-react-controller.test.mjs b/tests/unit/statistics-react-controller.test.mjs
        index b404ddc2c0..45438072b4 100644
        --- a/tests/unit/statistics-react-controller.test.mjs
        +++ b/tests/unit/statistics-react-controller.test.mjs
        @@ -373,3 +373,63 @@ test('React selection export refuses ambiguous same-title identities and restore
           assert.equal(f.types.statisticsActionInProgress$.value, false);
           c.controller.destroy();
         });
        +
        +test('React summary measures fixed pixel gaps at enlarged text sizes', async () => {
        +  const f = fixture();
        +  f.mock['$lib/functions/utils'].convertRemToPixels = (_window, value) => value * 32;
        +  f.mock['$lib/functions/utils'].getFullHeight = (_window, element) => element.height;
        +  const c = f.start('statistics-summary', {
        +    aggregratedStatistics: Array.from({ length: 12 }, (_, i) => f.row('Title ' + i, '2024-02-28')),
        +    statisticsDateRangeLabel: '2024'
        +  });
        +  c.renderFullStatisticsSummaryTable = true;
        +  c.statisticsSummaryTableContainerElm = { height: 500 };
        +  c.statisticsSummaryButtonContainer = { height: 44 };
        +  c.updateRowsPerPage(false);
        +  await f.frame();
        +  assert.equal(c.rowsPerStatisticsSummaryPage, 4);
        +  assert.equal(c.statisticsSummaryMaxPages, 3);
        +  c.controller.destroy();
        +  await f.frame();
        +});
        +
        +for (const movedFocus of [false, true]) {
        +  test(
        +    'React summary pager ' +
        +      (movedFocus ? 'preserves newer focus' : 'moves focus off its disabled end control'),
        +    async () => {
        +      const document = { activeElement: null, body: {} };
        +      const f = fixture({ document });
        +      const c = f.start('statistics-summary', {
        +        aggregratedStatistics: [f.row('One', '2024-02-28'), f.row('Two', '2024-02-29')],
        +        statisticsDateRangeLabel: '2024'
        +      });
        +      await f.frame();
        +      const previous = {
        +        isConnected: true,
        +        disabled: false,
        +        focus() {
        +          document.activeElement = this;
        +        }
        +      };
        +      const next = {
        +        isConnected: true,
        +        get disabled() {
        +          return c.currentStatisticsSummaryPage === c.statisticsSummaryMaxPages;
        +        }
        +      };
        +      c.previousSummaryPage = previous;
        +      c.nextSummaryPage = next;
        +      document.activeElement = next;
        +      const pending = c.pageSummary(1);
        +      const newer = {};
        +      if (movedFocus) document.activeElement = newer;
        +      await f.frame();
        +      await pending;
        +      assert.equal(c.currentStatisticsSummaryPage, 2);
        +      assert.equal(document.activeElement, movedFocus ? newer : previous);
        +      c.controller.destroy();
        +      await f.frame();
        +    }
        +  );
        +}
        diff --git a/tools/appearance/lint.mjs b/tools/appearance/lint.mjs
        index 715bc3889a..b58117208f 100644
        --- a/tools/appearance/lint.mjs
        +++ b/tools/appearance/lint.mjs
        @@ -66,6 +66,8 @@ const files = [
           'apps/web/src/lib/components/book-reader/reader-appearance.svelte',
           'apps/web/src/lib/components/ui/sheet/sheet-content.svelte',
           'apps/web/src/lib/components/statistics/statistics-header.svelte',
        +  'apps/web/src/lib/components/statistics/statistics-summary/statistics-summary.svelte',
        +  'apps/web/src/lib/components/statistics/statistics-summary/statistics-summary-header.svelte',
           'apps/web/src/lib/components/popover/popover.svelte',
           'apps/web/src/lib/components/dialog-template.svelte',
           'apps/web/src/lib/components/app-icon.svelte',