mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
45 commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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>
|
||
|
|
b58728c29a
|
feat(vocabulary): vocabulary builder and Learning/Mastered marks for Word Lens (#7284)
* feat(vocabulary): entry model, sentence extraction and merge Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): revive a word looked up after a delete on a stale device Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(vocabulary): local store, file persistence and backup Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(wordlens): hint Learning words and skip Mastered words Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(dictionary): Learning and Mastered chips, capture lookups to Vocabulary Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(sync): vocabulary table and sync route Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(sync): sync vocabulary across devices Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(vocabulary): export to Anki and CSV Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(vocabulary): hint sources from dictionaries and the AI context dictionary Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(vocabulary): vocabulary builder window Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(i18n): vocabulary strings Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): resolve the sync endpoint on use, not at import Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): save the lookup's sentence from its own paragraph with spacing kept Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): take a dictionary hint from the first definition, not the entry header Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): save a hint on Enter inside the Dialog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(wordlens): re-render hints after the selection clears, keeping the dictionary open Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): leave ruby hints out of saved sentences, dedupe a sentence across CFIs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): keep book text in its own direction under an RTL interface Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): a lookup never overrides a Learning or Mastered mark from another device A word first looked up on a device stamped modifiedAt with the current time, so its empty state beat a mark set elsewhere in the merge. Lookups now carry modifiedAt 0. Selections with no letters get no chips or entry. The migration moves to 032 (031 is taken on main). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): keep syncing past a bad row and cap saved sentences A rejected row failed the whole push, and the push's failure skipped the pull, so one bad word stopped vocabulary sync on that device. The server now skips malformed rows and reports them, the client clears them, and a failed push no longer prevents the pull. Sentences are cut to a window around the word and pushes go in batches of 50. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): rebuild from the server when the local word list is lost The pull cursor lives on the device apart from vocabulary.json. With the file missing or unreadable, the cursor still claimed everything was pulled, so the words never came back. Sync now starts over when the file held no words, trusts the cursor again after that full pull, and keeps a copy of an unreadable file before it is saved over. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): show typed hints as written; harden sentence capture and IME Enter A saved hint went through the pack gloss cleaner, which cut it at a comma or slash. A range the sentence reader couldn't handle could throw inside the annotator; it now falls back to the selected text. WebKit's IME-confirming Enter (keyCode 229) no longer saves the hint early. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(api): keep /api/sync/vocabulary off language detection and DOMPurify The vocabulary route syncs on every book open, so it joins the hot routes that #7274 keeps light. It passes as written: the route imports only the Supabase client, access check, CORS and the vocabulary entry/wire modules. Checked the case can fail: with `import '@/utils/sanitize'` added to the route it fails with `expected [ 'dompurify' ] to deeply equal []`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(vocabulary): describe lookup capture without naming another reader Comment-only change; no behavior to test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): drop the lookbehind from export bolding; guard CSV cells against formulas CodeRabbit on #7284. boldWord used (?<!…), which WebKit before 16.4 rejects and which failed the build's check:lookbehind-regex (build_web_app). It now consumes the boundary before the word in a capture group. CSV text cells that start with = + - @ tab or CR get a leading apostrophe, so a spreadsheet won't run book text or a hint as a formula. Tests that fail without it (export.test.ts): 'bolds whole words without lookbehind support' (RegExp throwing on lookbehind, as old WebKit does) and 'stops spreadsheet apps from running a cell as a formula'. pnpm build-web + pnpm check:all: no lookbehind in chunks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): cap a saved sentence when the selection itself is over the limit CodeRabbit on #7284. With a selection of 300+ characters the window half was 0 and pre.slice(-0) kept the whole text before it. Such a selection is now cut to the limit on its own. Test that fails without it (entry.test.ts): 'caps a selection longer than the limit' (expected 414 to be less than or equal to 302). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): keep unpushed words pending when the word file loads CodeRabbit on #7284. load() merged the file into memory with mergeEntries, which drops the dirty flag, so a word restored from a backup or looked up before the file loaded was never pushed. Either side being dirty now keeps the merged word dirty, as applyRemote already does. Test that fails without it (vocabulary-store.test.ts): 'keeps unpushed changes pending when the file loads over them' (expected undefined to be true). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): keep database errors out of /api/sync/vocabulary responses CodeRabbit on #7284. The route returned PostgREST error messages to the client; it now logs them and returns a fixed message. A since_ts that isn't a timestamp gets a 400 before any query. Tests that fail without it (sync-vocabulary.test.ts): 'rejects a since_ts that is not a timestamp before querying' (expected 200 to be 400) and the two 'keeps database error details out of …' cases. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): run one more sync when one is asked for mid-sync CodeRabbit on #7284. A debounced sync that fired while a sync was running got the running promise back, so words changed after its push snapshot waited for the next change. It now sets a flag and the running sync makes one more pass. Fake timers in the sync tests are restored in afterEach. Test that fails without it (vocabularySync.test.ts): 'runs once more when a sync is asked for while one is running' (pull called 1 time, expected 2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(wordlens): wait to draw hints when a selection starts while the pack loads CodeRabbit on #7284. whenSelectionClears guarded only the start of a refresh; a selection made while the gloss index or OpenCC loaded still had hints drawn under it, which can close the dictionary popup. The draw step now goes through whenSelectionClears and is dropped if a newer refresh ran. Tests (wordlens-section.test.ts): 'waits to draw hints when a selection starts while the pack loads' fails without it (expected [ '尼莫' ] to deeply equal []); 'drops a waiting draw once a newer refresh has run' guards the generation check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(reader): give the Learning/Mastered chips a 32px hit target and focus ring CodeRabbit on #7284, per DESIGN.md (32px minimum hit target, the canonical focus-visible ring). Styling only. Checked on dev-web in Chrome: both chips measure 32px high in the dictionary popup, and Learning toggles on and off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): drop the context when a selection leaves no room for it CodeRabbit on #7284. A 299-character selection skipped the over-limit cut, but the window half was still 0, and pre.slice(-0) kept the whole prefix. Context is now dropped whenever the half window is 0. Test that fails without it (entry.test.ts): 'caps the context when the selection leaves no room for it' (expected 701 to be less than or equal to 302). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): break merge ties on the display word too CodeRabbit on #7284. Two lookup-only copies of a word (same modifiedAt, state and hint) could keep "Serendipity" or "serendipity" depending on argument order, so devices and the server could show different forms. The tie key now ends with the display word. Test that fails without it (entry.test.ts): 'keeps the same display word whatever the argument order' (expected 'Serendipity' to be 'serendipity'). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): save pulled words to the data file before moving the cursor CodeRabbit on #7284. The pull saved its cursor right after applying a page, while the file write waited for the 500 ms save delay; quitting in between left the cursor past rows the file never got, and later pulls start from the cursor. The store gains flush(), and the pull awaits it before each cursor write. Test that fails without it (vocabularySync.test.ts): 'writes the pulled words to the data file before moving the cursor' (expected [ [] ] to deeply equal [ [ 'en:a' ] ]). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(wordlens): defer a whole hint refresh while text is selected CodeRabbit on #7284. The section-load refresh (and any other caller) cleared hints before checking the selection, which unwraps the <ruby> under it and can close the dictionary popup. refreshSectionGlosses now defers itself until the selection clears; its generation bump drops any older pending draw. Test that fails without it (wordlens-section.test.ts): 'leaves drawn hints alone until a live selection clears' (expected [] to deeply equal ['尼莫']). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(reader): save a new sentence for the same word while the dictionary stays open CodeRabbit on #7284. Lookup capture ran only when the word changed, so selecting the same word in another sentence with the popup still mounted saved nothing. It now also runs when the occurrence's book or sentence changes; repeat sentences are still deduplicated by the store. Test that fails without it (DictionaryVocabularyChips.test.tsx): 'records a new sentence for the same word while the popup stays open'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(vocabulary): write the word file one save at a time, and never mid-load CodeRabbit on #7284: flush() cleared the save timer but not a save already writing, so that older write could land over the list flush() had just saved, after the pull had moved its cursor. Writes now run through one chain, each saving the list as it is when it starts. The same race reached backup restore, which wrote the file directly while a delayed save could still land over it. Backup and restore now flush first. A save that ran while the file was still loading wrote the partial list in memory over the file; saves now wait until it has loaded, and load saves the merged list when words were recorded before it finished. Tests that fail without it: - vocabulary-store.test.ts 'flush saves the newest list even while a delayed save is still writing' (expected [ 'en:first' ] to include 'en:second') - vocabulary-store.test.ts 'saves a word looked up while the file is loading, without dropping the file': without the loaded check, expected [ 'en:new' ] to deeply equal [ 'en:new', 'en:old' ]; without the save after load, expected [ 'en:old' ] to deeply equal [ 'en:new', 'en:old' ] - backup-vocabulary.test.ts 'includes a word saved moments ago…' (expected [] to include 'en:fresh') and 'keeps restored words when an earlier save finishes during the restore' (restored word overwritten) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(vocabulary): sync the restore race test on flush instead of a delay CodeRabbit on #7284: a fixed 50 ms wait didn't show the restore was blocked on the stalled save, so the test could pass or fail on timing. It now releases the stalled save only once the restore has called flush(), and always releases it so a failure can't stall later tests. Checked it still catches the bug: with restore's flush() removed it fails with 'expected "flush" to be called at least once'; with it, 3 passed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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 |
||
|
|
85db6faf49
|
fix(opds): allow trusted private catalogs at runtime (#7225)
Add the server-only READEST_TRUSTED_PRIVATE_HOSTS exact hostname allowlist for self-hosted OPDS catalogs. Read it at request time, recheck redirects, and preserve private-address and DNS checks for unlisted destinations. Let self-hosted catalog forms submit LAN URLs and document Docker setup. Verified: 113 focused and neighboring proxy tests passed; pnpm lint, Biome formatting, pnpm build-web and Docker Compose configuration passed. The same production build denied private hosts by default, then allowed GET/HEAD with a runtime-only allowlist after restart. A fresh browser added the LAN catalog and opened its publication feed. Without the fix, the new OPDS proxy tests returned 400 instead of 200, and the self-hosted catalog form never called validateOPDSURL. Full-suite verification is unresolved: the default run had 4 timeouts and a TTS timer teardown error; the 4-worker rerun had 6 timeouts and 4 worker startup failures. An unchanged-main comparison reproduced a ControlPanelUpdateReset timeout. Related reliability tracking: #7217. No Docker image build or reporter deployment verification was performed. Reported by YorrickBao on GitHub. Fixes #7105 Co-authored-by: Claude Code <noreply@anthropic.com> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
9bafc11120
|
feat(tts): custom OpenAI-compatible TTS services (#6746)
* feat(tts): custom OpenAI-compatible TTS services with BYOK Closes #258. Adds Settings > TTS > Custom TTS Services (premium, Full Customization): users configure one or more OpenAI-compatible speech services (base URL, API key, model, voices, optional instructions). Each service's voices appear as their own group in the Read Aloud voice picker for every book language. - OpenAICompatibleSpeechProvider posts to {baseUrl}/audio/speech (mp3) behind BufferedTTSClient, so rate, caching and chapter downloads work as for other engines; highlighting is sentence-level (no word timings). - 401/403/404 end the session, other 4xx skip the sentence, 429/5xx retry. - SpeechProvider gains optional groupVoices (per-service voice groups) and cacheScope (model/baseUrl/instructions fold into the cache key so edits never replay stale audio). - Services sync as the new custom_tts replica kind with the API key encrypted, with its own Manage Sync category; backups strip the key unless credentials are included. Requires migration 027_replica_custom_tts.sql (replica kind allowlist) to be deployed before clients ship. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(tts): voice picker that lists every engine dependably Custom TTS services: - Voices come from the service: GET {baseUrl}/audio/voices (names or {id, name} objects); a service without a listing gets the standard OpenAI voices. The editor no longer asks for voice names and Test reports how many voices the service offers. - Custom voices are multilingual (lang `mul`): the picked voice is remembered and used for every language. Before, a pick never took effect and the first voice always spoke. Readest Voice: - Listed for every reader: `GET /api/tts/readest?all=1` returns the whole catalog with each voice's tier, and voices the reader's plan lacks are shown disabled. Without `all` the route answers released apps as before. - Treated as always on: listing reads the catalog only and never checks the voice worker, and the app answers from the last list it received, refreshing it in the background, so a failed or slow request never hides the engine. - A voice the plan lacks is never picked automatically, even a remembered one. Plus voices list before Pro ones, each by name. - Dev builds use the production API for Readest Voice, which a local server cannot serve. Voice picker: - Groups ordered custom services, Readest Voice, Edge TTS, system, Web (after a book's own narration). - An accordion: at most one group open, starting on the group of the voice in use, which stays marked and named while folded. The sheet keeps one height while folding. - Badges (Plus, Pro, Multilingual, Expressive) align to the row end; Edge's Multilingual/Expressive suffixes become badges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(tts): a Readest voice the plan lacks leads to the upgrade Tapping a greyed-out Readest voice opens the plans on the user page, or sign-in for a signed-out reader, instead of doing nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(tts): list a custom service's voices by the book language Kokoro names its voices by language (af_ American English, zf_ Mandarin, ...): those voices are offered only for books in their language, while a voice without one (OpenAI's) still reads any language. A voice list that states a language (lang or language) is used as given. A remembered custom voice yields to the default engine for a book none of its service's voices can read, as Readest Voice does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tts): sync a cleared custom TTS key and pick voices across services - A cleared API key is saved as '' rather than undefined, so it syncs and other devices drop their copy instead of keeping the old key. - The fallback voice for a language is looked up across every voice group, not only the first: a custom service without a voice for the book's language no longer hides one another service has. - The auth page browser test mocks the new getReadestVoiceAPIBaseUrl. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tts): Readest Voice is available to every reader The engine's init reported success only when the plan unlocked a voice, so signed-out and free readers lost the whole engine. It now always initializes; a voice the plan lacks stays listed but disabled and is gated where it is picked or played (setVoice, setLang, the language fallback, and the server). Opening the picker warms a worker only for a reader with a playable Readest voice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
8076905ce5
|
feat(translation): custom translation providers with a prompt library (#6582)
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 / 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 / test_web_app (2) (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
* feat(translation): custom translation providers with a prompt library
Users can add their own translation backends and use them anywhere Readest
translates (inline translation, the translator popup, the updater):
- OpenAI-compatible LLM (OpenAI, DeepSeek, OpenRouter, SiliconFlow, Gemini,
Ollama, LM Studio, ...): base URL + key + model. Concurrent paragraph
requests are coalesced into numbered batches; a reply with the wrong block
count falls back to one request per paragraph. Reasoning blocks are stripped.
- DeepL with the user's own Free/Pro key (app only; DeepL sends no CORS
headers).
AI translators use a prompt library: a built-in Default prompt plus named
user prompts with {{sourceLang}} {{targetLang}} {{bookTitle}} {{bookAuthor}}
placeholders, chosen per book. Output-format rules are appended by code, and
the cache key folds in the model and the rendered prompt so edits yield fresh
translations.
Requests go straight from the device through getAIFetch; custom providers
never touch the Readest translation quota. Providers and prompts sync as the
custom_translator / translation_prompt replica kinds under one "Translators"
category, with apiKey encrypted; backups strip the key unless credentials are
included.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(translation): address review on custom translators
- Strip only a leading <think> block so a quoted </think> survives.
- Make the DeepL 429 retry wait abortable and cap Retry-After at 10s.
- Associate the editor labels with their inputs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(translation): load the AI SDK lazily in the custom LLM translator
The reader imports the translator registry unconditionally, and the AI SDK
pulls in Node-only modules at import time, which broke the browser test that
imports useTextTranslation. Load ai + @ai-sdk/openai-compatible once, on
first use. Also drop the DeepL retry-wait abort listener once the wait ends.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(translation): stop the LLM request timeout once the reply arrives
tauriFetch cancels its request from the signal's abort listener and leaves
that call's rejection unhandled. With AbortSignal.timeout, the timer fired
60 s after every finished request and raised "The resource id ... is
invalid". The timeout is now a cleared timer on an AbortController.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(translation): make custom translators a premium feature
Custom translators follow the other premium features (isCustomizationAllowed:
Plus, Pro, Full Customization, or a self-hosted deployment). The check reads
the session token, so a reader never treats a premium user as free while the
plan loads.
- Settings: the Custom Translators row shows a Premium badge and routes free
users to the plans page and signed-out users to sign-in.
- Runtime: custom providers carry premiumRequired; isTranslatorAvailable
excludes them without premium, so inline translation, the popup and the
updater fall back to a built-in provider. The dropdowns list them as
"Name (Premium)", disabled, and the Prompt row is hidden.
- NavigationRow gains an optional badge.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(translation): customizable font, style, size and color for translated text
Language settings gain a Translated Text group: Font (the book's, or the
reader's serif, sans-serif or monospace font), Font Style (normal, italic,
bold, bold italic), Font Size (relative to the paragraph) and Text Color.
The rules go on .translation-target-block, so translated TOC entries keep
their look, and the defaults leave translations styled like the book.
The color is saved when the picker closes, not on every drag tick, and the
settings are not rewritten for a profile saved before these keys existed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(translation): give the popup layout browser test a decodable token
The premium check for custom translators decodes the session token, and
'test-token' is not a JWT.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(translation): relabel the popup's providers when the session changes
The popup derived provider labels and disabled flags only when the
translator list changed, so a sign-in or a token refresh that changed
premium eligibility left "(Premium)" or "(Login Required)" stale.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(translation): accept batch markers followed by text on the same line
Small local models such as gemma3 reply "[1]Translation…" instead of
putting the marker on its own line. The strict split rejected every such
batch and re-sent each paragraph on its own, so a batch cost one wasted
request. The block count and 1..n order checks still guard the split.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(translation): start translating when it is switched on in Settings
The reader's translation hook only re-runs when the viewSettings object
changes. Settings saved Enable Translation in place, so the book stayed
untranslated until it was reopened. Publish a new object, as the toolbar
toggle and the provider and prompt selects already do.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* perf(translation): batch 4 paragraphs per LLM request, 4 requests in flight
Measured against deepseek-flash and a local gemma3 with the reader's
scheduling on 16 paragraphs: batches of up to 8 with 2 in flight made the
first paragraph wait 2-4x longer than smaller batches, while total time
was unchanged and smaller batches cost only a few percent more prompt
tokens. 4 x 4 roughly halves the wait for the first translation and keeps
half of batching's request savings for rate-limited free tiers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(sync): allow the custom_translator and translation_prompt replica kinds in the database
The replica API accepted the two new kinds, but the replicas_kind_allowlist
CHECK did not, so every pushed row would have failed to insert. Migration
025 extends the CHECK (NOT VALID, then VALIDATE, as in 023), and a test now
fails when KIND_ALLOWLIST holds a kind the latest migration does not.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
9703d46113
|
feat(crosspoint): plugin updates, version display, and sync for optimized EPUBs (#6592)
* feat(crosspoint): check for plugin updates from the web settings card The Readest card on CrossPoint's web Settings page shows the installed plugin version and a Check for update button. Like the KOReader plugin, it reads latest.json from download.readest.com through the device relay. Update streams the release zip to the SD card, unpacks it with the JSZip the device already serves, and writes each file into the plugin's folder, manifest.json last, so an update cut short is offered again. CrossPoint never shows a plugin's version on the reader, so the release job now stamps it at the start of device.json's description, which the reader's plugin list shows under Readest. The committed manifest version becomes 0.0.1, so a copy made from the repo is offered the release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(crosspoint): keep syncing books rewritten by Optimize EPUB CrossPoint's File Manager can optimize an EPUB on upload. That rewrites the file, so its KOReader partial MD5 no longer matches the Readest book, and progress sync and reading statistics lost track of it. Sign-in now turns on KOReader Sync's Send metadata, so progress uploads carry the book's title and authors. An upload under an unknown document id links it to the one library EPUB with that title (the first author breaks ties), stored in the new crosspoint_documents table (migration 025), without moving Readest's position back on that first upload. Progress reads, progress uploads and reading sessions then follow the link. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(crosspoint): fail instead of syncing a copy under its own id on a database error A failed link lookup, library query or link write counted as "not linked", so a linked copy's reading session was recorded under the copy's own hash, a progress read answered 404, and a progress upload was saved under the copy's hash and acknowledged. The link helpers now report the error like a query, and the routes answer 500 so the reader retries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(crosspoint): compare every library book with a copy's title The title lookup stopped at 20 rows in no particular order, so with more books sharing a title it could miss Readest's own file or a second book that fits, and link a copy it should have left alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
54c089f362
|
feat(crosspoint): Readest plugin for CrossPoint e-readers (#6547)
* feat: Readest plugin for CrossPoint e-readers Adds an SD-card plugin for CrossPoint firmware (Xteink X3/X4) that signs in to Readest from the reader's web settings page, lets the reader browse, search and download the EPUBs in the user's Readest cloud library, and adds each on-device reading session to Readest reading statistics. The device pages its catalog by number, so a new GET /api/library/books lists the caller's uploaded EPUBs a page at a time. It returns one lookahead row past per_page: CrossPoint requests page_size + 1 rows and drops the last one, so stepping pages by the requested row count would skip a book per page. Each item links to the existing /api/storage/download route. The firmware renews tokens with a password grant, so the password is stored on the SD card, JSON-escaped for the firmware's raw template substitution and kept in dotfiles the reader's web server refuses to serve. Reading sessions post statPages only, keyed by the partial MD5 the firmware already computes, which is the book_hash Readest uses. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(crosspoint): sync reading progress through CrossPoint's KOReader Sync Readest now acts as the KOSync server for the CrossPoint plugin, so reading progress syncs between CrossPoint and Readest without configuring a sync server. Signing in on the plugin's card mints a per-device key and points the reader's built-in KOReader Sync at /api/crosspoint with binary document matching, so books match by the partial MD5 Readest uses as book_hash. The KOSync-compatible routes read and write the same book_configs row the apps already sync: a push stores the XPointer, scaled progress and a fresh updated_at, and keeps the library row's progress current like /api/sync; a pull returns the XPointer Readest last synced. Readest apps apply it when they open the book. Device keys live in a new table (migration 024), stored as sha256 of the md5 KOSync clients send, readable only by the service role. The reader's web API never returns the KOSync password, so the plugin keeps the key's random id in its non-secret account file and revokes by id at sign-out. Sign-out only clears KOReader Sync settings that still point at Readest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(crosspoint): ask before replacing a KOReader Sync server, email username The plugin card gains a "Sync reading progress" checkbox. It starts on when KOReader Sync isn't set up on the reader or already points at Readest, so the default stays zero-config, and off when the user set up another server, naming that server. Signing in with it off leaves KOReader Sync alone (and revokes this reader's key if it had one); sign-out shares the same logic. The KOSync username is now the account email, a label for the reader's settings: the server authenticates a device by its key alone, so the setting stays readable and survives an email change. key_hash becomes unique. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(crosspoint): sign readers in with a device code and a per-device key The plugin stored the account password on the SD card, and anyone on the reader's network could rewrite device.json through the device's unauthenticated plugin-fs endpoint to send that password elsewhere. Readers now sign in with a code their owner approves on the new /link page and get their own revocable key, never a password. The key authenticates the catalog, downloads, reading sessions and KOReader Sync, under /api/crosspoint. - Device sign-in: /device/code, /device/token and /device/approve, an OAuth device grant. The reader shows the code and a QR of the link; the plugin's web card runs the same flow and also points KOReader Sync at Readest. - Reading sessions are spread over the pages they covered in the book's Readest page count, or in 1% steps until a Readest app paginates the book. Reading-speed estimates leave out events longer than a page visit. Unrecordable sessions are acknowledged rather than refused, since the reader's event queue stops at the first failed delivery. - Progress pushes keep the percentage for unpaginated books, never overwrite a newer config, and never pull back a position the reader has not seen. Key lookup failures are server errors, not 401s. - The plugin records keys before handing them out, retries revocations that failed, revokes before clearing the card at sign-out, and serializes sign-in and sign-out. - Catalog: stable order by date added, literal search, clamped paging, and titles that can be saved as file names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(crosspoint): keep an approved sign-in when minting its key fails, list untitled books - device/token claimed the approved code before inserting the key, so a failed insert threw the approval away and the owner had to start over. The claimed row now goes back on failure. - books.title is nullable; an untitled book made the whole catalog page fail. It is listed under its hash instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci(release): attach the CrossPoint plugin zip to releases Like the calibre and KOReader plugins: stamp the release version into manifest.json and upload Readest-<version>.crosspoint-plugin.zip, which holds the readest/ folder to copy to the SD card, with the install guide inside it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
63bb079760
|
feat(library): add configurable bookshelves (#6329)
* feat(library): add configurable bookshelves and migrate preferences * fix(bookshelves): harden offline persistence and replica sync * fix(library): refine bookshelf editing layout and selection * i18n: translate bookshelf management across all locales * docs: document bookshelf behavior and review fixes * docs: clarify missing values in bookshelf filters * fix(bookshelves): address CI and sync review feedback |
||
|
|
05e8bd4523
|
docker: pull minio images from quay.io, Docker Hub removed them (#6196)
minio/minio and minio/mc 404 on Docker Hub now (MinIO discontinued free Docker Hub distribution, pushing toward their paid AIStor product) - docker pull fails with "repository does not exist or may require 'docker login'", which reads like an auth problem but isn't (confirmed: neither a fresh Docker Hub login nor a specific pinned version tag helps, since the repo itself is gone). quay.io/minio/minio and quay.io/minio/mc still work, no login needed. Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
731b13ab6f
|
fix(docker): unbreak large uploads and self-hosted cloud sync (#6100)
* fix(web): stop truncating request bodies over 10MB (#6091) `middleware.ts` matches /api/*, so Next buffers a clone of every non-GET request body. Past `experimental.proxyClientMaxBodySize` (10MB by default) `getCloneableBody` pushes null into both the middleware's stream and the one `finalize()` splices back over the IncomingMessage, so the route handler sees a short body ending cleanly: no error, no 413, just a stored file of exactly 10,485,760 bytes. `/api/send/inbox/file` accepts 40MB, so an inbox EPUB over 10MB was already being stored corrupt. The clone is buffered in memory before any handler can reject it, which makes the ceiling an unauthenticated memory budget on every /api/* route. Only the self-hosted image, which may proxy whole book files through the Node server, gets real headroom; `standaloneOutput` is the gate because BUILD_STANDALONE is set by the Dockerfile alone and web.readest.com runs on Cloudflare/Vercel. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(settings): stop gating cloud sync as Premium when self-hosted (#6093) Two causes of the same symptom on a self-hosted Docker deployment. The badge keyed off sign-in, not entitlement: !user || (userProfilePlan !== undefined && !isCloudSyncPremium) `!user` short-circuits, so a signed-out self-hoster — the normal state right after `docker compose up` — got a Premium chip on WebDAV, Google Drive, S3 and OneDrive. The rows opened fine and sync was never paused, but the chip reads as "not available in this deployment". `shouldShowCloudProviderBadge` decides on entitlement instead: self-hosting unlocks with or without a signed-in user. `SELF_HOSTED` also only reached the container through `compose.yaml` (`${SELF_HOSTED:-true}`), which landed in #5996. A compose file copied before that survives every `docker compose pull`, so those deployments came up gated with nothing on screen to explain why. The image now defaults it on: it is the self-hosted artifact, web.readest.com never runs it, and an operator selling plans still overrides with SELF_HOSTED=false. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs(settings): clarify that the tier chip still gates signed-out visitors The doc comment described what changed rather than what the predicate does, so "entitlement is the deciding input, not sign-in state" read as if signed-out users stopped being gated. They are not: a signed-out visitor to a hosted deployment is not entitled, so the row is badged and stays behind canToggleCloudProvider and the upgrade route, exactly as before. Only entitlement — which self-hosting confers — removes the chip. Assert the pairing in one test so a future refactor cannot decouple the badge from the gate. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
b80d83534e
|
feat(payments): separate storage and customization entitlements, unlock all when self-hosted (#5996)
* feat(payments): gate premium features on Full Customization Premium access was any of plus, pro or purchase, and `getUserProfilePlan` reports `purchase` for anyone holding ANY one-time purchase, which is how a storage add-on presents. Buying space therefore unlocked cloud sync, TTS download and Send to Readest as a side effect. Route every premium gate through one predicate: a paid subscription, an outright Full Customization unlock, or a self-hosted deployment. `PREMIUM_PLANS` is plus and pro only; `purchase` is deliberately absent, because that is exactly the value a storage-only buyer reports. * isCloudSyncAllowed, isTTSCacheAllowed and isEmailInPlan now take the customization claim and delegate to isCustomizationAllowed. Both server routes under pages/api/send move with them, so the client and the server cannot disagree about who is entitled. * Self-hosted deployments unlock everything, signed in or not. There is no store to buy from and the operator already runs the infrastructure the paywall funds. SELF_HOSTED is wired through runtimeConfig the same way STORAGE_FIXED_QUOTA is, and defaults to true in docker. * STORAGE_GRANTS_CUSTOMIZATION keeps storage add-ons unlocking customization during the launch grace period. It drives a durable payment row rather than a derived rule, so switching it off cannot revoke anyone who bought while it was on: updateUserStorage is the only writer of customization_purchased and reruns on every later purchase. Recording the grant never fails the purchase it rides on. * Google Play acknowledges a permanent unlock instead of consuming it. Consuming is what lets a SKU be rebought, which storage needs and an unlock must not have. isConsumablePurchase is an allowlist: an unrecognised product that cannot be repurchased is caught in testing, while wrongly consuming an unlock costs a user real money. It is still acknowledged, or Play auto-refunds after three days. * The Lifetime card shows Full Customization as unlocked once owned, reusing the Current Plan chip so the card footers stay aligned. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(payments): clear the customization entitlement on sign-out Three review findings. The module-level entitlement cache survived a sign-out. `useQuotaStats` returned early when there was no user or token, so nothing reset it, and `resolveCloudSyncGate` reads it synchronously for non-React gates: a signed-out session could still be treated as premium. Clear both caches on that path, falling back to the restrictive side, which is how these caches are already documented to behave before the first auth resolution. `customizationPurchased` is now derived from the token rather than held in state. State lags a render behind a token change, which briefly reported the previous account's entitlement after a switch. `SELF_HOSTED` set to an empty string masked `NEXT_PUBLIC_SELF_HOSTED`, because `??` only falls back on null or undefined, silently re-locking a self-hosted deployment. Use `||` in both `isSelfHosted` and `getServerRuntimeConfig`. The Arabic and Turkish `Unlocked` strings inherited "open" from the longer "Unlock All Customization Options" phrase, which reads as "opened" when the word stands alone on a status chip. The remaining locales keep their established verb deliberately. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(payments): cover the real sign-out path for the entitlement caches The existing test called setCachedCustomizationPurchased directly, so it pinned the wiring between the cache and the gate but never ran the cleanup in useQuotaStats. Deleting that cleanup would have left it green, which is exactly the regression it was meant to catch. Drive the hook through renderHook instead: render with a session, then rerender without one, and assert both caches are cleared and the derived value flips in the same pass. Verified by removing the cleanup and confirming the test fails, then restoring it. The cache-to-gate wiring test stays; it covers a different link. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
6834ee42ef
|
fix(stats): survive PostgREST's row cap when building archive segments (#5844)
* fix(stats): survive PostgREST's row cap when building archive segments stat_archive_rows is called through PostgREST, which caps every response at db-max-rows (1000 on Supabase). The LIMIT 10000 never survived the wire, so segments silently held 1000 rows, and the truncation could cut inside a run of rows sharing one updated_at (a push chunk shares one now()): the commit's range delete then removed rows that were never archived, surfacing as commit_mismatches during validation. Migration 021 makes the pair loss-proof under any proxy truncation: stat_archive_rows trims the trailing millisecond unless the page provably holds every row of it (whole-millisecond extension only for the single-millisecond page), so every result ends at a complete millisecond; and stat_archive_commit refuses with P0001, rolling back the manifest insert and the delete, when the range's delete count differs from the declared segment row count. The compact route now assembles each segment from sub-pages of at most 1000 rows, advancing p_from per sub-page until STATS_COMPACT_SEGMENT_ROWS or a drained user (only an empty page means drained; a short page can just mean the trailing millisecond was trimmed), writing one object and one commit per assembled segment, and counting a refused commit as a mismatch plus an error. The verification script applies 021 and asserts the trim, the equal-timestamp run, the covered-millisecond keep, the single-millisecond extension and the refusal rollback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(stats): keyset-paginate archive rows so no proxy row cap can wedge or lose data Review found the remaining hole in the trim design: a millisecond holding more rows than db-max-rows made the single-millisecond fallback return more than p_limit, PostgREST truncated it to the same first 1000 rows every time, the cursor stopped advancing and the sub-page loop repeated the identical page forever (or, cut differently, produced a refused commit). A restore can create such a millisecond: it re-inserts 500-row chunks, each stamping one now(). stat_archive_rows is now a plain keyset pager over (updated_at, book_hash, page, start_time) with three tie-cursor parameters (the 020 signature is dropped). Keyset pages are truncation-proof by construction: any cap only shortens a page, the cursor comes from rows actually received, and the tie columns paginate inside a millisecond of any size. The compaction route owns the boundary policy: assemble pages until the segment target plus a complete millisecond to cut at (or a drained user), trim the trailing millisecond unless it is provably closed (drained and ended at least 60 s before the window cutoff), defer a user whose only eligible rows sit in a still-fresh millisecond, and hard-stop a pathological millisecond beyond 50k rows. Regression tests: 1001 equal-timestamp rows in one millisecond become one segment with no repeated page and no refused commit; a mid-millisecond target cut trims and the next segment refetches the remainder; a still-fresh millisecond defers the user. The SQL script asserts keyset tiling, the tie-cursor resume inside an equal-timestamp run, and the refusal rollback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
9b33b52a40
|
feat(stats): tier stat_pages history into R2 segments behind a 7-day hot window (#5835)
* feat(stats): tier stat_pages history into R2 segments behind a 7-day hot window
stat_pages is an append-only per-user log of page events merged by longest
duration; the server never reads history for analytics and devices union-merge
everything locally, so keeping the whole history in Postgres is the most
expensive way to store it.
Migration 020 adds a second tier. Postgres keeps a hot window (updated_at
younger than 7 days by default); a cron job (POST /api/stats/compact, driven
by a scheduled() handler in a custom OpenNext worker entry) compacts older
rows per user into immutable JSON segments in R2, listed in the stat_archives
manifest. The commit RPC inserts the manifest row and deletes exactly the
archived (from, to] range in one transaction, compare-and-set on the user's
archived_to under a per-user advisory lock; segments never split a
millisecond, and objects are never deleted by the compaction path.
The stats pull composes pages server-side: hot rows are read before the
manifest (a concurrent commit can only duplicate, never lose), then the first
segment that still has rows past the cursor is served (paged, trailing
millisecond completed) or the hot rows; unpaginated pulls get every segment
then hot rows. The sync API, the app and the koplugin are unchanged.
Also: POST /api/stats/restore (rollback, re-inserts a user's segments through
upsert_stat_pages_as and drops the manifest rows; refuses while compaction is
enabled), account deletion removes the user's archive objects before the auth
user, a local PostgreSQL 15 verification script for the migration, and
docs/stats-archive.md. Ships disabled (STATS_COMPACT_ENABLED = "false").
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(stats): record one Analytics Engine point per archive-backed stats pull
Hot-only pulls write nothing; a pull that reads R2 segments writes one point
(indexes ['pull'], blobs ['paged'|'full'], doubles [segments_read, rows,
limit]) to STATS_COMPACT_AE. The share of pulls that reach the archive is the
number that should drive STATS_COMPACT_WINDOW_DAYS; we ship with 7 days.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* feat(stats): targeted compaction run for one user, plus the deployment runbook
POST /api/stats/compact with a JSON body {"user_id"} compacts that user only:
no claiming, the enabled flag is ignored (operator action, usable while the
cron is off) and the batching thresholds are ignored (everything older than
the window is archived). Still token-guarded; malformed ids answer 400. This
is what lets the rollout validate on a known account in production before the
cron is enabled, and drain one heavy user by hand.
docs/stats-archive.md gains the step-by-step deployment guide: migration
check queries, bucket and secret creation, disabled deploy and its checks,
validation on one account (targeted run, manifest/object checks, fresh pull
on a device or through the API, optional restore), enabling the cron, the
Analytics Engine and Postgres checks to watch, the post-drain REINDEX, and
the window revisit.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(stats): address review on the archive tier
- Account deletion: delete the identity first, then queue the user id in a
new service-role-only stat_archive_orphans table and delete the R2 prefix
best-effort; batch compaction runs sweep the queue (kill switch on or off)
until each prefix lists empty. Deleting objects before a failed deleteUser
would have left an active account with its history gone.
- stat_archive_state and stat_archive_orphans: RLS enabled and privileges
revoked from PUBLIC/anon/authenticated so PostgREST does not expose them;
the verify script asserts relrowsecurity on all three tables and that
anon/authenticated cannot read the service-role-only ones.
- Compact route: only an empty body is the cron's batch request; every other
body must be a valid {user_id} targeted request or it is a 400, so a typo
never starts a batch run. Guard: 503 (no token/bucket), 401, then the
kill switch, applied by the route after the orphan sweep.
- Paged stats pull fills a page across tiers: segments are read lazily until
they fill the page, short archive pages are topped up with hot rows and
the page is cut at limit with the trailing millisecond kept, so a client
that stops on a short page (the koplugin) never stalls on a tier boundary.
- Restore reads the manifest page by page (PostgREST caps responses at 1000
rows) until it is empty.
- Config knobs reject digit strings beyond the safe integer range.
- worker.ts logs a rejected cron fetch; the [limits] cpu_ms block is dropped
(the job is I/O-bound and the ceiling would apply to every request).
- Tests: PostgREST mocks now apply eq/gt filters and honor range/delete so
the query contract is exercised; rpcMock is cleared between tests.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(stats): refresh the compact route header comment for the reworked guard order
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(stats): address review round 2 on the archive tier
- The stats pull reads the stat_archives manifest in range pages (PostgREST
caps a response at 1000 rows) and appends hot rows only once a short final
page proves no archived rows remain past the cursor; a paged pull stops
fetching manifest pages as soon as its response page is full. A truncated
manifest list could otherwise let a client cursor skip segments. Regression
test with 1001 single-row segments, unpaginated and paged.
- Account deletion writes the stat_archive_orphans tombstone BEFORE anything
destructive and stops with 500 (retryable) if even that fails; a failed
deleteUser compensates the tombstone; the orphan sweep additionally skips,
keeping the row, any queued user that still exists, so a stale tombstone can
never wipe a living account.
- The compaction loop asserts each segment boundary advances past the previous
millisecond before writing the object. stat_archive_rows extends every
segment to the end of its last millisecond, so consecutive segments cannot
share an ms-keyed object name; the assertion turns a future SQL regression
into a loud per-user error instead of a silent object overwrite.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
71b07b44ff
|
perf(sync): merge stat_pages pushes in one upsert_stat_pages RPC (#5832)
The stats push fetched the batch's existing rows (user_id = ?, book_hash IN, start_time IN), decided longer-duration-wins in JS, then upserted in a second round trip. That lookup ran about 9 req/s in production (17% of DB time) and on PG 15 re-walks the whole (user_id, book_hash) primary-key range once per start_time array element, because start_time sits after the unconstrained page column of the PK. Migration 019 adds public.upsert_stat_pages(jsonb): a single INSERT ... ON CONFLICT DO UPDATE ... WHERE EXCLUDED.duration > stat_pages.duration that probes the PK exactly, collapses duplicate keys inside a batch to the longest duration, stamps user_id from auth.uid() and updated_at from now(), and runs SECURITY INVOKER so the stat_pages RLS policies stay in force. The push handler now calls the RPC per 500-row chunk; pickWinningPages is gone. Deploy order: apply migration 019 before deploying this API change. Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
73e933eb33
|
fix(docker): apply db migrations on first boot and let the font CDN be overridden (#5550) (#5551)
* fix(docker): apply db migrations on first boot and let the font CDN be overridden (#5550) A fresh self-hosted stack only ran volumes/db/init/schema.sql, so the incremental files under volumes/db/migrations never reached the database. Deployments came up without files.replica_id, the replicas table and the claim_inbox_item RPC, which broke uploads, replica sync and Send to Readest. Mount the migrations directory into the db container together with an apply-migrations.sh hook named so it sorts after the supabase image's own migrate.sh. It globs the mounted directory, so a new migration file needs no compose change, and it records what it applied in readest_meta.migrations so it can be re-run by hand after an upgrade. The reader also loaded its CJK webfont bundles from storage.readest.com, which only sends CORS headers for readest.com origins, so they were blocked on a custom domain. Read the base URL from runtime config via FONT_BASE_URL and keep the CDN as the default. Let SUPABASE_PUBLIC_URL and S3_PUBLIC_ENDPOINT be set directly instead of only being derived from HOST_IP, so the stack can be served from one HTTPS origin. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs(docker): add an example nginx config for a single HTTPS origin Keeps the template out of the README as a copyable file next to .env.example. Routes / to the client, /auth/v1 and /rest/v1 to kong, and the bucket prefix to minio with the Host header preserved so presigned signatures still verify. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
35b02c4efc
|
feat(statistics): KOReader-compatible reading stats with cross-device sync (#4606)
Supersedes #3156. Adds a reading-statistics system whose canonical data model is KOReader's own (book + page_stat_data), so stats round-trip losslessly between Readest and KOReader. - Storage: a cross-platform Turso statistics.db in KOReader's exact schema (web/Workers, desktop, iOS, Android) — replacing #3156's Node-only better-sqlite3 + statistics.json. - Tracking: per-page reading events (time-on-page, idle-capped) flushed on page-change/idle/hide/close — the KOReader model — not session aggregates. - Sync: legacy /api/sync extended with a stats type backed by self-contained Supabase tables (stat_books, stat_pages); union/longer-duration-wins merge keyed on book_hash. apps/readest.koplugin syncs through the same endpoint. - Scale & robustness: per-tab singleton connection (avoids OPFS lock conflicts) + explicit WAL checkpoint; transactional bulk apply; chunked resumable push; client-driven paged pull with trailing-ms completion; paginated/scoped server merge. Verified: 5668 unit tests, 155 koplugin busted tests, biome+tsgo + luacheck all green; web OPFS DB verified live. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
b8d986cbd6
|
fix(docker): fix Docker image latest tag and production runtime errors; add dev compose file, Codespace support, and semver release tagging (#7) (#4277)
* fix: also tag Docker image as latest on main branch push Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/bbc0f66e-7488-4d9d-976b-434588b3faa8 * fix: production Dockerfile missing patches/.env.web; add compose.dev.yaml for dev hot-reload Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/e27bba4e-b8ea-4694-b44d-6308aa778d41 * fix: add devcontainer to init submodules; add clear Dockerfile error when submodules missing Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/16d24ae0-d2e8-4523-b47e-4969dd587c50 * simplify production-stage: COPY --from=build /app /app instead of selective copies Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/356fabe4-f944-48b6-a409-41640480d52f * fix: add CI=true to dev compose to prevent pnpm no-TTY abort Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/ddc30fef-2c76-452d-aad6-d688ca912a1a * fix: add semver Docker image version tags on release Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/18cbc3c6-ba92-4e63-bef9-93dcf6698c21 --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> |
||
|
|
9ad43aa8b2
|
feat(docker): add GHCR and Docker Hub image publishing (#4250)
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 / publish (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 (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 GHCR and Docker Hub image publishing with fully runtime-configurable pull-first Docker setup (#1) * feat: add container image publishing workflow and pull-based compose setup Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/23c31167-9e15-4d44-ab89-f267b8cd6304 * refine docker publishing workflow and pull-first compose docs Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/23c31167-9e15-4d44-ab89-f267b8cd6304 * chore: temporarily expose docker publish run results for pr branch Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/c946a2f2-2219-4dea-a829-61b287bc4859 * fix: update pinned SHAs for setup-qemu-action and setup-buildx-action to v3 heads Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/0db6957e-476b-48e0-acf3-bee6964c3b32 Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * chore: switch all workflow action refs from SHA pins to stable version tags Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/19334b37-9b4c-45df-9c3c-81a497cef8e8 Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * fix: restore missing `with:` blocks lost during SHA-to-tag substitution Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/f204f742-5b7d-4f05-9647-03b9db86ea3d Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * fix(ci): checkout submodules for docker image workflow Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/72309e8a-6c7c-4004-902a-565f67e5c15f Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * Apply suggestions from code review Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * feat(docker): support runtime client env for pulled web image * refactor(web): serve runtime config via script endpoint * fix(web): escape runtime config script payload * fix: align docker runtime config with internal/public backend urls Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/3bbcb608-6202-4f9e-b288-5c95a259da93 Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * chore: align published workflow tags with docs * docs: clarify runtime config precedence and linux host mapping Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/3bbcb608-6202-4f9e-b288-5c95a259da93 * refactor: move storage/quota config from build args to runtime env Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/da9b749e-0b1c-47b9-b474-5009765b6ea6 Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * fix: load runtime config in pages router app shell Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/b375132c-8317-4c98-b437-ae48c0153e3d Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * fix: apply biome formatting for runtime config quota helpers Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/778f5d75-884e-401b-b7cb-4ab40bc64a11 Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> Co-authored-by: Amir Pourmand <pourmand1376@gmail.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * fix: S3_PUBLIC_ENDPOINT, _document.tsx for beforeInteractive, runtimeConfig fallbacks, README port (#2) Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/4f92f818-c008-4caa-9684-d530500b5fb2 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> * fix: reformat runtimeConfig.ts to satisfy biome formatter (#3) Agent-Logs-Url: https://github.com/pourmand1376/readest/sessions/4eea77f4-67ab-4428-b59e-0b21be988037 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: pourmand1376 <32064808+pourmand1376@users.noreply.github.com> --------- Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> |
||
|
|
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. |
||
|
|
0b18de0581
|
feat(send): Send to Readest — multi-channel capture into your library (#4230)
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
PR checks / test_web_app (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / rust_lint (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(send): Send to Readest — multi-channel capture into your library A Send-to-Kindle equivalent: email, web-upload, share, or one-click capture books and articles into the cloud library; they sync to every device. Architecture (client-side processing): out-of-app channels drop a raw payload into a per-user send_inbox; Readest clients drain it through one shared ingestService.ingestFile(). The server never parses or converts. - ingestService.ingestFile() — channel-agnostic import orchestration extracted from library/page.tsx (DI-based, forceUpload support). - send_addresses / send_allowed_senders / send_inbox tables + RLS + 4 SECURITY DEFINER claim/lease RPCs (migration 012_send_to_readest.sql). - Conversion subsystem (DOCX/RTF/HTML/article/TXT -> EPUB) in a Web Worker. - send-email Cloudflare Email Worker; inbox-drainer controller + useInboxDrainer hook; /api/send/* routes. - Send to Readest settings panel: inbound address, approved-sender allowlist, recent activity, per-device drain toggle. - /send web page (file drop + article URL) + SSRF-guarded fetch-url proxy. - OS-shared files routed through ingestFile; Manifest V3 browser extension. Security: inbox state changes only via SECURITY DEFINER RPCs (clients get SELECT-only on send_inbox); approved-sender allowlist gates email; SSRF guard on the one server-side URL fetch; inbox payload signed URLs authorize against send_inbox.user_id. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: run format:check in the pre-push hook Biome format checking is fast (~0.4s), so gate pushes on it too — catches mis-formatted files that bypassed the staged-only pre-commit hook before they reach CI. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(send): address CodeQL security findings - ReDoS (senders.ts): the email regex had ambiguous quantifiers around the literal dot. Rewrote it linear-time (domain labels exclude '.') and cap the input at 254 chars. - XSS (convertToEpub.ts): run untrusted HTML through DOMPurify (sanitizeForParsing — keeps document structure) before DOMParser, so title extraction and Readability never parse executable markup. - SSRF (fetch-url.ts): harden the host guard — block bare single-label hostnames, IPv4-mapped IPv6, CGNAT/benchmark/multicast ranges, and the unspecified address. DNS rebinding stays a documented residual risk. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
6e7c9d1395
|
feat(sync): bundled settings replica kind for cross-device prefs and credentials (#4094)
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
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): add bundled `settings` replica kind for cross-device prefs and credentials Adds a single-row `settings` replica that syncs a whitelist of `SystemSettings` fields across devices via per-field LWW (one entry per dot-namespaced path). Plaintext for theme / highlight colour / TTS configuration; encrypted (AES-GCM under the user's sync passphrase) for kosync / Readwise / Hardcover credentials. Highlights: - Push-side diff against an in-memory snapshot for plaintext paths and a localStorage SHA-256 hash for encrypted paths, so a refresh doesn't re-publish or re-prompt for the passphrase. - Pull-side cipher-fingerprint dedupe + per-row passphrase gate; decryption failures surface as toasts (wrong passphrase / orphan cipher) instead of silent drops. - Auto-recovery for orphaned ciphers: when a row references a saltId no longer in `replica_keys`, clear the local hash and re-encrypt under the current salt on the next save. - Single in-flight `/sync/replica-keys` fetch with a value cache to coalesce the boot-time burst of concurrent unlock callers. * fix(sync): guard settings dot-path helpers against prototype-polluting keys Reject `__proto__`, `constructor`, and `prototype` segments in the settings adapter's `readPath` / `writePath`. Every caller currently passes a constant from `SETTINGS_WHITELIST`, so the guard is purely defensive — but it silences the CodeQL prototype-pollution warning on PR #4094 and keeps the helpers safe if a future call site ever forwards an untrusted path. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
712d564e9d
|
feat(sync): encrypted OPDS credentials + Tauri keychain (PR 4c + 4d) (#4090)
* feat(sync): encrypt opds_catalog credentials end-to-end (TS path) Wires encrypted-credential sync for opds_catalog via the CryptoSession shipped in PR 4a (#4084) plus a new publish/pull crypto middleware. TS-only — native still uses ephemeral storage (re-enter passphrase per launch); PR 4d wires the OS keychain. - ReplicaAdapter gains optional `encryptedFields: readonly string[]`. Adapters stay sync; the middleware handles the crypto round trip. - replicaCryptoMiddleware.ts: encryptPackedFields drops the named fields from the push when the session is locked (no plaintext leak); decryptRowFields drops them on pull failure (local plaintext preserved by the store merge). - replicaPublish / replicaPullAndApply invoke the middleware. - OPDS adapter declares encryptedFields = [username, password] and now pack/unpack them as plaintext. - passphraseGate.ts: ensurePassphraseUnlocked coalesces concurrent calls, prompts via the registered prompter with kind=setup|unlock, throws NO_PASSPHRASE on cancel. - PassphrasePromptModal mounted at the Providers root; registers itself as the gate prompter. - CryptoSession.forget() wipes server-side envelopes + salts. - Migration 010 + replica_keys_forget RPC; DELETE /api/sync/replica-keys + client wrapper. - SyncPassphraseSection on the user page: status / Set / Unlock / Lock / Forgot. - CatalogManager pre-save: ensurePassphraseUnlocked when credentials are present; user cancel saves locally without sync. Plan updated: PR 4 split documented as 4a/4b/4c/4d. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(sync): persist sync passphrase via OS keychain (Tauri) Replaces the EphemeralPassphraseStore stub on native with real OS-keychain storage so users don't re-enter their sync passphrase every launch. Web stays on the in-memory ephemeral store by design. Native bridge plugin gains 4 commands wired across all platforms: - Rust desktop (`keyring` crate): macOS Keychain on apple-native, Windows Credential Manager on windows-native, Linux libsecret/ Secret Service on sync-secret-service. Per-target features so each platform compiles only the backend it needs. - iOS Swift: Security framework Keychain (kSecClassGenericPassword, SecItemAdd / Copy / Delete). - Android Kotlin: androidx.security EncryptedSharedPreferences (AndroidKeystore-derived AES-GCM master key, AES256_SIV / AES256_GCM key/value encryption). TS layer: - TauriPassphraseStore wraps the bridge calls. set is fail-loud (surfaces keychain rejection); get is fail-soft (returns null on any error so the gate prompts). - createPassphraseStore returns ephemeral synchronously; upgradeToKeychainIfAvailable swaps the singleton to TauriPassphraseStore on Tauri after probing the bridge. CryptoSession resolves the store via createPassphraseStore() each touch so the swap is transparent. - CryptoSession.tryRestoreFromStore: silent unlock at boot. Stale- entry recovery clears the store when the account has no salt server-side. unlock/setup persist; forget also clears the store. - Providers boot effect: upgrade keychain → silent restore. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sync): make encrypted-credential pull actually decrypt + UX polish PR 4c shipped the encrypt path but the pull side silently dropped ciphers when locked, the modal was busy with double-rings, and web re-prompted on every page refresh. This rolls up the post-test fixes + UX polish: Pull-side decrypt: - decryptRowFields takes an `onLocked` callback the orchestrator wires to the passphrase gate; encountering a cipher field with a locked session now triggers the lazy-prompt path instead of dropping the field. - replicaPullAndApply re-applies the unpacked row for metadata-only kinds even when a local copy exists, so the now-decrypted creds reach the store (the binary-kind skip-if-local optimization doesn't apply). - Cipher fingerprint comparison: capture the row's `cipher.c` for each encrypted field, compare against the local record's lastSeenCipher. Same → skip prompt + decrypt entirely. Different (rotation / value change on another device) → prompt to re-decrypt. Fingerprint persists via OPDSCatalog.lastSeenCipher. Web persistence: - SessionStoragePassphraseStore: passphrase survives page refresh within the same tab, dies on tab close. Replaces EphemeralPassphraseStore as the default on web. Avoids localStorage / IndexedDB to keep the tab-scoped trust boundary. UI: - Renamed PassphrasePromptModal → PassphrasePrompt; modernized: filled input style with single subtle focus border, btn-primary + btn-ghost replaced with leaner custom buttons. eink-bordered + btn-primary classes give the dialog correct e-paper rendering. - globals.css: suppress redundant outline/box-shadow on focused text inputs / textareas (the element's own border is the focus indicator). - AGENTS.md: documents the e-ink convention (`eink-bordered`, `btn-primary` for inverted CTAs, etc.) so future widgets ship with e-paper support. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
6bfeb295d2
|
feat(sync): add opds_catalog replica kind (plaintext fields) (#4087)
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
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Wires OPDS catalogs through replica sync as a metadata-only kind.
Plaintext fields only in this PR — encrypted credentials (username,
password) ship in the follow-up alongside the SyncPassphrasePanel UI
and Tauri keychain backend.
- Migration 009 extends the kind allowlist with 'opds_catalog'.
- replicaSchemas adds opdsCatalogFieldsSchema (name, url, description,
icon, customHeaders, autoDownload, disabled, addedAt) with a 50-row
per-user cap.
- New opdsCatalogAdapter is metadata-only (no `binary` capability).
Stable cross-device id from md5("opds:" + url.lower()) so two
devices that import the same URL converge to one row instead of
duplicating.
- New customOPDSStore (zustand) hydrates from SystemSettings,
publishes upserts/deletes through the replica pipeline, preserves
local-only username/password when overlaying remote updates, and
strips tombstones at the persistence boundary so existing
useSettingsStore readers (useOPDSSubscriptions, pseStream,
app/opds/page.tsx) need no migration.
- replicaPullAndApply branches on adapter.binary so metadata-only
kinds skip the bundleDir requirement and the manifest/binary path.
- CatalogManager rewires Add / Edit / Remove / Toggle / Add-popular
through the new store.
Plan update bundled in: tenet 8 (scalar settings sync via a bundled
row; collections sync per-record), per-kind allowlist now includes a
`settings` singleton that will collapse PRs 5 + 6+ into one bundled
adapter, and PR 4 is split into 4a (already merged) / 4b (this) / 4c
(encrypted credentials + UX).
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
35227ecd61
|
feat(sync): wire crypto session for encrypted-field sync (#4084)
Adds the per-account PBKDF2 salt endpoint and an in-memory CryptoSession
that derives keys lazily per saltId. Lets future kinds (OPDS catalogs in
PR 4b) encrypt/decrypt fields without re-deriving on every operation.
- Migration 008: replica_keys_{create,list} RPCs round-trip the bytea
salt as base64; SECURITY INVOKER, RLS-gated by the existing replica_keys
policies.
- /api/sync/replica-keys GET/POST endpoint matches the dual app/pages
shape used by /api/sync/replicas.
- ReplicaSyncClient.{listReplicaKeys,createReplicaKey} wraps the endpoint.
- CryptoSession.{unlock,setup,encryptField,decryptField,lock} caches
derived keys per saltId; foreign envelopes trigger a lazy re-list +
derive. Iterations injectable so tests run with PBKDF2 ITER=1000.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
981579c255
|
feat(sync): cross-device custom font sync (#4077)
* refactor(sync): kind-agnostic replica primitives Extract dict-only sync into shared primitives (registry, pull/apply orchestrator, persist env, schema allowlist) so other kinds can plug in. Companion changes: per-replica Storage Manager grouping, useReplicaPull boot-race recovery, manifest=null reconciliation on every boot pull, copyFile takes explicit srcBase + dstBase, settled- event helpers, lenient webDownload Content-Length (R2/S3 signed URLs commonly omit it), and generic "File" transfer toast copy any replica kind can share. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(sync): cross-device custom font sync Plug the font replica adapter into the kind-agnostic primitives: font store gains replica wiring, custom font import publishes the replica row + queues a binary upload, and bootstrap registers the font adapter and download-complete handler. Includes legacy flat-path migration so pre-existing fonts sync without re-import, full @font-face activation on auto-download (load + mount the rule, mirroring manual import), and a fix to createCustomFont so contentId / bundleDir / byteSize survive the trip through addFont — otherwise import-time publish silently no-oped on missing contentId. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
cbdc3b8f52
|
feat(sync): wire dictionary store through replica sync (follow-up to #4075) (#4076)
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
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): cross-device dictionary sync
Custom MDict / StarDict / DICT / SLOB dictionaries now sync across
signed-in devices via the replica layer.
- Store mutations publish replica rows with field-level LWW + tombstones.
- Re-importing the same content (renamed or after delete) preserves the
user's label and reincarnates the server row instead of duplicating.
- Manifest commits after binary upload so other devices never see a row
whose binaries aren't on cloud storage yet.
- Pull-side orchestrator creates a placeholder dict, queues the binaries
via TransferManager, and clears the unavailable flag on completion.
- Toast copy branches by transfer kind so dict uploads don't read
"Book uploaded".
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(sync): boot pull and binary download path
- Defer the boot pull until TransferManager is initialized so download
enqueues aren't dropped.
- Auto-persist the local dict store after applyRemoteDictionary; otherwise
the next loadCustomDictionaries wipes the in-memory rows.
- Boot pull passes since=null so a device whose cursor advanced past
unpersisted rows can still recover.
- Skip pulling when not authenticated instead of logging
"SyncError: Not authenticated" on every boot of a signed-out device.
- downloadReplicaFile resolves the destination against the kind's base
dir; binaries previously landed at the literal lfp and openFile then
failed with "File not found".
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(sync): per-page useReplicaPull hook
Lifts the boot-time pull out of EnvContext into a hook each page mounts
for the kinds it needs: useReplicaPull({ kinds: ['dictionary'] }).
Library page and the shared Reader component opt in. The hook fires 10s
after page load (so feature mounts hydrate first), dedups per-kind
across navigation, and releases the slot on failure so a later mount
can retry. Future kinds plug into the hook's per-kind switch.
Also closes two refresh-loop bugs:
- Hydrate the dict store from settings BEFORE the apply loop, so the
auto-persist doesn't clobber persisted rows that the in-memory store
hadn't yet read. Library-page refresh was the visible victim.
- Skip the download queue when every manifest file is already on disk
under the resolved bundle dir. Refreshing is a no-op; partial-
download recovery still queues because some files would be missing.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
3b348c8f35
|
feat(sync): CRDT replica sync foundation (#4075)
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
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(sync): foundation for CRDT-based cross-device replica sync (Phase 1+2)
Adds the primitives and orchestration layer for syncing user-imported
assets (dictionaries, fonts, textures, OPDS catalogs, dict settings)
across devices via a polymorphic `replicas` table with field-level LWW
under HLC ordering. Phase 1 ships the foundation (CRDT, crypto, server
schemas, SQL migrations, push/pull endpoint); Phase 2 adds the adapter
registry, HTTP client, and sync manager. No modifications to existing
book sync — additive only.
Phase 1:
- src/libs/crdt.ts — HlcGenerator (monotonic + remote-absorption +
clock-regression-safe), per-field LWW with deviceId tiebreak,
remove-wins tombstones, reincarnation token revival.
- src/libs/crypto/{derive,encrypt,envelope,passphrase}.ts —
PBKDF2-600k key derivation (OWASP 2024), AES-GCM round-trip,
envelope {c,i,s,alg,h} with SHA-256 sidecar integrity check,
passphrase storage abstraction (web ephemeral; Tauri keychain stub).
- src/libs/replica-schemas.ts — Zod-backed allowlist (dictionary only
in PR 1), 64KiB row cap, 64-field cap, schemaVersion bounds,
filename validator.
- src/libs/replica-sync-server.ts — push batch validation
(auth + allowlist + schema + HLC ±60s skew clamp).
- src/pages/api/sync/replicas.ts — POST/GET endpoint wrapping the
Postgres crdt_merge_replica function via RPC.
- docker/volumes/db/migrations/003_add_replicas.sql — replicas table
+ replica_keys table + RLS.
- docker/volumes/db/migrations/004_crdt_merge_replica_fn.sql — atomic
per-field LWW merge function (forwards-compat preserves unknown
fields).
Phase 2:
- src/services/sync/replicaRegistry.ts — adapter contract
(core + optional BinaryCapability + LifecycleHooks per eng review).
- src/libs/replica-sync-client.ts — HTTP wrapper mapping status codes
to typed SyncError codes.
- src/services/sync/replicaSyncManager.ts — 5s debounced push,
immediate flush on visibilitychange/online, per-kind pull cursor,
remote HLC absorption.
Tests: 125 new (crdt 26, crypto 32, schemas 21, server 16, client 12,
registry 6, manager 12). Full suite 3656 passing, lint clean. Existing
book/config/note sync paths untouched.
Plan: ~/.claude/plans/vivid-orbiting-thimble.md
CEO plan: ~/.gstack/projects/readest-readest/ceo-plans/2026-05-06-replica-sync-cathedral.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(sync): add kind="replica" path through TransferManager (Phase 3)
Adds the replica branch to the existing book-shaped transfer
infrastructure so dictionary (and future kinds) bundles can flow through
the same queue, retry, and progress UI as book uploads.
Existing book transfer paths remain unchanged. The book-side regression
suite (37 tests in transfer-store.test.ts, 37 in transfer-manager.test.ts)
all stay green.
Store (src/store/transferStore.ts):
- TransferItem gains kind: 'book' | 'replica' (default 'book' on legacy
persisted rows), replicaKind, replicaId, replicaFiles, replicaBase.
- New addReplicaTransfer(replicaKind, replicaId, displayTitle, type, opts)
with files + base in opts; auto-computes totalBytes from file sizes.
- New getReplicaTransfer(replicaKind, replicaId, type) lookup.
- getTransferByBookHash filters to kind === 'book' (defensive against
bookHash="" collisions on replica items).
- restoreTransfers fills kind: 'book' for legacy persisted rows.
Manager (src/services/transferManager.ts):
- queueReplicaUpload / queueReplicaDownload / queueReplicaDelete.
- executeTransfer dispatches by kind to the new executeReplicaTransfer
(iterates files, calls appService.uploadReplicaFile per file with
per-file progress aggregation) or the existing executeBookTransfer
(refactored out, byte-identical behavior).
- Dispatches replica-transfer-complete event on success so stores can
react (e.g., commit manifest_jsonb to the replica row).
Storage / cloud (src/libs/storage.ts, src/services/cloudService.ts):
- uploadReplicaFile bypasses the book-only File.name smuggling and
takes an explicit cfp (cloud file path).
- uploadReplicaFileToCloud / downloadReplicaFileFromCloud /
deleteReplicaBundleFromCloud orchestrate per-file operations under
${userId}/Readest/replicas/<kind>/<replicaId>/<filename>.
- replicaCloudKey() centralizes the path-construction rule.
- New CLOUD_REPLICAS_SUBDIR constant.
App service (src/services/appService.ts, src/types/system.ts):
- AppService gains uploadReplicaFile, downloadReplicaFile,
deleteReplicaBundle (file-level operations; orchestration lives in
TransferManager).
Tests: 18 new (12 in transfer-store.test.ts, 5 in transfer-manager.test.ts,
1 fixture). Full suite 3674 passing, lint clean. Existing book regression
clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(sync): dictionary replica adapter + bootstrap (Phase 4, partial)
Lands the safe-to-ship foundation of Phase 4 — adapter logic, registry
bootstrap, and SystemSettings hooks for replica sync. The on-disk
migration of legacy customDictionaries (bundleDir → content-hash id),
the live store wiring, and the Settings → Sync UI are deferred to a
follow-up PR so they can land with real-device QA.
Adapter (src/services/sync/adapters/dictionary.ts):
- dictionaryAdapter: kind='dictionary', schemaVersion=1.
- pack/unpack — only synced subset (name, kind, lang, addedAt,
unsupported{,Reason}). bundleDir / files / unavailable / deletedAt
stay per-device or are handled by the tombstone mechanism.
- BinaryCapability.enumerateFiles dispatches by bundle kind:
- mdict: mdx + mdd[] + css[]
- stardict: ifo + idx + dict + syn (skips .idx.offsets / .syn.offsets
sidecars — those are device-local indices)
- dict: dict + index
- slob: single .slob file
- primaryDictionaryFile() picks the anchor file per kind for
partialMD5 hashing.
- computeDictionaryReplicaId(partialMd5, byteSize, sortedFilenames)
produces a deterministic 32-hex content-hash id used at import time.
- 23 tests cover pack/unpack identity, kind dispatch, file enumeration,
id determinism, and per-device-field exclusion.
Bootstrap (src/services/sync/replicaBootstrap.ts):
- bootstrapReplicaAdapters() registers all known adapters once at app
start. Idempotent (safe to call multiple times). Wired into
EnvContext.tsx so the registry populates on app mount.
- 3 tests cover registration, idempotency, and the PR-1 allowlist.
SystemSettings (src/types/settings.ts, src/services/constants.ts):
- +SyncCategory = 'book' | 'progress' | 'note' | 'dictionary' — typed
union for the user-facing sync toggles. 'progress' gates the
existing book-config sync (reading progress); 'note' gates
annotations; 'book' gates book binaries + metadata; 'dictionary'
gates the new replica sync. Future replica kinds extend the union.
- +SYNC_CATEGORIES readonly array for UI iteration.
- +syncCategories: Partial<Record<SyncCategory, boolean>> — per-
category opt-in toggles in DEFAULT_SYSTEM_SETTINGS (default ON for
all four). UI panel ships in the follow-up.
- +lastSyncedAtReplicas: Record<string, string> — per-kind HLC pull
cursors (matches replicaSyncManager's CursorStore contract).
Registry type cleanup (src/services/sync/replicaRegistry.ts):
- BinaryCapability.enumerateFiles return shape: localRelPath → lfp
to match the existing TransferStore.ReplicaTransferFile convention.
Tests: 28 new (23 dict + 3 bootstrap + 2 syncCategories defaults).
Full suite 3702 passing, lint clean. Existing book/config/note sync
paths untouched.
Deferred to PR 1 follow-up (with real-device QA):
- customDictionaryStore migration: rehash legacy uniqueId() bundleDir
to content-hash id; preserve providerOrder mapping; staged
.legacy/<old-id>/ backup.
- Wire customDictionaryStore mutations through replicaSyncManager
(markDirty on add/rename/delete; pull on init).
- Settings → Sync panel: per-category toggles + last-sync timestamps.
- Sync passphrase modal: set / change / forgot flow (lazy first prompt
on encrypted-field push/pull).
- <CloudReplicaRow> in CustomDictionaries.tsx for "Download from cloud
(X MB)" affordance.
- Tauri keychain backend for sync passphrase storage.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(sync): replicaSync singleton + content-hash id at dict import (Phase 4b)
Two foundation pieces that everything UI-side will sit on top of, both
purely additive — no live store wiring, no behavior change for existing
dictionary imports.
replicaSync singleton (src/services/sync/replicaSync.ts):
- initReplicaSync({deviceId, cursorStore, hlcStore?, client?}) builds
one ReplicaSyncManager backed by an HlcGenerator with persistence
wrapped around .next()/.observe(). Idempotent (second init returns
the existing instance).
- LocalStorageHlcStore (src/libs/hlc-store.ts) snapshots the HLC
counter under 'readest_replica_hlc' so it survives restart. Falls
back silently when localStorage is unavailable (private mode, SSR);
client re-derives via the existing remote max(updated_at_ts) repair
path. InMemoryHlcStore is the test backend.
- 16 tests (9 hlc-store, 7 replicaSync) covering snapshot persistence,
restore-on-init, and idempotency.
- Wiring into EnvContext for production deferred to the follow-up that
also adds the cursor store backed by useSettingsStore.
Content-hash id at dictionary import
(src/services/dictionaries/contentId.ts):
- computeDictionaryContentId(primaryFile, filenames) wraps
computeDictionaryReplicaId(partialMd5(primary), byteSize,
sortedFilenames) — the cross-device id used as the replica_id when
the dict actually pushes/pulls.
- Wired into all four import paths in dictionaryService.ts:
- stardict primary = .ifo (small text, partialMD5 ≈ full hash)
- mdict primary = .mdx (body)
- dict primary = .dict.dz (gzipped body)
- slob primary = .slob (single-file bundle)
ImportedDictionary gains contentId?: string. Optional for backwards
compat; legacy bundles without contentId are flagged as
"needs rehash before sync" by the upcoming store-wiring follow-up.
- 6 tests cover identity determinism, byteSize sensitivity, filename-
set sensitivity, and order-independence.
Tests: 22 new (9 + 7 + 6). Full suite 3724 passing, lint clean.
Existing dictionary import flow unchanged for users — contentId is an
additional field, not a replacement for the bundleDir-based id.
Deferred to follow-up (with on-device QA):
- Production cursor store backed by useSettingsStore +
appService.saveSettings.
- EnvContext call to initReplicaSync after appService boot.
- customDictionaryStore mutation hooks → replicaSyncManager.markDirty.
- Legacy bundleDir → contentId migration with .legacy/ backup.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(sync): land replica-sync design plan in repo
Moves the plan document that drove this PR's foundation work
(`~/.claude/plans/vivid-orbiting-thimble.md`) into the project tree at
`apps/readest-app/.claude/plans/` so reviewers and future contributors
can read it alongside the code without leaving the repo.
The plan went through three review passes — Codex (19 findings, all
absorbed), CEO/scope review (mode SCOPE EXPANSION; encrypted secrets
pulled forward to v1, "private-only forever" posture lock), and eng
review (FULL_REVIEW mode, 16 findings absorbed). The full review trail
lives in the file's `## GSTACK REVIEW REPORT` section at the bottom.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs(crdt): point README at in-repo plan path
Now that vivid-orbiting-thimble.md lives at
apps/readest-app/.claude/plans/, the README link should point there
rather than at the home-dir copy that no longer exists.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* refactor(sync): rename src/libs files to camelCase per project convention
Test files renamed in lockstep. Imports + comment references updated
across cloudService, storage, transferManager, replicaSync,
replicaSyncManager, /api/sync/replicas, and all four test files. No
behavior change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
e7564ffc27
|
fix(docker): correct Kong gateway port for client build arg (#4046)
The web client's NEXT_PUBLIC_SUPABASE_URL build arg pointed at port 7000, but Kong is exposed on KONG_HTTP_PORT (8000 by default), so browser-side Supabase calls failed in the self-hosted Docker setup. Closes #4035 Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
d1e7b4902c
|
feat(share): time-limited share links with cfi-aware imports (#4037)
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
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Add a Share Book feature that generates an expiring HTTPS share URL plus a
parallel readest://share/{token} deep link. Recipients land on /s/{token},
where logged-in users can one-tap "Add to my library" (R2 server-side
byte-copy) and anonymous users download the book or open it in the app.
Sharers manage active links from a dedicated "Manage Shared Links" panel
under user settings.
Highlights:
- 9 new App Router endpoints under /api/share (create, [token], cover,
og.png, download, download/confirm, import, revoke, list).
- /s landing page with branded next/og chat unfurl image and SSR auth-cookie
detection so logged-in recipients see "Add to my library" as the primary
action without layout shift.
- Server-side R2 byte-copy for /import preserves the project's existing
invariant that every files.file_key is prefixed with its row's user_id;
stats / purge / delete / download routes work unchanged. URL-encodes the
copy source so titles with spaces or '&' don't break the copy.
- Universal 7-day expiry cap, no tier differentiation, no "never". DMCA-risk
reduction. Picker defaults to 3 days.
- Position-aware shares: "Share current page" toggle (off by default for
privacy) attaches the sharer's CFI; recipient lands at the same paragraph.
- Per-user 50-share cap, rate limiting via Cache-Control: no-store on
token-bearing responses, atomic SQL increment for download_count via a
SECURITY DEFINER function so the public confirm beacon stays safe under
concurrent fire.
- Soft revocation: presigned download URLs (5-min TTL) cannot be cancelled
before TTL; documented as accepted v1 behavior.
- token + token_hash hybrid storage: public endpoints look up by hash and
never select the raw token, so accidental SELECT-* leakage on a public
route can't expose the bearer credential.
- Mobile / desktop Tauri share via tauri-plugin-sharekit; web falls back to
navigator.share with a clipboard fallback when no native share method
exists. Share-sheet dismissal no longer silently copies.
UI:
- New Dialog with a settings-card group: iOS-style segmented duration picker
+ toggle slider for "Share current page", on a single row each.
- Reader top-bar Share button, library context-menu Share entry, manage-
shares list with cover thumbnails and overflow menu.
- New <SegmentedControl> primitive in src/components for reuse.
Coverage:
- Unit tests for token utils + URL parser (20 new tests, full suite at 3445).
- 31 locales translated for all new strings; en plurals hand-added per the
project's hand-curated en convention.
DB migration in docker/volumes/db/migrations/002_add_book_shares.sql adds
the book_shares table, RLS policies, and the increment_book_share_download
RPC. Migration is idempotent.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
baee85e7c8
|
feat(rsvp): sync reading position to cloud via book_configs (#3801) | ||
|
|
29df8522fa
|
chore(bump): bump Tauri to the latest version (#3716) | ||
|
|
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> |
||
|
|
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 |
||
|
|
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 |
||
|
|
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 |