Commit graph

17 commits

Author SHA1 Message Date
Huang Xin
045beb4d1a
feat(crosspoint): sync CrossPoint 2.0 clippings with Readest highlights (#7317)
* feat(crosspoint): sync CrossPoint 2.0 clippings with Readest highlights

CrossPoint 2.0's Sync Clippings first probes
{KOSync server}/api/v1/clippings/{document} for sync_version 2, and stops
the whole sync, progress included, when the probe fails. Readest's KOSync
endpoint had no such route, so a reader signed in with the Readest plugin
showed "Could Not Sync Clippings" and stopped syncing progress once the
setting was on.

- /api/crosspoint/api/v1/clippings/{document} serves the clippings API
  (sync_version 2, cursor paging, tombstones). A clipping is a book_notes
  highlight whose new `crosspoint` column holds the reader's anchor (spine
  plus a code-point range), the way xpointer0/xpointer1 hold KOReader's.
  Only items the firmware can decode are sent, up to the 256 an X3/X4
  holds per book. A rewritten copy (Optimize EPUB) syncs as the library
  book it is linked to, and its first clippings move to that book when
  its progress upload links it.
- Readest apps turn a clipping into a CFI when they open the book, and
  give each EPUB highlight a CrossPoint anchor when they push it (tried
  once a session). Moving a highlight's range drops the old anchors.
- Migration 033 adds book_notes.crosspoint (nullable jsonb). Apply it
  before the web deploy.
- Plugin README: CrossPoint 2.0 names and requirements, and highlights.

Fails without the change: useNotesSync-crosspoint (4 of 5, e.g. "turns a
clipping a reader synced into a highlight at its CFI"), transform "carries
the anchor in the crosspoint column, both ways", useAnnotationEditor "a
moved range drops the KOReader and CrossPoint anchors of the old one"
(expected the old xpointer to be undefined), and the route test "moves a
rewritten copy's clippings to the library book it gets linked to". The
clippings route tests can't run without the route.

Verified on a real X4 (CrossPoint 2.0.0) with Sync Clippings on: the
probe and uploads answer 200, a reader clipping shows in Readest on its
words, a Readest highlight shows on the X4, and deletions go both ways.

Reported by itsthisjustin (CrossPoint).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(crosspoint): sync a document a reader names by its file name

A reader set to match documents by file name (CrossPoint's default, and
the alternate lookup of its Smart Sync) sends md5 of the book's file
name, as KOReader does. Since #7237 Readest keeps the name a book was
imported under (books.original_filename), and #7253 digests it the same
way in Readest's own KOSync client.

Progress, clippings and reading sessions now resolve such a document to
the library book imported under that name, link it on first sight like a
rewritten copy, and move clippings saved under the name's id to the book.
When two books were imported under one name, the most recently read one
wins. A document that is a book's own id is never looked up by name, and
an NFD spelling of the name does not match.

Fails without the change: 5 of the 6 tests in "a document named by its
file name", e.g. "syncs it as the library book imported under that name,
linked on first sight" (the link write and the library book's queries
never happen). The sixth, a name no book has, passed before too.

Not run on a device: the books in the test library were imported before
#7237 and have no original_filename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(crosspoint): page the file-name lookup, and retry a failed clipping move

From CodeRabbit's review of this PR:

- The lookup of the book imported under a file name read the user's books
  in one request, and PostgREST answers at most 1000 rows (db-max-rows),
  so a match past them was never found. It now pages through them by
  book_hash.
- A copy was linked before its clippings moved to the library book, and a
  failed move only logged a warning. Every later request followed the
  link, so those clippings stayed under the copy's id for good. They now
  move first, and a failed move fails that sync, leaving the copy
  unlinked so the next sync tries again.

Fails without the change: "finds the book past the first 1000 imported
under a name" (no link written: expected [ …(20) ] to deeply equal
ArrayContaining{…}), and "links a copy only once its clippings have
moved, so a failed move is tried again" (expected 200 to be 500).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:22:58 +01:00
Huang Xin
d5e10369b4
fix(library): preserve original filenames and use PDF filename titles (#7237)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_web_browser (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* fix(library): preserve import filenames and use PDF filename titles

Save each imported file's original basename, including its extension, on
the local Book record. Use the filename stem as the PDF display title while
preserving embedded metadata and the sourceTitle used to locate managed
files. Retain the original filename when re-importing a managed copy.

Regression evidence: before the fix, import-metahash and
import-docx-conversion had 13 assertion failures for missing
originalFilename fields and PDF titles still reading PowerPoint
Presentation. Both suites pass with the change.

Verified:
- Full unit suite: 1220 files passed, 4 skipped; 14648 tests passed,
  16 skipped (before updating to origin/main a2dd013a4).
- On origin/main a2dd013a4: six import suites plus useProgressSync,
  7 files / 124 tests passed.
- pnpm lint passed; formatting and git diff --check passed.
- Real web app: imported Device_Manual_V2.1.pdf with embedded title
  PowerPoint Presentation; filename title and originalFilename persisted
  after reload.
- Windows desktop not tested. Linux CEF verification was incomplete:
  the reused binary rendered a blank frontend in the isolated harness.

Reported by xiongshaowei on GitHub.
Refs #7230.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve question marks in import basenames

Derive local basenames without the URL helper's query stripping. For local
path imports use the supplied path, since NativeFile.name may already have
been shortened by that helper. Remote and provider imports retain their
resolved file names and URL fallback behavior.

The new File and path regression cases fail before this change with
originalFilename/title 'manual' instead of 'manual?rev1.pdf'/'manual?rev1'.
They now pass and verify two revisions remain separate library records.
A URL query fallback test also passes. Six import suites: 82 tests passed.
pnpm lint and formatting passed. The pre-push hook reruns the full suite.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): retain filename provenance across import and sync

Keep literal POSIX backslashes in import basenames and PDF identity, while
recognizing explicit Windows paths. Strip queries only from web URL fallback
names and preserve explicitly resolved filenames.

When a cloud-restored PDF lacks its original filename, reimporting its exact
managed path preserves the stored title and metadata hash. File sync fills
missing original filenames without changing titles, storage paths, or clocks.

Verification: four importer regressions failed first (URL fallback, two
backslash input forms, and cloud-restored managed copy). Three sync assertions
failed first for missing provenance and repair detection. All 232 tests across
11 affected suites pass with the fixes. pnpm lint, Biome formatting, and git
diff --check pass. Real web imports and reload retain three distinct filename
titles, original basenames, and embedded metadata. Windows desktop was not
tested; the earlier isolated Linux CEF harness remained blank. The full suite
runs again in the pre-push hook.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): exclude URL fragments from import fallback names

Remove the fragment before deriving the fallback name for a remote file,
while keeping explicitly resolved filenames unchanged.

Verification: the new fragment regression failed first because originalFilename
was manual.pdf#page=2 instead of manual.pdf. All 94 tests across the importer
metadata and web service suites pass, including query-plus-fragment and explicit
question-mark/hash filename cases. pnpm lint, formatting, and git diff --check
pass. Full unit tests run in the pre-push hook. Native device verification was
not repeated for this web URL fallback change.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): decode remote basenames after parsing the URL path

Derive a web remote file's fallback name from its final pathname segment before
decoding. This excludes queries and fragments, decodes reserved characters, and
preserves encoded backslashes as filename characters. Keep the encoded spelling
when pathname bytes cannot be decoded as UTF-8. Explicit filenames bypass this.

Verification: six new URL cases failed before the fix, covering C++, a slash
inside the query, malformed query/path bytes, and two encoded backslash names.
All 100 tests in the importer metadata and web service suites now pass. pnpm
lint, Biome formatting, and git diff --check pass. The full suite runs in the
pre-push hook. Native device verification was not repeated for this web fallback.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* test(library): cover Android provider display names on import

Verify opaque Android content URIs resolve the provider display name through
Tauri basename, for both external-storage and staged-provider file paths.
Verify importBook uses that resolved File.name for originalFilename, PDF title,
and salted identity instead of parsing the document identifier.

Verification: all 114 tests across the import metadata, web service, and native
service suites pass, as do pnpm lint, formatting, and git diff --check. This is
coverage of the existing basename flow, so no production behavior changed.
Android native basename was inspected and queries OpenableColumns.DISPLAY_NAME.
UI verification could not run against the available emulator because its
existing development WebView shows an unavailable URL. The full unit suite runs
in the pre-push hook.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve resolved filenames as atomic basenames

Do not split a resolved File.name again during original filename capture.
Local path basenames were already extracted, while a decoded URL segment may
contain a slash that belongs to its filename identity.

Verification: the two-file URL regression failed first with one/part.pdf reduced
to part.pdf and a different salted hash. It now passes and verifies two live
records with distinct filename titles and metadata hashes. All 138 tests across
eight import/native suites pass. pnpm lint, formatting, and git diff --check
pass. The full suite runs in the pre-push hook. Device UI checks were not
repeated for this filename capture change.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): simplify import filename handling (owner: refactor and simplify it)

Replace nested filename selection with explicit URI and local-path branches.
Resolve the managed-copy title/hash exception in one block instead of spreading
it across a boolean and three ternaries. Use the resolved title directly and
avoid PDF stem processing for non-PDF imports.

Verification: this is a control-flow refactor with no intended behavior change.
All 138 tests across eight import/native suites pass both before and after.
pnpm lint, Biome formatting, and git diff --check pass. Existing regressions
cover provider names, local special characters, Windows paths, decoded URLs,
conversion, and managed-copy identity. Full tests run again in the pre-push
hook. Device UI checks were not repeated for this refactor.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): share URL filename parsing across native and web imports

Reuse the URL pathname basename decoder in native and web filesystems. Native
URL fallbacks now exclude fragments and query separators and preserve decoded
filename characters, while explicit names remain unchanged. Use the existing
platform-aware path normalizer for managed-copy comparisons.

Verification: the new native URL and case-variant managed-copy regressions
failed before the fixes. All 146 tests across eight affected import/native
suites pass. pnpm lint, formatting, and git diff --check pass. Full tests run
in the pre-push hook. Device UI checks were not repeated; prior platform
verification limitations remain recorded on the PR.

Reported by xiongshaowei on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): keep extensionless PDF downloads distinct

Use the existing file hash as the PDF identity salt when a remote URL does
not provide a .pdf filename. Keep the query-free title and original filename.
This prevents distinct query-selected downloads with identical metadata from
replacing one another's managed files.

Verified: the new extensionless-download regression failed before the fix
(expected two live books, received one), then all 147 affected tests passed.
pnpm lint passed with one unrelated informational notice; diff check passed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): retain extensionless PDF identity on reimport

Select the PDF identity salt from the preserved original filename rather than
the current input URL. Extensionless imports keep content-based identity when
the same files are reopened from local managed paths.

Verified: the extended two-download regression first failed because both
metadata hashes changed to the shared download stem. The correction preserves
both hashes, original names and live records without removing managed files.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): persist import provenance through cloud sync (owner: Can we simplify it?)

Add nullable books.original_filename, database mappings and blank-fill sync
merging so imported provenance survives cloud restoration and old clients.
Migration 031 must be applied before deploying the updated server.

Simplify PDF title/identity selection into three direct cases and normalize
the name once. Keep fallback metadata stable on managed-copy reimport and
refresh stale batch metadata keys after successful imports.

Verified: new regressions failed first for stale index keys, sanitized PDF
fallback titles, transform round trips and cloud filename merging. All 242
related tests pass, as do TypeScript, Biome lint and formatting checks. Actual
web imports, local reimports and reload preserve names and separate identities.
Migration applied twice successfully in isolated PostgreSQL, preserving null
legacy rows and round-tripping a Unicode filename. No live database changed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): resolve import filenames in openFile (owner: hide the filename parsing in openFile)

Have native and web filesystem openFile return a File whose name is the resolved
basename. Keep URL and Android provider resolution at that boundary and share
literal local-path basename parsing between the filesystem implementations.
The importer now reads fileobj.name without parsing the source path again.

Verified: eight new filesystem assertions failed before the changes for full
web paths, literal POSIX backslashes, question marks and percent-encoded-looking
local or supplied names. All 252 affected tests pass, as do TypeScript and Biome
lint. Existing importer mocks now provide resolved basenames; the obsolete
empty-name filesystem fallback test was removed.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): resolve relative Windows import basenames

Normalize native Windows separators before extracting a local basename, so
relative and drive-relative paths satisfy the openFile name contract while
POSIX backslashes remain literal.

Verified: relative and root-relative Windows regression cases failed first
with directory components in File.name. The same POSIX relative name remains
literal. All 139 filesystem/importer tests and TypeScript/Biome lint pass.
Windows UI was not exercised on this Linux host.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(library): preserve PDF identity and edited titles (owner: just use the origin filename as the default title)

Use the filename stem only as the initial PDF display title. Preserve stored
PDF titles and metadata hashes on exact-file reimport, and leave existing
books without filename provenance as they are. Keep the original content
hash and new-import metadata-hash calculations, removing content-salt and
managed-copy identity migration branches and their index maintenance.

Verified: two new regressions failed first because reimport replaced edited
or legacy titles and metadata hashes. All 81 importer tests now pass; lint
and whitespace checks pass. In the real web app, importing a PDF, editing
its title through Book Details, reloading, reimporting, and reloading again
preserved the edited bookshelf title, original filename, and both hashes.
Native UI was not repeated for this title-only simplification.
Reported by xiongshaowei on GitHub (#7230).

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(library): clarify native filename branches (owner: Why the change is so ugly?)

Resolve URL and provider names within their early-return branches, then
select the local filename. Remove the overwritten mutable filename and
nested platform/path ternary while preserving existing naming behavior.

Verified with 141 passing native/web filesystem and importer tests, plus
TypeScript, Biome lint, and git diff --check. This is a control-flow cleanup;
no behavior change or new regression test is introduced. Native UI was not
repeated for this refactor.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 11:52:20 +01:00
Huang Xin
bc7a5bfa54
feat(sync): record each book's synced read-aloud packs in its config (#7190)
* feat(sync): record each book's synced read-aloud packs in its config

Every Read Aloud open listed every sync destination for the book's audio,
including books that have none. The packs each destination holds now
travel in the book's config (BookConfig.ttsPacks, by destination id), which
every device already fetches when it opens the book:

- An open lists a destination only when the record names a pack this
  device lacks, or the destination was never recorded. A book without
  audio, once recorded, makes no request.
- A push needs no listing when every downloaded pack is already recorded
  there. With something to upload it still lists first, which checks the
  destination still takes the book (Readest Cloud) and skips what a peer
  uploaded.
- After a listing, the record for that destination is replaced with what
  it found (a declining destination as empty) and saved to the local
  config file at once.

The record merges as a union and never bumps updatedAt, so recording audio
cannot move reading progress: in config.json as its own envelope key, in
the Readest Cloud pull, and on the server, which grafts the union onto the
row whichever side wins it. Readest Cloud stores it in a new
book_configs.tts_packs column (migration 030).

Verified:
- Tests that fail without the change: engine.test.ts "makes no request
  when every pack is already recorded there" (`expected 1 to be +0`);
  tts-book-cache-store.test.ts "an open pulls nothing when every
  destination is recorded and nothing is missing" and "records what each
  listed destination holds, a declining one as empty"; merge.test.ts
  "unions both sides even when the remote config is older"; wire.test.ts
  "buildRemotePayload carries the synced read-aloud packs outside
  config"; transform.test.ts "round-trips the packs each destination
  holds"; sync-tts-packs-merge.test.ts (resolveTTSPacksMerge is new);
  useProgressSync.test.tsx "adds the read-aloud packs a peer recorded,
  without bumping updatedAt".
- dev-web, WebDAV only, request counter in the page: the first open of a
  book listed WebDAV once (404); after a reload, opening and starting Read
  Aloud made no audio-sync request; downloading a chapter listed once,
  created the folder and uploaded the pack; the config.json pushed to
  WebDAV carried `"ttsPacks":{"webdav":["1-4f4d1ca4.mp3"]}`; the next open
  made no audio-sync request.
- Not run in the app: the Readest Cloud half. dev-web uses the production
  database, which does not have migration 030 yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): never skip a push on the recorded read-aloud packs

Review finding (CodeRabbit): the record of each destination's packs only
grows by merging, so after a book's audio is purged from a destination
(the book removed from Readest Cloud) it still names those packs. A push
trusting it skipped the listing, so the device holding the audio never
uploaded them again, even after the book was uploaded again.

The record now only lets an open skip its pull. A device with downloaded
audio lists each destination once per open before pushing, as before the
record existed, and that listing corrects the record. A book without
downloaded audio still makes no request.

Verified: engine.test.ts "still uploads a recorded pack the destination no
longer holds" failed with the push still taking the record (`expected +0
to be 1`); with the parameter gone, tts-book-cache-store.test.ts "the push
never trusts the record, so purged packs are uploaded again" pins that the
round no longer hands it over (fails with the old call, `expected
"vi.fn()" to be called with arguments: [ Array(4) ]`). pnpm test (1217
files, 14485 tests), pnpm lint and pnpm format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep pack records another sync merged while a round ran

Review finding (CodeRabbit): a sync round read the book's ttsPacks when it
started and wrote back that copy plus what it listed. The reader's
open-time pull can merge a peer's record while the round awaits its
listings, and the write-back dropped it. The round now starts from the
config as it is when it commits and replaces only the destinations it
listed.

Verified: tts-book-cache-store.test.ts "keeps an entry another sync merged
while the round ran" fails without the change (`expected "vi.fn()" to be
called with arguments: [ 'hash-rec6', { ttsPacks: { …(2) } } ]`). pnpm test
(1217 files, 14486 tests), pnpm lint and pnpm format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sync): keep a pack merged into a destination while a round listed it

Review finding (CodeRabbit): a round replaced each listed destination's
record with its listing, so a peer's pack merged into that destination
after the listing began was dropped, and the next open skipped pulling
it. The listing now supersedes only the entries the round started with;
entries added since are kept.

Verified: tts-book-cache-store.test.ts "keeps a pack merged into a
destination while the round listed it" fails without the change
(`expected "vi.fn()" to be called with arguments: [ 'hash-rec7', …(1) ]`).
pnpm test (1217 files, 14487 tests), pnpm lint and pnpm format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:01:24 +01:00
Huang Xin
5d2a939c28
fix(storage): check the quota after reserving the row and keep clients off files writes (#6820)
* fix(storage): reserve upload quota atomically and cap public image uploads

Check the storage quota and record the file row in one database call
(reserve_storage_upload, migration 029) that serialises a user's
reservations with an advisory lock and sums live file sizes under it, so
concurrent upload requests can no longer each pass against the same usage.
A reservation is released if signing the upload URL fails.

Require a positive integer fileSize on every upload path, and cap the
unmetered public cover/temp image uploads at 20 MiB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(storage): report re-upload usage without double counting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(storage): check the quota after reserving the row (owner: optimize the upload quota check instead of adding another layer)

The `files` row an upload writes is already its reservation, and the
trigger on `files` adds its size to `plans.storage_usage_bytes` in the
same transaction. So instead of migration 029's locked RPC, the upload
route now inserts the row first, reads the counter, and deletes the row
and returns 403 if it is over quota. Every accepted request checked after
its own row committed, so the last one to check counted all the others:
concurrent uploads can no longer pass against the same usage. A row is
also dropped if signing fails, and a re-upload of an existing key adds
nothing and is not re-checked. The fileSize validation and the 20 MiB
cap on cover and temp uploads stay.

Share import gets the same check. A fresh import used the token's frozen
usage claim, and restoring a soft-deleted copy was never checked at all;
both now check the counter once the row is live and undo it if over.

Migration 029 now revokes INSERT/UPDATE/DELETE/TRUNCATE on `files` from
anon and authenticated and adds CHECK (file_size >= 0). Only the API
routes write `files`, through the service role, but the grants let a
signed-in user write their own rows through the REST API directly:
insert a negative size, edit a size, or delete a row and keep its object.
init/schema.sql matches it for new installs.

Verified:
- storage-upload-quota.test.ts and share-import-quota.test.ts run
  against main's routes fail 12 and 2 cases: three concurrent uploads
  reach 608174080 bytes against a 524289000 limit; fileSize -1 and
  -107374182400 return 200 and leave a row; a failed signing leaves its
  row; a re-upload is counted twice; over-quota share imports and
  restores return 200 instead of 402. All pass with this change.
- Migration 029 applied twice to a local Postgres 15 `files` table with
  prod's policies and ALL granted to anon/authenticated: before it, a
  signed-in user set their own row's file_size to -5; after it, their
  insert, update and delete fail with "permission denied for table
  files", their select still works, and the service role cannot insert
  a negative size.
- pnpm test (1167 files passed), pnpm lint, pnpm format:check.
- Not run: an end-to-end upload in the app, or a concurrent burst
  against a real database.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(storage): fail closed when the storage usage read fails

Both quota checks fell back to the token's frozen usage claim on any
error reading `plans`, so a transient database error let an upload or
share import pass on stale usage. Only a missing row (PGRST116) or a
missing `plans` table, as on self-hosted servers (PGRST205, or 42P01 from
older PostgREST), now falls back. Any other error returns 500 and undoes
the reservation: the upload deletes its new row, and share import
deletes a fresh row or soft-deletes a restored one again.

Raised by CodeRabbit on #6820.

Verified: the new cases in storage-upload-quota.test.ts and
share-import-quota.test.ts ("fails closed ... when the usage read
fails") fail on the previous head with "expected 200 to be 500" and pass
now; the fallback cases cover all three codes. pnpm test (1167 files
passed), pnpm lint, pnpm format:check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:29:27 +02:00
Huang Xin
385889d57d
feat(sync): sync the import-time page count across devices (#6775)
#6662 records a book's page count at import, but only on the importing
device. Other devices got a count only once someone opened the book, and a
cloud-only book could not be counted locally at all.

- Add a nullable books.page_count column (migration 028) and map it both ways.
  A pulled row without a count leaves the key off, so the pull merge keeps the
  local value.
- The server merge keeps the row winner's count and falls back to the other
  side's, so a push without one (old clients, the KOReader and Calibre
  plugins, devices that never counted the book) never erases it, and a server
  row missing a count gets it filled in without a date-read reorder.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:45:34 +02:00
esmaeelE
7893fa9167
Support handwriting annotation (#6674)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* Add handwriting annotations with optional BOOX pen support (#3673)

- services/handwriting: platform-neutral ink model (normalized,
  page-relative coords, versioned schema), coordinate transform,
  canvas renderer, editor with undo/redo/erase, capability detection,
  and BookConfig persistence (device-local, excluded from cloud sync
  like the existing paired-audiobook field). 44 unit tests.
- Generic pointer-event backend works everywhere (web/desktop/iOS/
  non-BOOX Android); BOOX raw-drawing is an additive fast path chosen
  automatically via detectPenCapabilities().
- Native bridge: query_pen_capabilities/start_raw_drawing/
  stop_raw_drawing/set_raw_drawing_enabled commands added to
  tauri-plugin-native-bridge (Rust: commands/mobile/desktop/lib/
  build.rs + permissions).
- BOOX Pen SDK isolated behind a new Gradle 'pen' flavor dimension
  (genericPen default / booxPen opt-in) so default/FOSS builds never
  add BOOX's Maven repo or dependency; rationale and build docs in
  android/README-pen.md. PenInputController interface keeps every
  Onyx SDK type out of NativeBridgePlugin.kt.
- Reader UI: HandwritingOverlay/Canvas/Toolbar + useHandwriting hook,
  mounted in BooksGrid next to FoliateViewer. PDF pages are keyed
  precisely by page index; EPUB ink is anchored per-section (documented
  limitation: reflow has no fixed page).

Verified: tsc --noEmit clean, biome clean, full handwriting test
suite green (44/44).

NOT verified (no Android SDK/NDK or BOOX hardware in this
environment): android/src/booxPen/** has not been compiled — see
android/README-pen.md for what to check before shipping the booxPen
flavor. The Rust plugin changes have not been built with cargo/tauri
CLI (not installed here) but follow the existing refresh_eink_screen
command's pattern exactly across every layer they touch.

* add handwritten

* chore(android): update icons and add Android build docs

- Regenerate app icons with pnpm tauri icon
- Simplify ic_launcher.xml via tauri android init
- Add ANDROID_BUILD.md with build instructions

* docs(android): document build fixes for Android APK build

- Java 21 requirement (Gradle 8.14.3 fails on Java 25)
- AGP downgraded from 8.11.0 to 8.7.3
- Aliyun Maven mirror for offline Google repo access
- buildToolsVersion 35.0.0 pinning
- compileSdk warning suppression

* test(browser): update annotation popup screenshots for added handwriting tool

* chore: drop Android icon regeneration and local build doc from PR

* fix(test): restore upstream ExportMarkdownDialog test and add getConfig mock

* refactor(handwriting): rework ink anchoring, persistence and BOOX pen path

Ink placement:
- Key fixed-layout ink by section index instead of the location counter,
  which collided for adjacent PDF pages.
- Anchor reflowable ink to the page-start CFI and reuse any stored anchor
  inside the visible range, so ink no longer repeats on every page of a
  chapter.
- Normalize fixed-layout ink to the page frame, so it follows zoom and pan.
- Disable handwriting in scrolled mode.

Persistence:
- Clearing the last inked page now sticks (the store merges partials).
- Imports update the store before the live editor reloads.
- Save on committed edits only, debounced to disk; simplify strokes on
  commit instead of on export.
- Ink written by a newer schema is never overwritten.

UI:
- Enter via View menu > Handwriting Mode; drop the always-visible floating
  button and the selection-popup tool.
- Single toolbar below the safe-area inset; no color swatches on B&W e-ink.
- The Notebook falls back to Notes when the Handwriting tab has nothing to
  show; rows are labelled by chapter and sorted in reading order.
- JSON export works for books that only have ink.
- Drop the restyle feature.

BOOX:
- Run the pen SDK on the WebView with density scaling, close the previous
  session on restart, and deliver each stroke on pen-up with normalized
  pressure.
- Only use raw drawing when an EMR pen digitizer is present, so pen-less
  readers keep finger drawing.
- Make the opt-in booxPen flavor build: repository in the app module,
  support-library exclusion, libc++ pickFirst, no stripping of prebuilt SDK
  libraries, and R8 rules.
- Remove the unused set_raw_drawing_enabled command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): tap ink to edit it; show every anchor on a reflowed page

- A single tap on existing ink enters handwriting mode instead of turning
  the page. Single clicks now carry their main-window position so overlays
  can hit-test them.
- A reflowed page shows the ink of every anchor in its visible range, not
  just one, so a smaller font no longer hides ink drawn on the next page.
  Eraser, Clear Page and Undo cover all of them as one step; new strokes
  go to the page's primary anchor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): pin reflowable ink to the content it marks

Ink in reflowable books was stored in page coordinates, so any font,
spacing or margin change left it over the wrong text. Each stroke is now
bound to content and re-placed from the current layout:

- Ink over text or images binds to the range of words and elements it
  covers (underlines bind to the line above) and is stored normalized to
  that range's box. Re-fitting to the new box keeps its shape and topology
  through font size, font family, line height and margin changes.
- Margin ink binds to the nearest character and scales uniformly; strokes
  written in one burst share an anchor so a note stays in one piece.
- Reflowable ink is keyed per section; the notebook labels rows by the
  chapter of the inked text and jumps straight to it.
- Fixed-layout ink stays normalized to the page, which already tracks
  zoom and pan.

This replaces the page-start anchors and the multi-anchor workaround.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): drawings as annotations; shape-aware morphing

Each drawing is now an `ink` booknote: listed with the other annotations
in the left sidebar (pen icon and the text it marks), navigable and
deletable there. A reflowable book gets one note per anchor, a fixed-layout
book one per page. Ink notes travel by file sync; Readest Cloud has no field
for stroke data yet, so they are kept out of its push. The notebook's
Handwriting tab and the separate handwriting import/export are removed; a
notebook canvas is left for a follow-up.

Pinned ink now morphs by its shape:
- flow (underline, strike-through): follows its words, split per line on a
  re-wrap; marks are resampled so they stay continuous.
- box (circle, box, scribble): fitted to the content it encloses, so an
  edge brushing the next line no longer widens it to the whole line.
- span (bar or bracket beside a paragraph): stretched along its lines,
  kept at its distance from the text edge.
- rigid (margin notes): moves and scales with the nearest character.
Boxes are measured within one column, so a range wrapping onto the next
page can no longer blow a drawing up across two pages.

Ink also shows in scrolled mode (read-only) for every loaded section or
page, and follows a PDF pinch live instead of jumping when it commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): redesign drawing mode; one annotation per session

- Drawing starts from a pen button in the reader header (the View menu
  item is gone; tapping existing ink still opens it for editing).
- While drawing, the reader's header and footer give way to the mode's own
  bars: a top bar (Drawing, Done) and a bottom dock with the pen (color and
  size in a popover), eraser, undo, redo and page turning. Nothing can cover
  Done any more.
- Strokes still save as they are drawn, but everything drawn in one visit
  to drawing mode is one annotation in the sidebar, instead of one per
  stroke. Each stroke keeps its own text anchor (or page in fixed layout).
- A short underline that encloses nothing binds to the word it marks,
  rather than to whichever character happened to be nearest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): draw in scrolled mode

Scrolled views show several sections (or PDF pages) at once, so drawing
was limited to paginated mode. Each finished stroke and eraser sweep is now
routed to the section or page it is drawn over, pinned with that section's
text anchoring (or normalized to that PDF page), while the live stroke
draws over the per-section ink layers. Undo follows the page last drawn
on, and the dock's arrows scroll a screen at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): stronger strokes and room for the drawing bars

Pen widths are heavier (default 0.006 of the page width) and a finger
stroke no longer carries pressure: touch reports contact size, not
pressure, which thinned every finger stroke. Ordinary pen pressure now
draws the full pen width, so existing strokes render stronger too.

Drawing mode lives in the reader view state, and the viewer reserves
the top bar and dock bands in its margins (paged) and scroll padding
(scrolled) while it is on, the way the TTS mini player does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): draw committed strokes as smoothly as live ones

A stroke was simplified on commit to within a pixel and then drawn as a
polyline, so small loops turned angular and pressure changed in steps
once the pen lifted. Keep points to a fifth of a pixel and wherever the
pressure changes, and draw strokes as quadratic curves through the
samples. Also add the drawingEnabled view state to two test fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): fill pen strokes as one antialiased outline

A pen stroke was stroked as many short pieces of different widths. Each
piece antialiased its own edge with round caps, so at every joint the soft
edges blended twice and the width stepped, which read as a jagged edge
next to native ink. Trace the stroke's outline around samples every 1.5px,
with the width interpolated along the curve, and fill it once. A single
contour has no inner edges for the rasterizer to blend, and points where
the inner side of a tight turn would fold back are skipped so no hole
opens there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): start every drawing session with the pen

The eraser toggle outlived the drawing session, so turning drawing back on
after erasing left the eraser active and the first strokes wiped ink
instead of drawing, which looked like strokes were not being recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): keep a Pencil stroke drawn right after a tap

iOS WebKit read a quick tap followed by a drag as its own double-tap or
text-selection gesture and withheld that touch from the page entirely, so
the stroke never reached the canvas. touch-action: none only stops panning
and zooming. The drawing surface now cancels the default of its touch
events, which leaves the touch sequence to the page while pointer events
still arrive, and is unselectable with no callout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): draw from the instant annotation tools, save from the dock

Draw moves from its own header button into the header's instant
annotation tools. The top drawing bar is gone: its Done becomes a save
icon as the dock's last button, and only the dock's band is reserved
below the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): add a marker tool beside the pen

A marker draws a broad translucent band of even width with flat ends, for
highlighting what is under it. It is stroked as one path, so it does not
darken where it crosses itself, while separate marks still mix where they
cross. It ignores pressure, keeps its own highlighter colors and widths,
and the eraser sizes itself to one marker band instead of three. The dock
shows pen, marker and eraser side by side; tapping the active tool opens
its options. Marker ink is stored with tool: 'marker'; pen ink is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): match the pen and marker buttons to the rest of the dock

The tool buttons used a different icon set and a wider pill with a color
dot and caret. They now use the dock's line icons in the same square
button, with the active tool's ink color as a thin band under its icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): lead each annotation with an icon for its kind

Bookmarks, highlights, notes and drawings each start with a small round
badge, so the kind of an item reads at a glance. The badge carries the
kind's name for screen readers and replaces the inline pencil drawings
used to show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): save a drawing and keep drawing; close from the dock

Save now finishes the current drawing as one annotation and stays in
drawing mode, so the next strokes start a new annotation, with a short
toast when there was ink to save. A Close button at the end of the dock
leaves drawing mode. Strokes are still saved as they are drawn, so
neither discards anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sync): sync handwriting strokes through Readest Cloud

Adds an ink jsonb column to book_notes (migration 026, folded into the
base schema) and carries ink notes through the notes sync instead of
leaving them to file sync only.

- The sync transform maps strokes to and from the column. Other notes
  never send the key, so an upsert does not clear stored strokes, and a
  pulled row without strokes carries no key, so merging it cannot wipe
  strokes held locally.
- Drawings are pushed when they change and never get an xpointer, which
  keeps every KOReader plugin version from importing one as a highlight.
- Committed points are rounded to 1/10000 of the page (pressure to
  1/100), which more than halves what each drawing stores and syncs.

The column has to exist before a server running this code receives a
drawing, so apply the migration to the database first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Readest Agent <agent@readest.local>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 21:31:38 +02:00
Huang Xin
80f196a9b8
fix(sync): resolve book groups and metadata on their own clock (#5911, #5912) (#5921)
* fix(sync): resolve book groups and metadata on their own clock (#5911, #5912)

Book groups (#5911) and book descriptions (#5912) are one defect: `groupId` /
`groupName` and the `metadata` blob were resolved on the whole-row `updatedAt`
clock with raw, clearing assignment, so a copy of a row that had neither could
overwrite a copy that had both.

`updatedAt` is stamped by operations that have nothing to do with either. The
important one is uploading: `cloudService.uploadBook` sets
`updatedAt = Date.now()` so the fresh `uploadedAt` reaches peers, and
`transferManager` runs uploads as a queue — which is exactly the reporter's
"19 records with sequential updatedAt within ~8 seconds". Those rows were never
re-grouped, they were re-uploaded, and that made them outrank every genuine
grouping edit that came before.

Two more things completed the chain. `isReadestCloudEnabled` falls back to
`enabled ?? !hasAnyThirdPartyEnabled`, so a WebDAV user's group edits never
reach Readest Cloud while a clean install (no backend configured yet) restores
those stale ungrouped rows on sign-in. And the pull side used a strict `>` while
the push side rebuilt library.json from the local rows unconditionally, so a TIE
did not mean "no opinion, keep both" — it meant "local wins, the peer's data is
destroyed", which is how the emptied rows propagated back to every device.

Group membership now merges on its own `groupUpdatedAt` / `group_updated_at`,
mirroring reading_status_updated_at (015, #4634), cover_updated_at (017, #4544)
and metadata_updated_at (018, #5438) across the schema, the server merge, the
Readest Cloud client merge and the third-party file-sync merge, and stamped at
every group mutation site.

One deliberate difference from those three: an unstamped TIE does NOT fall back
to the row winner — the side that actually has a group wins. Every existing row
is unstamped, so without this the fix would only prevent new damage and leave
already-broken libraries broken; instead the device that still has the groups
republishes them. "Never grouped" and "ungrouped by a client too old to stamp"
are indistinguishable on a tie, erasing a real group is unrecoverable, and
losing an un-group is not. A stamped removal still propagates, so the #4942
contract holds on the right clock (its merge.test case is restamped).

For #5912, an absent `metadata` blob now never wins on any clock. Nothing in the
app empties `book.metadata` — the editor edits fields inside it — so an absent
blob always means "this row never had one", never "the user cleared it".

The two clock-free repair clauses would otherwise fire for a whole library at
once on the first run after the fix, costing a cover GET and a config GET per
book and breaking the O(changed) contract of incremental sync. `engine.ts` gates
those pulls on `isRemoteBookClockNewer`; the repair path touches index fields
only, with regression tests asserting zero cover/config reads.

Shipping this needs a deploy, not just a client release: it adds migration 022
and changes the server-side books merge.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(sync): keep the group/metadata repair off the incremental path

Incremental sync is O(changed) by contract. The repair clauses added in
af4c3355 broke that: `isRemoteBookMissingLocally` is true for an ENTIRE library
at once on the first run after the fix, and each hit calls
`store.updateBookMetadata` -> `useLibraryStore.updateBook` ->
`saveLibraryBooks`, which serializes and rewrites the WHOLE library file plus
its `.bak`. A 181-book library whose rows all need a group back would do 181
full-library writes on an ordinary background sync — quadratic in bytes, for a
repair nobody asked for at that moment. Gating the cover and config GETs, as
that commit did, addressed the requests and missed the writes.

The repair moves to Full Sync, which is already where this engine reconciles
`uploadedHashes` / `emptyDirs` drift and row-vs-filesystem split-brain.

Stopping the DAMAGE does not need any of it, and is now free. The propagation in
#5911 / #5912 is entirely a PUSH-side effect: the index re-push rebuilds
library.json from the local rows, so a device whose row merely tied the row
clock republished its ungrouped, description-less copy over the peer's good one.
`resolvePublishedBook` resolves each row against the remote index entry as the
push walks the map it already walks — no request, no library write — and makes
the narrow claim that publishing must never DELETE what the remote already had.
This device's row still wins the row on its own clock.

So an incremental run now never repairs and never writes, yet can no longer
empty a peer's shelf; Full Sync is what puts a device's own groups and
descriptions back.

Both guards are mutation-checked: dropping `resolvePublishedBook` flips 2 tests
red, dropping the `fullSync` gate flips 1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(sync): resolve the metadata group on its own clock when publishing

Review follow-up on #5921. `resolvePublishedBook` preferred any non-empty
`local.metadata`, so a device holding an older description could publish it over
a peer's newer one.

Not reachable under 'silent': the reconcile pass resolves the metadata clock
into the local row before the push, and a test now pins that. It is reachable
under 'send', which applies nothing from the remote and therefore skips the
reconcile block entirely — leaving `resolvePublishedBook` as the only thing
between a peer's newer description and a stale local blob. #5900 established
that a send run may publish its own rows but must not erase what peers
contributed to the index; this is the same invariant for a field rather than a
row.

Resolved as a GROUP (title / author / tags / blob / stamp move together), the
way `mergeBookMetadata` resolves it, so the published row cannot pair one
device's title with another's description. The never-delete fallback still
applies whichever side wins the clock.

Mutation-checked: pinning the winner back to `local` flips the send test red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 15:22:35 +02:00
Huang Xin
165e3192ae
fix(sync): merge book metadata on its own clock so page turns cannot clobber edits (#5438) (#5442)
A metadata edit (title, author, tags, metadata incl. language) shares the
books row with page-turn progress, which dominates updated_at: any device
that reads the book after the edit pushes a stale-metadata row with a newer
updated_at and whole-row LWW reverts the edit server-side; on pull, the
locally-read book keeps its stale copy. RSS feed books are read daily on
every device, making the loss near-deterministic (issue #5438).

Give the metadata group its own field-level LWW timestamp, the same fix
reading_status (#4634) and the cover (#4544) received:

- migration 018 adds books.metadata_updated_at (nullable, additive)
- getBookWithUpdatedMetadata stamps it on every metadata edit; the ingest
  subject-tag append stamps it too since tags ride the metadata clock
- the server merge resolves the group by the stamp on both row outcomes,
  with a value-level no-op guard; an unstamped-vs-unstamped tie follows the
  row winner so legacy rows keep their historical behavior
- useBooksSync grafts the fresher group client-side and recomputes
  primaryLanguage (what TTS reads) from the adopted metadata, also when
  adopting a new cloud book
- the file-sync mergeBookMetadata mirrors the clock, and
  shouldApplyRemoteBookMetadata triggers on a metadata-only-newer remote
- the calibre plugin stamps metadataUpdatedAt when a push changes the
  group and carries the server stamp otherwise

The other half of the issue, feeds missing on Android entirely, is the
already-merged #5314 which is not in the shipped 0.11.20 builds.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-02 15:46:39 +02:00
Huang Xin
082edc204b
fix(sync): sync updated book covers across devices (#4544) (#4731)
* docs: design for syncing updated book data (cover + file) (#4544)

Cover-change sync via a content hash (coverHash = partial MD5 of cover.png)
plus a cover_updated_at field-level merge timestamp; file updates ride the
existing re-import / metaHash dedupe.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(sync): sync updated book covers across devices (#4544)

Editing a book's cover wrote cover.png locally but changed no hash (the
cover is keyed by the file hash), so peers had no signal to re-download it
and the change never propagated.

Give the cover its own content-addressed version:
- coverHash = partial MD5 of cover.png; a peer re-downloads the cover iff
  the synced hash differs from the local one (idempotent, no churn on
  identical/re-extracted covers — compatible with the metaHash dedupe).
- coverUpdatedAt = field-level LWW timestamp so a page-turn that wins
  whole-row LWW on updated_at can't clobber a cover edit (mirrors the
  reading_status_updated_at fix for #4634).

Editing a cover recomputes the hash, bumps coverUpdatedAt, and re-uploads
only the cover; the server merges cover fields independently; peers
re-download on a hash diff. File updates continue to ride the existing
re-import / metaHash dedupe (changed file -> changed hash -> re-key).

Migration 016 adds cover_hash / cover_updated_at to books.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 17:31:03 +02:00
Huang Xin
9155ae627c
feat(sync): decouple the incremental-pull cursor from updated_at via server synced_at (#4678) (#4712)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
PR checks / test_extensions (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): decouple the incremental-pull cursor from updated_at (#4678)

`books.updated_at` was overloaded as both the incremental-pull cursor
(`GET /api/sync?since=…` filters `updated_at > since`, devices keep one
global `max(updated_at)` watermark) and the library "date read" sort key.
A server-resolved reading-status merge had to be written with a timestamp
greater than every peer's global cursor to propagate, which forced
`updated_at = now()` and reordered the date-read library by sync-processing
time (the #4677 symptom).

Introduce a server-assigned `synced_at` column on `books`, stamped by a
`BEFORE INSERT OR UPDATE` trigger on every write, used only as the pull
cursor. `updated_at` stays pure client event time used only for sorting.

- Migration 016 + baseline schema: add `synced_at` (NOT NULL DEFAULT now()),
  index `(user_id, synced_at)`, trigger `set_books_synced_at`. Backfill
  `synced_at = updated_at` before creating the trigger so existing devices'
  cursors hand over without a re-sync storm.
- GET: books filters/orders on `synced_at > since` (a delete bumps synced_at,
  so the deleted_at clause is dropped); configs/notes stay on updated_at.
- POST: extract `buildStatusPropagationRow` and drop the `updated_at = now()`
  bump — the trigger advances synced_at so peers re-pull the status change
  while updated_at (the sort key) stays put.
- Client `computeMaxTimestamp` keys on synced_at, falling back to
  updated_at/deleted_at for pre-migration servers and configs/notes.

Backward-compatible: `synced_at >= updated_at` always, so `synced_at > since`
is a strict superset of `updated_at > since` — old web clients and the
koplugin keep working with no data loss (at worst a redundant idempotent
re-pull of rare server-merged rows). The koplugin's shared pull/push cursor
is left untouched; a proper split is a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(sync): make the books synced_at backfill safe for large live tables (#4678)

The single `UPDATE … WHERE synced_at IS NULL` deadlocked on a 3.8M-row
production `books` table: it rewrites every row in one transaction while the
live /api/sync push path upserts books rows, and the two lock rows in opposite
orders. `ALTER COLUMN … SET NOT NULL` (full-table ACCESS EXCLUSIVE scan) and a
plain CREATE INDEX (write-blocking SHARE lock) compounded it.

Rework migration 016 as an online migration (run via psql, not in a wrapping
transaction):
- backfill in small autocommitted batches via a procedure, using
  FOR UPDATE SKIP LOCKED so it never waits on an app-locked row;
- CREATE INDEX CONCURRENTLY instead of a blocking build;
- install the trigger last (so it can't clobber the updated_at backfill);
- drop the hard SET NOT NULL (the default + trigger + backfill keep the column
  populated and the client falls back to updated_at); a NOT VALID CHECK +
  VALIDATE alternative is included, commented, for operators who want it.

The baseline schema.sql (fresh, empty installs) keeps the simple inline
NOT NULL DEFAULT now() + trigger.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 21:24:01 +02:00
Huang Xin
72233e1c6a
feat: sync reading status across devices and with KOReader (#4634) (#4656)
* docs(sync): design spec for syncing reading status (#4634)

Field-level LWW for reading_status (dedicated reading_status_updated_at),
a new 'abandoned' status in the Readest UI, and a koplugin bridge to
KOReader's native summary.status (whole-library apply + capture).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(sync): implementation plan for syncing reading status (#4634)

Bite-sized TDD tasks across 3 parts: A) cloud field-level LWW
(reading_status_updated_at on server upsert + client pull-merge),
B) 'abandoned'/On-hold status in the Readest UI, C) koplugin bridge
to KOReader summary.status (mapping + reconcile + whole-library
apply/capture).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(sync): add reading_status_updated_at for field-level status LWW (#4634)

* feat(sync): stamp readingStatusUpdatedAt on status change in updateBookProgress

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(sync): stamp status timestamp on explicit library status edits

* feat(sync): resolve reading status by its own timestamp in client pull-merge

* feat(sync): resolve reading status by its own timestamp in server upsert (#4634)

* fix(sync): tighten reading-status merge typing + strengthen test (A5 review)

Replace as-unknown-as double-casts at read sites with typed locals
(clientBook/serverBook); retain a single as-unknown-as only at the
server-wins construction site where the static type is too narrow.
Strengthen test 3 to assert both fields with toEqual.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(library): render the 'On hold' (abandoned) status badge

* feat(library): add 'Mark as On hold' actions + i18n for abandoned status

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* i18n: translate 'On hold' and 'Mark as On hold' for the abandoned status (#4634)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(koplugin): add reading-status mapping + reconcile between Readest and KOReader

* feat(koplugin): persist + sync reading_status_updated_at in LibraryStore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(koplugin): bridge reading status to KOReader summary.status on library sync (#4634)

* test(sync): cover koplugin v1->v2 migration + tighten status-sync tests (final review)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(sync): redesign KOReader first-sync (decisive-only + bootstrap) (#4634)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(koplugin): safe first-sync of reading status (decisive-only + bootstrap) (#4634)

KOReader auto-sets summary.status='reading' on first open, and legacy Readest
statuses have reading_status_updated_at=0, so pure timestamp LWW let opening a
finished book downgrade it. Restrict sync to deliberate statuses (finished/
complete, abandoned/on-hold, unread->clear); never capture KO 'reading'/'New'.
On the unsynced baseline (Readest ts=0) conflicts resolve Readest-authoritative,
then stamp now_ms to exit bootstrap into steady-state LWW. reconcile now returns
write_ko/write_store flags; statussync captures now_ms once and equalizes both
sides (convergent, idempotent, resumable).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(koplugin): cover remaining first-sync graph cells + document sort effect (review)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 05:00:40 +02:00
loveheaven
ae81cd0151
feat(annotator): support global highlights that fan out across all matching positions (#4257)
Introduces a 'global' annotation flag so a highlight/note created on one occurrence of a phrase is automatically applied to every matching occurrence in the book (and stays applied across reloads). Renders these expansions as transient overlays without creating duplicate persisted notes. This flag will not show when the book is fixed layout like PDF or CBZ.

- types: add 'global?: boolean' to BookNote and DBBookNote; transform layer round-trips the field, with regression coverage ensuring older clients do not clobber it on write-back.

- db: new migration 013_add_book_notes_global.sql adds nullable 'global' column to public.book_notes; init schema.sql updated to match.

- annotator: new utils/globalAnnotations.ts handles cfi expansion / text-match search across the spine and overlay synthesis. Annotator.tsx fans out global notes on load and on overlay creation; AnnotationPopup and HighlightOptions expose a toggle to mark a highlight as global.

- sync path is transparent: a global note created on another device is fanned out locally on next render with no extra UI required.
2026-05-21 18:59:07 +02:00
Lex Moulton
baee85e7c8
feat(rsvp): sync reading position to cloud via book_configs (#3801) 2026-04-09 15:52:49 +02:00
Huang Xin
76b239f382
feat(koplugin): add support for annotation sync (#3579)
Add bidirectional annotation/highlight sync between KOReader and Readest:

- Add xpointer0/xpointer1 fields to BookNote and DBBookNote types for
  KOReader XPointer positions alongside Readest's CFI format
- Extend transform layer to pass through xpointer fields to/from DB
- Convert CFI→XPointer on push and XPointer→CFI on pull in useNotesSync,
  discarding notes that fail conversion
- Support KOReader's text()[K].N indexed text node format in xcfi.ts for
  paragraphs with inline elements (e.g. <a> page anchors)
- Generate KOReader-compatible XPointers: text().N for single text nodes,
  text()[K].N only when multiple direct text nodes exist
- Skip cfi-inert elements (injected by Readest at runtime) in XPointer
  path building and resolution
- Map highlight colors between KOReader and Readest color systems
- Implement KOReader plugin annotation push/pull with deterministic IDs,
  auto-sync on document open/close, and UIManager refresh on pull
- Refactor koplugin into focused modules: syncauth, syncconfig,
  syncannotations, selfupdate

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 16:43:51 +01:00
Azeem Bande-Ali
34ad6e6749
fix(selfhost): update docker db schema to match FileRecords (#3527)
In #2636, FileRecord was defined to have updated_at  field
which is used when it is accessed from the database. But the
local dev setup is missing this field.

This diff adds an updated_at column to match the expectation
2026-03-13 05:15:55 +01:00
Huang Xin
c533da498d
feat(annotator): add page number for annotations, closes #3082 (#3405)
* feat(annotator): add page number in annotation

* feat: add page number for annotations, closes #3082
2026-02-28 08:08:56 +01:00
Aniket Kotal
eec2c39f19
feat(docker/podman): self-hosting with docker/podman compose (#3312)
Some checks failed
Deploy to vercel on merge / build_and_deploy (push) Has been cancelled
* initial files

* added testing files

* removed unused files

* cleaned additional mounts

* fixed sql init

* removed more unused files

* moved to docker folder

* revert package.json

* gitignore update

* env example comments and compose necessary healthcheck

* ghcr package impl

* updated dockerfile steps  for layer caching

* added development-stage to dockerfile to dev environment

* added documentation on how to use dockerfile and compose.yml

* fixed prettier issues

* fixed image tag

* removed workflow for later
2026-02-18 14:28:10 +01:00