Commit graph

4072 commits

Author SHA1 Message Date
Shigenobu Nishikawa
bbd7266987
Add a list view for OPDS catalogs (#8151)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(opds): add a catalog details view

Similar covers and truncated titles can make editions or volumes hard
to distinguish. Give readers a full-width view for titles, filenames
and dates while retaining the catalog's navigation and grouping.

Co-Authored-By: Codex (GPT-6.2 Sol) <noreply@openai.com>

* fix(opds): handle localized publication fields

Readers can open and import an entry with translated titles and
subtitles. Retain a valid update date when modified is malformed.

Co-Authored-By: Codex (GPT-6.2 Sol) <noreply@openai.com>

* fix(opds): preserve catalog details across locales

Use the valid update date when the supplied calendar day is invalid.
Keep translated editions recognizable after changing the display
language, and preserve contrast in e-ink detail rows.

Co-Authored-By: Codex (GPT-6.2 Sol) <noreply@openai.com>

* fix(opds): preserve catalog calendar dates

OPDS metadata can specify a calendar date without a time. Formatting
that value in the device time zone can show the previous day. Display
the supplied calendar day and retain local formatting for timestamps.

Co-Authored-By: Codex (GPT-6.2 Sol) <noreply@openai.com>

* feat(opds): list view with whole titles, switched from the header (owner: "go ahead with your implementation and update the pr")

Narrow the details view to what #8127 needs and use the library's
Grid/List words:

- A header button switches between Grid and List. The choice is the
  `opdsViewMode` setting, next to `libraryViewMode`, instead of text
  buttons in the feed header and a localStorage key.
- A list row shows the whole title, the author, a thumbnail and the file
  name from the acquisition link when it names a book file and differs
  from the title. The date (and its calendar checks) and the subtitle are
  gone.
- The list saves its position as it unmounts, so coming back from paging
  or a facet lands where scrolling stopped. Before, it was saved only when
  a row was clicked.
- The language-map changes (PublicationView, findExistingBook,
  feedChecker, metadata import) leave this PR. OPDS 2.0 titles given as a
  language map crash the grid on main as well, so they get an issue and a
  PR of their own.
- The grid's markup is unchanged. NavigationCard and PublicationCard
  return a separate button row for the list, with phrasing content only
  and one 1px base-content divider under e-ink.

Verified:
- pnpm lint (Biome + tsc) and pnpm format:check pass.
- vitest: src/__tests__/app/opds, src/__tests__/services/opds-*,
  constants, backup-settings and settings-store, 35 files and 587 tests
  pass. The 11 new unit tests fail on main (no List switch, no list row).
- Chromium: feed-view.browser.test.tsx, 3 pass. With the save on click
  only, "returns to where the list was left" fails with
  `expected 'Book 0' to be 'Book 61'`. With the title clamped to one
  line, "shows the whole of a long title" fails with
  `expected 60 to be less than or equal to 21`.
- dev-web, local Atom feed (40 long titles differing at the end, facets,
  paging) and OPDS 2.0 feed (navigation, three groups): the switch
  persists across a reload; open a book, Next and a facet each come back
  to the same row; phone (iPhone 13), dark, e-ink and Arabic checked.
  In grid mode the DOM under <main> is identical to main's on both feeds.
- Not run: a Komga, Kavita or COPS server (the unit tests use their URL
  shapes), an e-ink device (data-eink set in Chromium), the native apps.

Reported by shishi on GitHub.

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

* fix(opds): keep a '#' file name and translate Untitled in list rows

Two findings from the review of 6c892ba8f:

- The file name was checked for a book extension after decoding, so a
  '#' in it (`/books/Volume%2312.txt`, common in comic and light-novel
  names) read as the start of a fragment and the name was hidden for
  formats with no inference rule, such as TXT. Check the encoded path,
  then decode for display.
- A list row with no title showed English "Untitled" in every locale; it
  now goes through useTranslation like NavigationCard.

Verified: the two new cases in publication-card.test.tsx fail without the
change (`expected 'Series, Vol. 12' to be 'Series, Vol. 12Volume#12.txt'`,
`expected 'Untitled' to be 'translated Untitled'`) and pass with it.
src/__tests__/app/opds and services/opds-* pass (32 files, 404 tests);
pnpm lint and pnpm format:check pass.

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

---------

Co-authored-by: Codex (GPT-6.2 Sol) <noreply@openai.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 21:32:03 +08:00
Mohammed Efaz
731c2dd312
fix(xray): follow-up fixes from the #3119 review, and #8094 (#8148)
* fix(xray): keep a queued request waiting while the server answers another (#8094)

X-Ray sends four requests at once. A local server that answers one at a
time, such as llama.cpp, takes the next only when the one before is done.
At 12 tokens/s the fourth waited about 510 s against the 300 s limit for a
first reply, so the update failed with "The AI provider stopped
responding." Each streamed chunk now restarts the wait of every request
whose reply hasn't started.

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

* fix(xray): keep what a broken reply got right, and ask a small model less (owner: "One invalid JSON reply fails the whole update")

One reply with invalid JSON failed the whole update, as small local models
often send (gemma3 at a 4096 token context). A reply now keeps its items up to
where its JSON breaks. One without any JSON is asked again in halves, down to
3000 characters. After a reply breaks or is cut off, that model is asked about
half as much at once until the app restarts.

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

* fix(xray): find a quote whose quotation marks the model restyled

Models often send straight quotation marks for curly ones, hyphens for dashes,
and an ellipsis at the end, so a verbatim quote wasn't found and its item was
dropped. Quotes are now matched without those differences, and kept as the book
has them, without a quotation mark at either end, which the quote shows itself.

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

* fix(xray): leave the book's front matter out (owner: "Mentions include front matter (the title page is Alice's first mention)")

Mentions and the passages sent to the AI now skip the sections that the book's
landmarks call its cover, title page, contents, copyright page or colophon, and
those before where the landmarks say the story starts. A table of contents also
told the AI the names of chapters still to come.

Alice in Wonderland, to chapter 4: the first mention of Alice is in chapter 1
instead of on the title page, and 57 mentions are 54.

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

* fix(xray): show one quotation mark before a quote that opens with one (owner: "a mention that starts with a quotation mark shows two")

A quote or mention was always put in quotation marks, so a sentence that opens
with its own showed two. It now shows the book's own, and only those.

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

* fix(xray): offer the update above the mentions (owner: "Update X-Ray sits below the fold of the popup when mentions show")

When a name had no X-Ray entry, its mentions came first, and up to five of them
pushed Update X-Ray out of the popup's view. The update now comes first.

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

* fix(notebook): keep the X-Ray tab while its toolbar tool is on (owner: "the X-Ray tab disappears after switching to another Notebook tab")

The X-Ray tab showed while the X-Ray dictionary was on or the tab was open.
With only the toolbar tool in use, it went away once another tab was opened. It
now also stays while the book's toolbar has the X-Ray tool.

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

* fix(xray): say in its settings that the toolbar tool shows it too (owner: "The X-Ray settings text doesn't mention the toolbar tool, as the Context Dictionary text does")

The X-Ray box now says, as the Context Dictionary's does, that it shows with
every lookup when on, or only when its toolbar tool is tapped. This also
translates the error for an invalid reply, which is now shown translated.

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

* fix(xray): keep the items of a reply whose stream the server ended early

With requests waiting behind it, Ollama sometimes ended the stream of a
reply without a finish reason, and the whole update failed with "Response
stream ended without a finish reason." What came now counts as a reply
cut off: its complete items are kept and the update goes on.

Alice in Wonderland to chapter 9, gemma3:4b on Ollama answering one
request at a time: 3 of the first 4 updates failed this way; with the fix
the same update ended with 12 characters and 10 events.

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

* fix(xray): keep a story whose body landmark is the first section

A body landmark at section 0 was taken as none, so a later one moved the
story's start past the sections before it.

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

* fix(xray): fail a batch when a half asked again still has no JSON

The batch is saved as read, so the half without items was never asked
about again. It now fails as a reply without JSON did, and the next
update asks about it again.

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

* fix(xray): keep the smallest batch size learned for a model

An update that started before another one learned a smaller size wrote
its larger one back.

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

* fix(xray): read the book when a landmark href is malformed

resolveHref throws at once on a malformed href (decodeURI), which skipped
the catch and failed every later read of the book. It now leaves that
landmark out.

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

* fix(xray): keep a section where the story starts after its title page

A title page and the first chapter can share one file, and a book can be
one file: the section a body landmark points at was left out whole when
an aside landmark pointed at it too. It is now kept, and a book whose
landmarks leave no story is read whole.

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

* fix(xray): find a quote whose ellipsis the model restyled

A quote with three dots where the book has an ellipsis, or the other way
around, was not found, so its item was dropped.

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

* fix(xray): fail a batch whose reply was cut off before any item

The batch is saved as read, so its text was never asked about again. It
is now asked again in halves, or fails and is asked about by the next
update.

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

* fix(xray): match each ellipsis of a quote, in the passage the reply names

A quote with both ellipsis forms, each the other way around in the book,
was not found, and a restyled quote could be placed in another passage
before the one the reply named. Every ellipsis is now one character when
matching, with where it is in the book kept.

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

* fix(xray): ask again in halves about a reply cut off before its end

A reply cut off at the output limit, or whose stream the server ended
early, kept its complete items and the batch was saved as read, so the
passages after where it stopped were never asked about. Such a batch is
now asked about again in halves, as one without JSON is. A batch too
short to split still keeps the items it got.

On Ollama with a 4096 token context, 4 of 7 replies in one update were cut
off at the limit.

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

* fix(xray): keep the names of a reply cut off that its halves missed

A batch whose reply was cut off is asked about again in halves, and the
items from before the cut were dropped. A character the model found the
first time and not the second was then lost. Those characters are now
kept; the others, and the cut reply's events and relationships, are left
to the halves, so nothing shows twice.

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

* fix(xray): take a closed reply whole, shrink batches on full ones, keep the book's quotation marks

Follow-ups from the review of this PR:

- A complete reply that needed a small repair (a trailing comma, a closing
  brace too many, a note after it) counted as broken: the batch was asked
  again in halves and the model's batch size halved. A reply is now whole
  when its JSON closes; one cut off still isn't.
- The last batch before the page can be short. Cut off once, a 2,500-char
  remainder set every later batch of that model to 3,000 chars. A request
  of half a batch or less no longer shrinks the batches.
- A quote that ran past the end of a speech showed the book's closing mark
  inside ours: “Keep your temper," said the Caterpillar.” A quote now keeps
  the book's own marks where the reply quoted them, and shows only those,
  in the X-Ray tab and in the dictionary popup, which wrapped every quote.
- A mention that opens with a straight quote or a German » lost it and got
  ours around the book's closing one. Those marks are dropped only when no
  word follows them, as a closing mark of the sentence before.
- The queued-request test no longer leaves two requests waiting for the
  tests after it.

Tests that fail without it (each on its assertion, run with the old source
files put back): "is taken whole when its JSON closes" x3 (called 3 times,
not 1), "asks about as much at once after a short batch is cut off"
(2940, not > 11000), "keeps the quotation marks of the book where the reply
quoted them", "places a quote whose quotation marks and dashes the model
restyled", "keeps the opening quotation mark of a sentence…" (findMentions),
"shows a quote that opens with its own quotation mark in that one alone"
(popup), and XRayView's mention list.

Ran: the xray, notebook and dictionaries suites (42 files, 436 tests),
pnpm lint, pnpm format:check. On dev-web with Gutenberg's Alice (straight
quotes) read to chapter VII: gemma3 on Ollama sent the same 4 batches
before and after, all replies whole; with a stub reply quoting dialogue,
the timeline, the mention search and the popup showed “Keep your
temper," …”, “You promised…," said Alice, "and why…” and “In that
direction," the Cat said…” before, and the book's own marks after, in
light, dark and e-ink.

Not changed, with the reason in the review: the front-matter cut at the
story-start landmark (in 28 local EPUBs with one, every text section before
it was front matter), an aside landmark with a #fragment (no local book
has one pointing at story text), the order of names kept from a cut-off
reply, and failing a batch whose smallest half is cut off before any item.

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

* fix(i18n): word the German X-Ray settings text as its neighbour does

The new X-Ray line used "Sie" and "Suche" beside the Context Dictionary's
"Schalte es oben ein … bei jedem Nachschlagen". Checked against that string;
the other locales already match theirs.

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

* fix(xray): keep the closing quotation mark of a mention in quotation marks

A sentence ends at its "!", "?" or ".", which a quotation keeps inside its
closing mark, so a mention that opens with the book's own mark showed none
at its end: "That was a narrow escape! A sentence that opens with a
quotation mark now gets the closing one that follows its terminator. One
whose quotation opens mid-sentence is left as it was, and the shared
extractSentence is unchanged, so Vocabulary's sentences stay the same.

Test that fails without it: "keeps the closing quotation mark of a sentence
in quotation marks" (expected '"Anna!"', got '"Anna!'), for straight,
curly and German marks. Ran: the xray, notebook, dictionaries and
vocabulary suites (51 files, 617 tests), pnpm lint, pnpm format:check. On
dev-web with Gutenberg's Alice to chapter VII, the X-Ray search for
"crying", "narrow" and "wretched" showed "Come, there's no use in crying
like that! before and "Come, there's no use in crying like that!" after.

Raised by CodeRabbit on this PR.

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

---------

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-12-01 21:30:41 +08:00
Kel
b03a283dee
fix(reader): preserve local SVG glyph references (#8149)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
The figures in the #8108 EPUB draw their labels as outlined glyphs, each a
<use> instance of a path in the same SVG. DOMPurify drops every <use>
because one can load another document, so only the diagram's boxes showed.

Keep a <use> when all its references (href and legacy xlink:href) are
fragments of the same document, and drop it otherwise. One helper,
removeNonLocalUses, runs on DOMPurify's inert output in sanitizeSvg (SVG
files, as in the report) and in the chapter sanitizer (inline <svg> in
XHTML, which had the same gap). sanitizeBookFragment still strips <use>,
since that markup runs in the app window.

Verified:
- svg-sanitizer.test.ts fails on main (expected [] to have a length of 2
  but got +0). The chapter case in transformers.test.ts fails without the
  chapter change (expected [] to deeply equal [ '10', '30' ]). Both pass;
  src/__tests__/services/transformers 127/127. Lint and format:check are
  clean. CI is green at 388ffa1c9.
- Main vs this change over 6000 chapters from 466 local EPUBs:
  byte-identical. Of 136 SVG files, 22 are identical and 114 differ only
  by the 28,996 kept <use> elements.
- dev-web (Chromium): the reported EPUB renders all 79 and 275 glyph
  references in figures 0-1 and 0-2, where main drew empty boxes. A copy
  with figure 0-1 inlined into the chapter keeps all 79 as well.
- Chromium 148, Firefox 150 and WebKit 26.4 ignore xml:base when
  resolving <use href="#g">, and DOMPurify's SVG profile strips it, so
  no xml:base handling is needed.
- Not run: the desktop and mobile apps, dark mode and e-ink.

Fixes #8108. Reported by Oshibuki on GitHub.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 20:50:06 +08:00
Huang Xin
34496862c2
fix(library): start a long press over when a second finger lands (#8169)
A second pointerdown overwrote the long-press timer without clearing
the first one. Before #8168 the first selection's re-render cleared
the second timer through the deps effect, which #8168 removed, so
since then a second finger landing on a cover during a hold selected
it and then deselected it 200 ms later. Clear any pending timer before
starting a new press. CodeRabbit flagged this on #8168.

Verified:
- "selects once when a second finger lands on the cover during the
  hold" fails on main: expected "vi.fn()" to be called once with
  arguments: [ 'hash-1' ], Number of calls: 2. It passes with this
  commit and before #8168 (4d8a163a1).
- dev-web, Chromium with CDP touch input, a second touch point on the
  cover 205 ms into the hold, released at about 1 s: before #8168
  (4d8a163a1) the cover was selected 3 of 3 times, with #8168 0 of 3
  (select mode on, book deselected), with this commit 3 of 3. The
  mid-hold import check still selects 3 of 3.
- Related unit tests (34 files, 575 tests), pnpm lint and
  format:check pass.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:00:13 +01:00
doublex640
e2f884af24
fix(tts): size the minimal mini player's time box to its label (#8143)
The minimal Read Aloud row cut its remaining time to "-3…" on a 360dp
Android phone with a larger system font: Android's font size grows the
text but not the fixed 3.5rem box around it. The time box now grows to
its label from a 3.5rem floor. The transport buttons give up their side
padding first, so a row that already fits is unchanged. A sleep timer no
longer widens the box. The time follows the system font up to 1.5x, and
the speed badge keeps the settings glyph's size.

Verified: TTSMiniPlayer-android-width.browser.test.tsx (14 cases) fails 6
cases on main's component; TTSMiniPlayer.test.tsx 28 passed; lint and
format clean; CI green at c26ce7043. On an API 35 emulator at 360dp and
1.3x the full label shows, using main's build with the fix's computed
styles applied over CDP. Not run: a build of this branch on a phone, iOS.

Fixes #8118. Reported by doublex640 on GitHub.

Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 16:42:33 +08:00
doublex640
03ee470284
fix(reader): apply the same three-zone click layout outside the page (#8146)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Clicks outside the page iframes split at half the window width. That
covers the blank viewport below a short section in Single Section
Scroll, the page margins, and the space around a PDF page. So the
middle band turned the page, and a click on the exact center did
nothing. These clicks now go through the same zones as clicks on the
page, measured on the reader container:

- The middle 25% toggles the bars.
- The outer bands turn the page. Swap Click Area, the fullscreen click
  area and the reading ruler apply.
- With Click to Paginate off, a click anywhere toggles the bars.
- With the bars shown, a click only hides them.

Clicks on the page now use the window point the iframe reports, not
screenX minus the window position.

Verified:
- usePagination-marginClick.test.ts: six tests fail against main's
  usePagination.ts (expected setHoveredBookKey to be called with
  'book-1' / null) and pass with the change.
- usePagination-*.test.ts and iframeEventHandlers.test.ts: 11 files,
  176 tests pass. pnpm lint and format:check are clean.
- dev-web (Chromium) and the Linux CEF desktop app at 1280x720, with
  Scrolled Mode and Single Section Scroll on a two-line section. On
  main, a blank click at 50% did nothing and blank clicks at 40% and
  60% turned the section. With the change, those three toggle the bars,
  15% and 85% still turn, and with the bars shown a side click only
  hides them. Paginated page clicks are unchanged: 40-60% toggle, 30%
  turns back, 70% turns forward.
- Not run here: Windows, the reporter's platform. The reporter
  confirmed the scrolled single-section case on a Windows portable build
  of the first commit.

Fixes #8116. Reported by doublex640 on GitHub.

Co-Authored-By: workbuddy (Deepseek-V4.1-Flash-1017) <46395142+doublex640@users.noreply.github.com>
Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 11:36:51 +08:00
doublex640
64999632dd
fix(tts): keep the full mini player up while its controls are in use (#8145)
Entering the full-style mini player clears hoveredBookKey to drop the
reader toolbar, and that also armed the 5 s auto-hide. The card then faded
out while its play/pause and skip buttons were in use. A pointer on the
card now holds it up and cancels any countdown in flight. The 5 s start
again once the pointer leaves. The minimal player is unaffected.

The hold uses pointer events. A touch tap on a platform that isn't mobile
(a Windows touch laptop, or iPad Safari with its desktop user agent) fires
a compatibility mouseenter with no mouseleave after it, and a hold keyed
on mouse events kept the card up for the rest of the session. The hold is
also dropped when the player sheet replaces the card, since a card
unmounted under the pointer never reports pointerleave.

Fixes #8142. Reported by doublex640 on GitHub.

Verified:
- New tests fail without the change: the useMiniPlayerAutoHide hold
  tests (expected false to be true), the TTSMiniPlayer pointer and touch
  tests (expected "vi.fn()" to not be called at all, but actually been
  called 1 times), and the TTSControl sheet-reset test without the
  unmount reset (expected 'true' to be 'false').
- src/__tests__/components/tts/: 178 passed. pnpm lint and
  pnpm format:check are clean. CI is green at the merged head.
- dev-web (Chromium, full style, Kokoro voice), main against this branch:
  - Mouse on the card through 12 s of Pause/Play: main hid the card
    after 5 s. This branch keeps it up and hides it 5.8 s after the
    pointer leaves.
  - Touch tap on Pause, then toolbar off: the card hides 5 s later, the
    same as main.
  - Opening and closing the sheet from a hovered card: it hides 5 s
    later.
- Not run: the Windows app itself, iPad Safari.

Co-Authored-By: workbuddy (Deepseek-V4.1-Flash-1017) <46395142+doublex640@users.noreply.github.com>
Co-Authored-By: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 11:14:00 +08:00
Huang Xin
7e7be3baed
fix(library): keep a long press when the library re-renders mid-hold (#8168)
useLongPress cleared its 500 ms timer whenever the caller's deps
changed and never restarted it. The library hands each cover a new
toggleSelection callback on every render, so an import, a sync pull
or a transfer progress tick during a hold silently dropped the
selection. The timer now calls the latest onLongPress through a ref
and is cleared only on unmount. A cover that starts showing a
different book remounts, since cells are keyed by book. The deps
argument has no use left, so the three callers drop it; BooknoteItem
passed [] and behaves as before.

Found while reviewing #8135.

Verified:
- "selects when the library re-renders during the hold" fails on
  main: expected "vi.fn()" to be called once with arguments:
  [ 'hash-1' ]. It passes with the fix.
- dev-web, Chromium with CDP touch input, an EPUB dropped about
  125 ms into a hold on a cover (React commits land at ~130, ~190 and
  ~300 ms, before the timer): main (4d8a163a1) selected 0 of 3 times,
  this branch 3 of 3. Holds without a drop selected 3 of 3 on both,
  and the drop alone selected nothing. #8135's drift holds still
  select once, and a tap and a swipe behave as before.
- Related unit tests (34 files, 574 tests), the three bookshelf
  browser suites (56 tests), pnpm lint and format:check pass.
- Not run: the reader's annotation long press in the app. It passed
  empty deps, so its timer was already cleared only on unmount.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:03:56 +01:00
Shigenobu Nishikawa
4d8a163a11
Tolerate slight touch drift when selecting book covers (#8135)
* fix(library): tolerate small touch drift

A deliberate hold on a book cover can be canceled by slight finger
movement. Allow more movement for shelf touch holds while preserving
the hold time, tap threshold, and drag behavior.

On the production web build, a 12 CSS px drift went from zero of three
selections to three of three. Swipes still scrolled and taps still
opened the book. The related regressions fail on main and pass with
this change.

Co-Authored-By: Codex (GPT-6.2 Sol) <noreply@openai.com>

* docs(library): say where the touch drift tolerance takes effect

The 16 px hold tolerance only matters where the browser waits more
than 10 px before it starts a pan, because the pan cancels the
pointer. Say so next to the constant, so nobody expects it to change
anything on Android phones.

Comment only, so there is no new test. Checked the behavior it
describes:
- dev-web, Chromium with CDP touch input (desktop slop): main selected
  a cover on neither a 12 px sideways nor a 14 px downward hold, and
  this PR selected on both. A 20 px drift, a tap and a 96 px swipe
  behaved the same on both.
- A probe page in desktop Chromium got pointercancel at 16 px.
  Chrome on an Android 15 emulator cancelled a 12 px drift at 8.1 px,
  before the 500 ms hold (one run).
- Related unit tests (21 files), the three bookshelf browser suites,
  lint and format pass. iOS not checked.

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

* fix(library): drop the unrendered RecentShelf change

RecentShelf has not been rendered since the configurable bookshelves
(#6329), as #8134 found: the Recently read shelf draws its covers with
BookshelfItem, so the BookshelfItem change already covers it. Drop the
RecentShelf change and its two tests.

Move the drift-and-return test to BookshelfItem, next to a plain tap
that opens the book. With the tapCancelled check removed from
useLongPress it fails: expected "vi.fn()" to be called +0 times, but
got 1 times.

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

---------

Co-authored-by: Codex (GPT-6.2 Sol) <noreply@openai.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 03:48:41 +01:00
leehuazhong
bb2cc53961
perf(reader): pipeline next-page capture during committed settle animation (#8103)
* perf(reader): pipeline next-page capture during committed settle animation

Eliminate consecutive rapid page-turn stalls without growing the 3-page native texture cache:

- Allow NativePaperTurn.capture(allowActive=true) during committed settle animations while protecting active current/destination textures, skipping PopupWindow relayout, and isolating speculative capture failures from tearing down the live animation.
- Advertise Android lookahead capability via start's canPipelineCapture flag so platforms without active-turn capture (e.g. iOS) skip lookahead cleanly.
- Pipeline navigation and N+2 lookahead capture inside NativePageTurn.endDrag() once animate(commit=true) begins.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(reader): clean up provisional GL texture and skip post-dispose rollback

- Delete the provisional GL texture in NativePaperView.upload when texImage2D or glGetError throws so non-fatal allowActive failures cannot leak textures.
- Return before rollback navigation in NativePageTurn.endDrag if disposed while settle-time lookahead was in flight, with unit test coverage.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(android): offer settle captures on RuntimeShader only, refuse empty regions

- `start` reports `canPipelineCapture` only on the RuntimeShader
  surface. On the GL surface (API < 33, two-column spreads) the upload
  runs on the GL thread that draws the settle, so a lookahead capture
  would land between its frames. That path was never measured.
- A speculative capture whose region rounds to no device pixels is
  refused. With the early return before the size check,
  `Bitmap.createBitmap(0, h)` threw in a main-thread callback and
  crashed the app.
- `dragging`, `cancelled`, `current` and `destination` are volatile:
  a speculative capture's `valid()` reads them on the surface's upload
  thread.

New tests in NativePaperTurnTest (both surfaces):
- offersSettleCapturesOnlyOnTheRuntimeShaderSurface: with `true`
  advertised, the GL run fails with expected:<false> but was:<true>
- capturesThePageAfterNextWhileACommittedTurnSettles: the capture is
  accepted, the live pages stay and the unused page is evicted, and the
  next turn lands on the captured page
- refusesUnflaggedAndLivePageCapturesWhileATurnSettles
- keepsTheSettleWhenASpeculativeCaptureHasNoPixels: with the PR's
  early return, the instrumentation process crashes with
  IllegalArgumentException: width and height must be > 0
- keepsTheSettleWhenASpeculativeUploadFails (RuntimeShader)

Verified on Readest_API35 (emulator-5556):
- connectedFossGenericPenDebugAndroidTest for NativePaperTurnTest,
  NativePaperTurnRuntimeShaderTest and NativePaperRuntimeViewTest:
  58 tests, 4 skipped, 8 failed. The 8 are the four exact-colour tests
  (repeatedlyCompletesAnimationTails…, keepsTheRestoredPageCovered…,
  capturesThePageUnderTheNativeCover…, followsNativeTouchAndKeeps…) on
  both surfaces. They read red 253 / green 254 here and fail the same
  way on origin/main on this emulator. All new tests pass.
- testFossGenericPenDebugUnitTest: 59 passed.

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

* fix(reader): take the settle lookahead for a turn with another queued

A burst was only a turn that started while the previous turn or its
warm-up was running. Turns queued together (rapid taps that arrive
before the first turn's scene exists, or `Promise.all` of
`view.next()`) all start before any scene exists, so none of them took
the lookahead. On the emulator, five queued turns each waited for
`finish`, then a capture under the held cover, then `start`. A turn
that has the next one queued behind it now counts as a burst too: the
same check that sends `complete` and `keepCover`.

Test: "captures the page after next while the next queued turn waits
for the settle" fails without this change (expected undefined to be
'3').

Verified:
- native-page-turn, useCapturedTurn, useCapturedTurn-scrollLock and
  retained-page-turn: 205 passed. pnpm lint and biome format: clean.
- Debug x86_64 APK of 65a3d274c (this branch before this commit) on
  Readest_API35 (emulator-5556, RuntimeShader surface, thread
  ReadestPaperUpl), sample Alice, Curl, native ops traced with a CDP
  logpoint on the paper_curl call:
  - Paced `view.next()`: start, animate, finish, then the warm-up
    captures the next page. No capture during the settle, as on main.
  - Five `view.next()` 150 ms apart: turns 2-4 each capture the page
    after next with allowActive while settling, and the next turn's
    start follows the previous finish by 4 ms with no capture or cover
    (the first burst turn needed a 160 ms capture). Five consecutive
    pages, across a section boundary, with no double navigation.
  - A held curl onto a page captured that way: the revealed strip
    matches the same strip of the live page after the turn, pixel for
    pixel (0 pixels differ by more than 40 levels), so the sheet was
    taken from the thawed cell.
- Not run on a device: this commit's queued-turn case (the APK above
  predates it; the lookahead path it opens is the one exercised above).
  iOS (it never offers `canPipelineCapture`). Frame timing on a 120 Hz
  phone.

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

---------

Co-authored-by: Antigravity (Gemini) <noreply@google.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 10:48:08 +08:00
Shigenobu Nishikawa
efea4f6659
Preserve library selection when touch contextmenu arrives early (#8134)
* fix(library): preserve web touch long presses

A touch context-menu notification can arrive while the cover's
long-press timer is still running. Keep that timer responsible for
selection on both web shelves. Leave native and mouse handling and
drag-to-reorder on their existing paths.

Two new cases fail on main. The patch passes the full unit suite and
the production frontend build. A Chromium component fixture selects
each shelf item once when the early touch notification is injected.
It also exercises scrolling and drag reordering.

Co-Authored-By: Codex (GPT-6.2 Sol) <noreply@openai.com>

* fix(library): drop the unrendered RecentShelf change

RecentShelf has not been rendered since the configurable bookshelves
(#6329). The Recently read shelf draws its covers with BookshelfItem,
like every other shelf, so the BookshelfItem change already covers it.
Drop the RecentShelf change and its two new tests.

Verified on this commit merged with current main (5d820e426):
- The library, bookshelf and reader unit suites pass (210 files,
  1712 tests). pnpm lint and pnpm format:check pass.
- With main's useLongPress and BookshelfItem, "selects once when the
  touch context menu arrives before the timer" fails with: expected
  "vi.fn()" to be called once with arguments: [ 'hash-1' ].
- The web app in Chrome 124 on an Android emulator, at the previous
  head (same rendered code): Chrome's touch contextmenu arrives
  494-499 ms after pointerdown, against the 500 ms long-press timer.
  A real long press on a cover selected it 0 of 10 times on main and
  10 of 10 times with this change.

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

---------

Co-authored-by: Codex (GPT-6.2 Sol) <noreply@openai.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-12-01 03:22:15 +01:00
leehuazhong
5d820e4269
perf(reader): hand off native page warm-up and freeze webview during turns (#8102)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* perf(reader): hand off native page warm-up and freeze webview during turns

- Hand off in-flight idle neighbor warm-up directly into beginDrag()
  instead of aborting and re-capturing the same adjacent page.
- Keep the native cover up across back-to-back queued turns via
  keepCover / coverHeld capability negotiation (iOS safely falls back
  to re-covering when coverHeld is not reported).
- Suppress redundant WebView repaints/animations while the opaque native
  sheet covers the viewport (data-native-turn-frozen).
- Suppress op: move IPCs while beginDrag() is still preparing.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(reader): scope turn freeze to host cell and harden warm-up handoff edge cases

- Scope data-native-turn-frozen to the turning cell's hostElement so sibling parallel-view readers stay visible.
- Guard post-start freeze against disposal/stale scenes, clear rejected session before releasing held cover, reconcile native result.keys on aborted captures, and replay buffered drag pose when touchTracked is false.
- Fix animate-rejection test to reject animate specifically and add regression tests for all edge cases.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(reader): lower adopted covers, drop aborted uploads, stop previews on touch

Review fixes for the native warm-up and cover handoff:

- A turn that adopts a held cover skips `cover`, so native keeps the
  previous turn's id. When that turn failed before `start`, `#restore`
  sent `finish` with its own id, native dropped it, and the sheet stayed
  up over the reader. `#restore` now also sends `idle` when it drops a
  held cover.
- An aborted capture whose upload had finished returned its key in
  `result.keys`, and JS kept it, but `abortCapture` drops that texture
  on native. A later turn then called `start` with a missing destination.
  The aborted key is now left out of the reconciled set.
- `#touchRetained` was cleared only by `releasePreparedCapture`. A
  committed turn's relocate reaches it through
  `invalidatePreparedCapture`, but a cancelled swipe whose DOM touch end
  takes the drag path never does, so warm-ups after it took the current
  page only until the next touch. `beginDrag` now clears it.
- A touch no longer stopped a running warm-up preview, so the paginator
  stayed on the neighbouring page under the finger until its capture
  ended (`previewPage` restores the live page only on abort). Contact
  now aborts an in-flight preview and starts no new one. A capture of
  the current page keeps running for the turn to take over. The cost:
  the aborted page is captured again after the touch, and a tap turn
  in that direction no longer reuses the in-flight preview.
- Native `cancel` hides the sheet while the WebView was still hidden
  by `data-native-turn-frozen`, leaving a blank cell until the finger
  lifted. `invalidatePreparedCapture` now thaws the WebView when it
  sends `cancel`.

The reconciliation test now makes page 0 resident before the warm-up,
so it fails without the reconciliation (CodeRabbit).

Verified:
- New tests in native-page-turn.test.ts fail on 0cddd67a0 and pass
  here. With each fix removed alone, only its own test fails:
  - reconciles resident keys...: expected 1 to be 2 (also with no
    aborted-key reconciliation at all: expected 1 to be 2)
  - lowers a held cover...: expected true to be false
  - warms both neighbouring pages again after a cancelled swipe:
    expected false to be true
  - returns a touched page from a warm-up preview...: expected false
    to be true
  - shows the reader again when an overlay cancels...: expected 'true'
    to be undefined
- pnpm test --run native-page-turn, useCapturedTurn and
  useCapturedTurn-scrollLock: 187 passed
- pnpm test:browser --run paginator-paginated.browser.test.ts: 37 passed
- pnpm lint (tsc + biome) and pnpm format:check: clean
- Debug x86_64 APK built (compiles the NativePaperTurn.kt change, which
  PR CI does not); ./gradlew :tauri-plugin-native-bridge:
  testFossGenericPenDebugUnitTest: 55 passed
- Android 17 emulator (Readest_API37, WebView 145), alice.epub, Curl,
  native ops traced with a CDP logpoint on the paper_curl invoke:
  - 5 queued turns (view.next() x5): each finish sent keepCover, the
    next turn captured its destination under the held cover with no
    `cover`, and the last finish lowered it. A paginator goTo to the
    next chapter then showed on screen, so no sheet was left up.
  - Swipes: committed swipes warm both neighbours on 0cddd67a0 too,
    because the relocate releases the lease. The cancelled-swipe case
    was not exercised on the device.
  - Touch while the warm-up previews the next page: on 0cddd67a0 the
    paginator still showed the preview page at the first sample after
    touchstart and returned when the capture finished (~30-50 ms).
    Here it was back on the live page at the first sample, with
    `abortCapture` sent, and the page was captured again after release.
- Not run: the held-cover failure path, the aborted-upload race and the
  overlay `cancel` on a device (timing-dependent; covered by the unit
  tests above). iOS.

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

* docs(reader): say why a touch keeps a current-page capture running

The comment on retainPreparedCapture said a turn can take the capture
over. It cannot: beginDrag aborts any warm-up that is not previewing in
the turn's direction. The capture keeps running because it leaves the
viewport alone.

Comment only. native-page-turn.test.ts: 36 passed; biome check clean.

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

* fix(reader): keep a refreshed page out when native reports its pages

`#capture` replaced the resident set with the page list native returns,
even for an aborted warm-up capture. `refreshCurrentPage` (a PDF page
drawing its sharp layer once shown) stops the warm-up and drops the
current page, but a neighbour capture that native had already finished
still listed the old current page and put it back. The next turn then
used the stale sheet. On main this could not happen: stopping a warm-up
cleared every key, and an aborted capture's list was ignored.

Native's list now only removes pages (an evicted texture, or the aborted
upload its `abortCapture` drops); the captured page is added on success.

The test fixture's `previewPage` now returns to the live page when its
signal aborts, as the paginator does. The iOS re-cover test now checks
that both turns succeed and that the second turn's `cover` comes before
its page 3 capture (CodeRabbit).

Verified:
- "keeps a refreshed page stale when an aborted warm-up returns native
  keys" fails without the nativePageTurn change: expected 1 to be 2.
  "reconciles resident keys..." still fails with no reconciliation at
  all (expected 1 to be 2).
- "re-covers on the next queued turn..." fails when JS takes the cover
  as held without native's `coverHeld`: expected -1 to be greater
  than -1.
- native-page-turn, useCapturedTurn and useCapturedTurn-scrollLock:
  189 passed. pnpm lint and pnpm format:check: clean.

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

---------

Co-authored-by: Antigravity (Gemini) <noreply@google.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-30 16:39:58 +01:00
Shigenobu Nishikawa
f3fc4ef65c
test(reader): check QR colors in the code region (#8133)
Enabling a quote card's QR code changes the available text area.
Limit the foreground check to the actual QR so that text reflow does
not affect the assertion. Check the finder patterns and retain the
full-card color checks.

Chromium reproduced the old 2087-pixel failure. The patched file
passed all seven cases and still failed when QR painting was withheld.
The full unit and Chromium suites, TypeScript, changed-file Biome
and the production frontend build passed. The browser test rendered
the real quote canvas.

Co-authored-by: Codex (GPT-6.2 Sol) <noreply@openai.com>
2026-11-30 23:39:37 +08:00
leehuazhong
659f8716ae
perf(android): add API 33+ RuntimeShader paper surface and Page Flip LUT (#8101)
* perf(android): add API 33+ RuntimeShader paper surface and Page Flip LUT

Replace the TextureView/EGL14 worker path on Android 13+ single-column
turns with an HWUI RenderThread AGSL RuntimeShader surface, 1D
precomputed Page Flip LUT, and background HARDWARE bitmap promotion
with deferred safe recycling, while preserving upstream cylindrical curl
geometry, shading, and 100-240 ms linear settle timing 1:1.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(android): harden surface handoff, lazy upload worker, and curl parity tests

- Await transferred bitmap uploads before starting the scene on EGL <-> RuntimeShader switches, using a surfaceGeneration predicate instead of !bmp.isRecycled so async HARDWARE promotion commits cleanly.
- Dispose rejected NativePaperRuntimeView candidates and start ReadestPaperUpload lazily on first upload.
- Remove the 600 dp tablet exclusion so single-column tablets use RuntimeShader and EGL bitmap retention matches surface selection.
- Preserve exact pixel-center alignment for flat Page Flip columns, reset FrameStats before span < 0.001f, and serialize EGL FrameStats reset/log onto the GL worker.
- Extract production CylindricalCurlMath used by NativePaperRuntimeView and test it directly against NativePaperMesh output vertices across all four curl regions.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(android): rework the RuntimeShader paper surface (owner: fix the issues)

Review of #8101 found the RuntimeShader curl drew a different roll from the
GL mesh, surfaces switched mid-turn by copying bitmaps between them, and the
GL path and turn controller changed for every device without a run below
Android 13. This keeps the AGSL surface and narrows the rest:

- Curl: the shader now follows NativePaperMesh's own geometry: a cylinder
  through its 64 hinges of PI/65, starting half a band past the fold, and a
  flap tilted at 64*PI/65 (it was a 180-degree roll of radius arcLen/PI).
- Page Flip: one table column per pixel, plus a row holding the low bits of
  the sheet position and scale, so the table carries FLIP_FRAGMENT's values
  instead of F16 roundings (up to half a pixel on a 2560 px page).
- Surface choice: captures send the column count, and the surface type is
  picked when a layout's first page is captured (RuntimeShader for one
  column on API 33+, GL otherwise or when the AGSL does not compile). A
  column change follows a relayout that already invalidated every page, so
  the bitmap handoff, the retained CPU copies and the mid-turn switch are
  gone.
- NativePaperView and NativePaperTurn are main's code plus the PaperSurface
  interface; the swap interval, forced alpha, paper colour sampling, thread
  priority, finger timing, cover/idle refusals and frame stats are reverted.
  The cover and finish keep main's two-frame wait. Only the curl settle on
  the RuntimeShader surface is paced by Choreographer, as Page Flip already is.

Verified:
- CylindricalCurlParityTest rasterizes NativePaperMesh as NativePaperView
  draws it (perspective-correct, nearest triangle) over a 12 px grid for 5
  poses x 3 grab heights x LTR/RTL and compares CURL_SHADER's inverse: worst
  texture error 0.30 px. With the old geometry put back it fails:
  "texture position off by 0.576 px at (1254.5, 1362.5) pose=0.05".
- PageFlipLutTest checks every column against FLIP_FRAGMENT computed by trying
  every profile segment, over drag and settle frames. With the low row
  removed it fails: "sheet x resting column 36 of 1080 expected:<36.5> but
  was:<36.485596>".
- native-page-turn.test.ts: "tells every capture how many columns the spread
  shows" failed before the nativePageTurn change ("expected { op: 'capture',
  ... } to match object { columns: 1 }").
- Emulator, API 35 (Readest_API35_7819), Alice EPUB: held poses on main's APK
  (GL) and this build (RuntimeShader), same finger paths. Curl, 6 poses: mean
  pixel difference <= 0.08/255, <= 0.10% of pixels differ by more than 16,
  none by more than 64. Page Flip, 3 poses: <= 1.3% of pixels above 16, none
  above 64, no local shift on the sheet (filtering on text edges); main
  against itself: 0%. Landscape spread switched to GL (ReadestPaperGL) and
  turned; portrait switched back (ReadestPaperUpload) and turned. 5 forward
  and 3 backward taps turned 5 and 3 pages in Curl and in Page Flip, with no
  "Native page turn interrupted" warning.
- Emulator, API 29 (Readest_API29_7542): GL surface only, Curl and Page Flip
  held and turned, no class-loading errors.
- native-bridge Kotlin unit tests (59), the 4 related vitest files (186), the
  paginated browser test (37), pnpm lint, pnpm format:check.

Not run: frame pacing on a 120 Hz device (the PR's benchmark was measured on
its earlier version); iOS (no iOS code changed).

Builds on leehuazhong's RuntimeShader surface (#8100).

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

* test(android): run the paper-turn controller tests on both surfaces

On API 33+ a single-column capture now gets the RuntimeShader surface,
but NativePaperTurnTest cast every surface to NativePaperView. With the
head at 925641e20, 21 of its 22 tests failed on the API 35 emulator,
mostly with "NativePaperRuntimeView cannot be cast to NativePaperView".
PR CI doesn't run instrumented tests.

The base class now forces the GL surface, which spreads and API < 33
still use. NativePaperTurnRuntimeShaderTest runs the same tests on
RuntimeShader: paperFrame() reads its frame by drawing the view
offscreen, and the capture helper asserts which surface it got. The
three tests that hold GL's worker thread are skipped there. A new test
turns a spread on GL, then one column on RuntimeShader again.

Verified with the native-bridge plugin's instrumented suite:
- API 35 emulator: 82 tests, 0 failed, 3 skipped (the GL-worker tests
  on RuntimeShader).
- API 29 emulator: 82 tests, 0 failed; the RuntimeShader tests skip.

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

* fix(android): fail an unreadable capture instead of ending the app

NativePaperRuntimeView read the paper color with getPixel(2, 2) on its
upload thread, outside any handler. A capture under 3 px on a side threw
IllegalArgumentException there and ended the app. NativePaperView
catches the same read and reports the failed upload, which ends the
turn. The RuntimeShader view now does the same.

Verified on the API 35 emulator:
- NativePaperRuntimeViewTest.aCaptureTooSmallToReadFailsTheUploadNotTheApp
  fails without the fix ("Instrumentation run failed due to Process
  crashed", IllegalArgumentException: x must be < bitmap.width()) and
  passes with it.
- Plugin JVM tests: 59 pass.

Found by CodeRabbit on #8101.

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

* test(android): compare the production curl shader with the GL mesh

CylindricalCurlParityTest checks the mesh against the shader's math as
the test writes it, so a change to CURL_SHADER itself could pass. The
new instrumented test renders the same poses with NativePaperView and
NativePaperRuntimeView and compares their pixels: 3 progress values x
2 grab heights x LTR and RTL, with striped pages so a shift shows.

On the API 35 emulator at most 542 of 230400 pixels differ by more
than 16/255 and 35 by more than 64/255; the limits are 1% and 0.1%.
It fails with each of these shader changes:
- the first version's 180-degree roll: 5250 pixels over 64/255
- a back tint of 0.8 instead of 0.6: 21875 pixels over 16/255
- no fold shade: 6973 pixels over 16/255
A fold-shade peak of 0.3 instead of 0.25 passes; that change is under
16/255.

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

* fix(android): refuse a stale capture before reading it on RuntimeShader

NativePaperView checks a capture's validity before it reads the paper
color, so a capture that is already stale is refused quietly. The
RuntimeShader view read the pixel first. A stale capture under 3 px on
a side then reported an error, and the bridge ended the active turn
for a capture nobody needs any more. It now checks first, like GL.

Both surfaces now check validity before the read and again when the
page commits. aStaleReplacementUploadKeepsTheResidentPage goes back to
main's one validity stub for both.

Verified on the API 35 emulator:
- NativePaperRuntimeViewTest.aStaleCaptureIsRefusedBeforeItIsRead fails
  without the fix ("a stale capture is not an error expected null, but
  was:<java.lang.IllegalArgumentException: x must be < bitmap.width()>")
  and passes with it.
- Native-bridge instrumented suite: 83 tests, 0 failed, 3 skipped (the
  GL-worker tests on RuntimeShader). JVM tests: 59 pass.

Found by CodeRabbit on #8101.

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

---------

Co-authored-by: Antigravity (Gemini) <noreply@google.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-30 14:42:15 +01:00
k6G52m4Dz75W
5426965721
chore(deps): bump localsend to v1.19.0 for the fingerprint, PIN and transfer fixes (#8107)
* chore(deps): bump localsend to v1.19.0 for the fingerprint, PIN and transfer fixes

Syncs the pinned readest/localsend fork branch with upstream
localsend/localsend v1.19.0 (44f48f18): 125 upstream commits since the
previous snapshot (6279d3e3), with the fork's two consumer patches
replayed unchanged. Core fixes readest picks up:

- localsend/localsend#3754 - the sender fingerprint of anonymous
  senders now comes from the TLS client certificate instead of a
  spoofable self-declaration
- localsend/localsend#3493 / #3724 - transfers fail with special
  characters in the PIN, and the PIN no longer leaks into HTTP client
  error messages
- localsend/localsend#3683 - filenames normalized to NFC (Korean jamo
  on Windows)
- localsend/localsend#3726 - 5s limit on pinned-client connection setup
- localsend/localsend#3725 / #3730 - cancellation interrupts
  prepare-upload/upload response reads
- localsend/localsend#3450 - an unreadable file fails the transfer
  instead of silently sending an empty body
- localsend/localsend#3424 - reduced file stream read-ahead

Mechanical adaptations, three per consumer plus test-side call sites:

- `add_device` -> `observe_inbound` (rename; the new implementation
  also probes reverse reachability in the background)
- `cert_fingerprint` -> `sender_fingerprint` (readest is HTTPS-only, so
  `Some` still means a verified certificate fingerprint and the
  auto-accept gate is unchanged)
- `into_receiver()` -> `into_stream()`: transfer I/O failures now
  surface as a final stream error instead of a silently truncated body
- test fixtures: `StatefulDevice` gains `confirmed`/`verified` (whether
  a request was ever exchanged and whether the fingerprint is proven) -
  the src-tauri fixture models register-answering HTTPS peers, so both
  hold; two `add_device` call sites in the localsend-bin tests rename
  accordingly

Pin 1609ca7c -> e39c66c2 in src-tauri and localsend-bin; both
Cargo.locks refreshed.

Co-Authored-By: ZCode (GLM-5.3-Flash) <noreply@z.ai>

* chore(deps): pin localsend to the readest fork's v1.19.0 rebase

readest/localsend `readest` is now upstream v1.19.0 (44f48f18) plus the
same two readest patches (flutter submodule `update = none`, best-effort
SO_REUSEPORT), rebased in the fork itself (4ed3532f). Its previous head
1609ca7c stays fetchable as tag readest-v1.18.2-snapshot. Re-pin both
consumers to 4ed3532f instead of a contributor branch head, and finish
what the bump touches:

- Cargo.cef.lock: the Linux CEF build and the Nix package resolve from
  this lock, which still pinned 1609ca7c.
- nix/package.nix: cargoHash blanked for the fod-hashes check to report
  the new value.
- tokio-stream: dropped from src-tauri and localsend-bin; nothing uses it
  now that uploads read `FileContent::into_stream()`.

Verified on this tree (merged with origin/main at 73d45abf7):
- src-tauri: cargo fmt --check, clippy -D warnings clean; cargo test -p
  Readest --lib 217 passed.
- localsend-bin: cargo fmt --check, clippy --all-targets -D warnings clean;
  cargo test 28 passed.
- Real use, Android debug APK (API 35 emulator) <-> Linux CEF dev app,
  both on 4ed3532f: Linux -> Android sent a 404 kB EPUB with a CJK
  file name, Android -> Linux a 3.06 MB one; both arrived byte-identical
  (sha256) and were imported. Both receive dialogs offered pairing, so the
  sender stays certificate-verified after the sender_fingerprint rename.
  A 194 MB send cancelled at 16% from Linux stopped reading at 61 MB,
  left Android's inbox empty with nothing imported, and the next send
  went through. A 194 MB send completed intact.
- Not run: pnpm test / pnpm lint (no TypeScript changed); a physical
  Android phone, macOS, Windows, iOS and the koplugin on a Kindle.

Reported by k6G52m4Dz75W on GitHub (#8106).

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

* chore(nix): refresh cargoHash for the localsend v1.19.0 pin

Value from the fod-hashes check on 7cca1b3a5 (got:), which builds the
vendored cargo sources from Cargo.cef.lock without the cache.

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

---------

Co-authored-by: ZCode (GLM-5.3-Flash) <noreply@z.ai>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-30 14:30:12 +01:00
Anant Kaurav
7f7215c2a2
fix(library): preserve bookshelf scroll state across group navigation (#8105)
* fix(library): preserve bookshelf scroll state across group navigation

Keep Virtuoso StateSnapshot across group/breadcrumb changes in BookshelfStream instead of syncing raw scrollTop in page.tsx.

Co-Authored-By: Antigravity (Gemini) <noreply@antigravity.dev>

* fix(library): keep scroller mounted on in-place sort and view changes

Separate navigationKey (group/shelf/filter) from scrollKey so sort, order, view, and dialog URL params do not remount VirtuosoShelf.

Co-Authored-By: Antigravity (Gemini) <noreply@antigravity.dev>

* fix(library): filter search in place, keep the offset after a column change

The scroller's remount key now holds only the params that pick the view:
group, shelf and groupBy. Before, the search params (q, search, mode,
matchCase, matchDiacritics, nearby) stayed in it, so each debounced
query swapped in a new scroller, jumped to the top and flashed blank.
Both keys now come from one helper, bookshelfStreamKeys in
libraryUtils.ts, which also treats `?group=` as All.

When the rows changed while away (a new column count, a book added),
the snapshot no longer fits them. The list now returns at the saved
offset instead of the top, as main did.

Also updates the comments that still described the removed scroll save.

Verified:
- bookshelf-stream-keys.test.ts fails on the previous key logic:
  "expected 'group=abc1234&q=dune&search=title&mod...' to be
  'group=abc1234'".
- stream.browser.test.tsx: the drill-in check now uses a 60-book group
  and fails on main's BookshelfStream ("expected 'all:50' to be
  'all:0'"). The new column-change return fails without the fallback
  ("expected +0 to be 4500").
- Unit tests in src/__tests__/bookshelves and src/__tests__/app/library:
  95 files, 790 tests pass. Browser tests in the same folders: 11 files,
  169 tests pass. pnpm lint and pnpm format:check pass.
- Production web build, Chromium on Linux, about 95 manual groups with
  nested sub-groups, 5 columns:
  - All > group > sub-group > All returns to the same row and offset.
    The same holds with author grouping ("Back to library") and in
    e-ink, where PageDown still pages afterwards.
  - Typing a search keeps the same scroller and position, with no blank
    frames. A sort change stays in place.
  - With auto columns, resizing from 8 to 6 columns inside a group
    returns to the saved offset (2119) instead of the top.
  - Pull-to-refresh attaches to each new scroller.

Not run: the full pnpm test, the Windows desktop app, phone sizes.

Reported by AnantTux on GitHub (#8104).

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

---------

Co-authored-by: Antigravity (Gemini) <noreply@antigravity.dev>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-30 14:25:40 +01:00
Huang Xin
73d45abf73
fix(payment): keep the plan while a plan switch's bank debit is processing (#8121)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / build_web_app (push) Blocked by required conditions
PR checks / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Switching plans in the Stripe billing portal bills the prorated
difference at once. Paid by US bank debit (ACH), that payment stays
`processing` for days, and Stripe marks the subscription `past_due`
until it clears. getHighestActivePlan counted only `active` and
`trialing`, so the customer.subscription.updated webhook wrote
`plan: free` the moment the subscriber switched: no paid features, and
cloud sync blocked once their library was over the free quota. A new
subscription paid the same way is `active` from the start, so only the
switch hit this.

A `past_due` subscription now counts while its latest invoice's
PaymentIntent is `processing`. When the debit settles, invoice.paid or
invoice.payment_failed (both on the live endpoint) re-resolves the plan,
so a failed debit still drops it as before. Failed card payments are
unchanged.

Reported by a subscriber by email.

Verified:
- stripe-server.test.ts: the two new processing tests fail on main with
  `expected 'free' to be 'plus'` and pass with the fix.
- stripe-server.live.test.ts, read-only against the reporter's live
  subscription (past_due, ACH payment processing): main resolves `free`,
  this branch resolves `plus`.
- pnpm test: 1452 files passed, 0 failed. pnpm lint: clean apart from
  one warning and one info that main has too. pnpm format:check: clean.
- Not run: an end-to-end ACH plan switch with webhook delivery in Stripe
  test mode.

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-29 18:29:17 +01:00
Huang Xin
18824247b9
fix(stats): keep reading time from before the statistics DB opens (#8119)
The reader's stats tracker dropped every page event flushed before
StatisticsDb.open resolved (since #4929). On a first web visit over a
slow network the Turso WASM can take minutes to load, so that whole
session was lost with no warning. Events now wait for the DB to open, as
the TTS recorder's already do.

Verified:
- New test "keeps the pages read and the book closed before the
  statistics DB opens" fails without the change:
  expected [] to deeply equal [ [ 1, 30 ], [ 2, 20 ] ].
- statistics and components/stats suites: 16 files, 182 tests pass.
  pnpm lint and Biome format pass.
- dev-web with the Turso WASM held back by Playwright, a book read and
  closed before it arrived: main showed 0m and 0 pages; this change
  showed 1m and 6 pages. A session read at reading pace kept its speed
  (English 495 words/min).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:25:25 +01:00
Curtis Huttenhower
44c8a2697e
fix(android): consume the key-up of intercepted volume keys (#8092)
* fix(android): consume the key-up of intercepted volume keys

Added ConsumedKeyTracker class to manage volume key events and prevent unintended volume changes during key presses (particularly for KeyUp on firmware such as BOOX that responds to it).

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

* test(android): cover ConsumedKeyTracker

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

* fix(android): consume the key-up of a volume key captured in learn mode

Setting a page-turner key captures a volume key's DOWN natively, as volume
page turning does, but its UP still went to the system. On BOOX, which
changes the volume on key-up, pressing a side button while "Set key" was
listening changed the volume. Record that DOWN in the same tracker so its
UP is consumed too. The volume-key check is now shared by both branches.

Verified on the Readest_API35 emulator (Android 15) with debug x86_64
builds of this branch on origin/main. MediaSessionService logs each volume
key event that reaches the system, which shows which halves got through:
- Learn mode, VOLUME_DOWN then VOLUME_UP: without this commit both
  ACTION_UPs reach the system; with it, none. The keys still don't bind,
  and MEDIA_NEXT binds as before.
- Reader and e-ink library with volume paging on (press, long-press,
  1.5 s hold): no volume event reaches the system, and the same pages
  turn as on main (+3 for the same key sequence). On main every
  ACTION_UP reaches the system, which is how #8091 happens on BOOX.
- Menu open, Read Aloud playing, Use Volume Keys off: DOWN and UP reach
  the system and the volume changes, as on main.
- Interception toggled mid-hold: a consumed DOWN's UP stays consumed
  after the menu opens; a DOWN that went to the system keeps its UP
  after the menu closes.
- Back closes the book; arrow keys, Page Down and a bound MEDIA_NEXT
  still turn pages.
- ./gradlew :app:testUniversalDebugUnitTest: ConsumedKeyTrackerTest 4/4,
  KeyLearnCaptureTest 3/3.
Not run: a BOOX device, the only place the volume changes on key-up.

Reported by chuttenh on GitHub (#8091).

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

---------

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-11-29 13:44:52 +01:00
Huang Xin
60aac44770
feat(stats): reading speed by language over time, synced across devices (#8023) (#8070)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(stats): reading speed by language over time (#8023)

Reading speed was kept per unit (words, characters) for today and all
time only. Speed samples now record the language they were counted in,
the section's lang or else the book's, and Reading Statistics shows:

- a Reading Speed section with each language's average, its change this
  month against last month, and a 12-week trend;
- a Reading Speed page per language: a Week/Month/Year line chart with
  the period's average and its change from the period before, the
  selected day or month with its measured reading time, today/this
  week/this month/highest monthly average, and each book's speed.

The layout follows the reporter's mockup, with the dialog's existing
pieces (boxed lists, the reading time chart's range control and period
arrows). A migration adds `lang` to readest_reading_speed; samples from
before it show under Unknown. Speed samples still stay on the device:
syncing them needs a server table and is left for its own change.

Tests: readingSpeedStats (new) covers grouping by language, local days,
week/year points and period change; statisticsDb covers the migration
on a v0.12.26 database and the two new queries; readingSpeed and
ReadingStatsTracker cover the recorded language; ReadingStats covers the
section and the page (change this month, overview, books, arrow keys,
switching language). Without the change they fail: without the
migration the statisticsDb cases fail with "no such column: lang";
without recording the language the tracker cases fail on the missing
lang ('expected { unit: 'words', count: 80, ... } to match object
{ unit: 'words', lang: 'en' }'); without the dialog wiring the two
ReadingStats cases find no "Englisch" row. 164 tests in the statistics
and stats suites, the calendar browser test (16), lint and format pass.

Verified on dev-web (Chromium, Galaxy S8 360px and 1280px desktop) with
real page turns in an English and a Chinese EPUB on dates from Sep to
Nov: light, dark, e-ink, Arabic RTL, German; tapping chart points.
On the Linux CEF desktop app (native Turso), a statistics.db built at
the v0.12.26 schema with two speed samples migrated to user_version 3,
kept both rows with lang '' (shown as Unknown, 275 words/min), and three
real page turns in Alice were stored as 'en' at 208-221 words/min and
shown as English, 217 words/min.

Reported by Zack9476 on GitHub.

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

* fix(stats): reading speed review fixes from CodeRabbit (#8023)

Five findings from CodeRabbit on #8070:

- Reading Speed by Book joined speed samples to book rows by md5, and a
  KOReader book table can hold two rows of one md5 (keyed on title,
  authors and md5), so such a book's words and time were counted twice.
  It now joins the first row of each md5.
- The 12-week trend dropped weeks without a speed before drawing, so a
  gap of ten weeks looked like a gap of one. Each week keeps its place.
- Language rows were as tall as their content, so a row with the "this
  month" line was taller than one without. Rows are min-h-14 like the
  other boxed-list rows.
- The Details link's tap area was its 19px line. It takes touch-target.
- Speeds from before languages were recorded can be in words and in
  characters, and the picker showed both as "Unknown". Those options now
  name their unit.

Tests: statisticsDb "counts a book's speed once when the book has two
metadata rows" failed with count 120 instead of 60; ReadingStats "spaces
the trend by week" failed with x 0/50/100 instead of 0/9/100; "tells
apart languages that were not recorded" failed with two "Unknown"
options. All pass now, with the 167 tests of the statistics and stats
suites, lint and format. The by-book query returns one row per book on
Turso 0.6.0-pre.9 (the native plugin's version) and 0.6.0-pre.28.

In dev-web at 360px: both language rows measure 56px with and without
the change line; the Details link answers taps 16px above and below its
centre (44px target); Reading Speed by Book still lists the book.

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

* fix(settings): keep sub-page breadcrumbs on one line (owner: Layout for smaller screen, wrapped lines at header is strange)

On a phone, "Reading Statistics › Reading Speed" did not fit: the parent
crumb wrapped onto two lines and the page name was cut ("Reading
Spe…"). Reading Calendar and Statistics by Book did the same, and so did
Settings sub-pages with a long parent ("Custom Translators › Add
Translator" in English, more in longer languages).

Now only the parent shrinks, on one line with an ellipsis, so the page
you are on keeps its full name. The name is cut only when it would leave
the parent less than a 1.5em stub, and the crumb row fills the header
so the cap measures the room the row really has.

Tests: a 360px browser test opens the three statistics sub-pages in en,
de, el, ka and ta and checks the parent stays on one line and the page
name is cut only once the parent is down to its stub. On the old header
it fails in all five: en, el, ka and ta with "expected 2 to be 1" (the
parent took two lines), de with "expected 105 to be 27" (the name was
cut while the parent kept 105px). The statistics and Settings sub-page
suites (64) and the browser file (21) pass; lint (tsc + biome) passes
apart from a warning in a file this change doesn't touch.

Checked against the old header on every Settings breadcrumb (30 pairs)
in en, de, fr and ka at 296px (phone) and 520px (desktop dialog): 172
of 240 render identically, all desktop ones among them; 53 now show the
page name in full where the parent wrapped or the name was cut; 15 are
still cut, never shorter than before; none wraps. On dev-web at 360px
(Galaxy S8) the three statistics sub-pages are one line in English,
German, French and Arabic.

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

* fix(settings): keep the breadcrumb's back target large when it shrinks

Since the parent crumb gives up its width first, it can shrink to its
1.5em stub (27px), and its hit area shrank with it. The button now
carries touch-target, which grows the hit area to 44px without
widening what you see, and the label is cut inside the button: the
clip used to sit on the button itself and would have cut the larger hit
area too. Raised by CodeRabbit on #8070.

Tests: the 360px breadcrumb browser test now taps 4px below the parent
crumb and, at its stub, 6px to its left; both reach the crumb. On the
previous header it fails in all five locales ("expected false to be
true" at the tap below). The browser file (21), the statistics and
Settings sub-page suites (64) and lint pass. On dev-web at 360px the
breadcrumb band of all three statistics sub-pages is pixel-identical
to before.

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

* feat(sync): sync reading speed across devices (#8023)

Reading speed stayed on the device that measured it, so each device
showed only its own languages and history. It now syncs through
Readest Cloud like the page events, behind the same stats sync switch.

A device pushes one row per book, language and unit for each quarter
hour it read in, keyed by its first sample there: about four rows per
hour of reading instead of one per page, so the server table needs no
archive. Two devices never share a key, and a row only grows while its
quarter hour lasts, so the server keeps the longer copy. Pulled rows
are kept apart from this device's own samples (a `remote` flag), so a
device's own row coming back meets its first sample's key and is
ignored. Deleting a book's statistics deletes its speed on every
device: the pull flags rows that started before the book's deleted_at.
Merging moves the source's speed, its own and pulled, to the target.
A server without speed sync still syncs and merges the pages.

Server: migration 036 adds stat_speeds with RLS and the
upsert_stat_speeds merge RPC; /api/sync/speeds pages its pull on the
(updated_at, book_hash, start_time_ms) keyset. Deploy both before
releasing clients that push speed.

Tests: speedSync covers the push (one row per quarter hour, sent again
only when it grows, pulled rows never sent back), the pull (counted
once, own rows and deleted books skipped, keyset paging, a minute of
overlap) and the merge; sync-speeds covers the route; ReadingStats
covers the dialog's pull. Removing each behavior fails its test on an
assertion: without the echo guard the totals read count 340 for 270,
without skipping deleted rows 370 for 270; pushing pulled rows changes
the pushed rows; without the changed-quarter check the push runs twice
for once; without the merge push "expected to be called with
arguments"; without the route's flag ['x', 1000, false] for true;
without the dialog's pull "expected to be called at least once". The
related suites (53 files, 641 tests), lint and format pass. The new
local SQL gives the same results on Turso 0.6.0-pre.9 (native app) and
0.6.0-pre.28.

Verified end to end on a self-hosted Supabase (repo migrations, 036
applied) with dev-web and three browser profiles on one account. Device
A, holding Sep-Nov history, pushed 10 rows; a fresh device B then showed
the same English 180 words/min and Chinese 249 characters/min as A.
After B read three pages of Alice, both showed English 203 words/min
(+25.5% this month), matching the server's sum. After Alice's
statistics were deleted, A and a newly signed-in device C showed only
Chinese.

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

* fix(sync): order the speed pull after pages, keep merges retryable

From CodeRabbit's review of #8070:

- The reader started the page pull and the speed pull together. Speed
  fetched just before another device deleted a book could be applied
  after the page pull removed it, bringing its rows back. The speed
  pull now starts once the page pull settles, as the dialog already did.
- A merge carried on after any failure to move the speed, then deleted
  the source on the server, so speed this device had already pushed
  never reached other devices under the target. Only a server without
  speed sync lets it carry on now; any other failure stops before the
  deletion, so the merge can be retried. SyncClient tells the two apart:
  a 404 (no /api/sync/speeds) reads as "no speed sync" (null / false)
  instead of an error, which also stops the reader warning on every
  push against such a server.
- The push route read fields of a null row and failed the batch with a
  500; it now rejects that row and stores the rest.
- The pull test's leftover empty response was consumed by its second
  pull, so the shorter-row check never ran. It runs now: without the
  longer-wins rule it fails with count 130 for 270.

Tests: before the fix the new ReadingStatsTracker case failed with
"expected not to be called at all, but actually been called 1 times"
(speed pulled while the page pull was pending); the merge case with
"promise resolved undefined instead of rejecting"; the client case
threw "Failed to pull speeds" on a 404; the push-cursor case with
"expected 1800000001000 to be +0"; the route case with "Cannot read
properties of null". The related suites (55 files, 651 tests), lint
and format pass.

On the self-hosted stack with dev-web: device B read three pages of the
Chinese book; the server log shows its stats pull, then its speed pull,
then three speed pushes; device A then showed the server's total, 276
characters/min. With the route removed (404), A's statistics still
showed its local speed, and the app logged no speed warning.

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

* feat(sync): carry reading speed in page events' ext (owner: Can we sync the raw data, and make every device calculate the speed?)

Replaces the stat_speeds table and /api/sync/speeds route from 119bf2801
and b08db6c10. Reading speed now syncs with the page events it was read in,
so no server change is needed.

- A speed sample waits for the next page event the tracker saves. The page
  turn that ends a sample also saves that page, so the sample goes with it.
  When an idle pause has already saved the page, the next page carries it.
  The event keeps the samples summed per language and unit as
  `{ speed: [{ lang, unit, count, durationMs }] }`.
- Locally, the event's ext goes in the existing readest_page_ext table. The
  speed queries read rows built from it, starting where the event starts.
  Every device builds them the same way for every event it holds, so a
  device's own events coming back from the server meet the same keys and
  change nothing. That removes the remote flag, the speed cursors and the
  dedup guard.
- Push sends ext with each event. /api/sync already stores and returns it,
  and the archive keeps it. Pull reads it, dropping entries it can't
  read. Merges carry ext under the target, and deletions remove it.
- Speed saved before this change stays on its device, and is still merged
  and deleted with its book.

Verified:
- New and converted tests fail without the change, each on an assertion,
  e.g. pageSpeedSync "expected null to deeply equal { speed: [...] }" and
  ReadingStatsTracker "expected [] to deeply equal [[{ lang: 'en', ... }]]"
  (12 failing tests across 5 files); all pass with it.
- 828 tests in the 93 related files (statistics, stats components,
  api routes, libs, database) and pnpm lint pass.
- dev-web on a local self-hosted Supabase whose schema is main's
  (stat_speeds dropped), two fresh browser devices on one account. The
  server rows carry each page's speed in ext. Both devices show English
  398 words/min and Chinese 454 characters/min, the totals of those rows.
  After the second device read more English, both show the combined 327
  words/min. The first device's own events coming back left its numbers
  unchanged.
- Not run: the Tauri app (native Turso). The SQL ran on the Node build
  (tests) and the web WASM build (dev-web).

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

* fix(sync): date page-event speed by its first sample, read events with it

From CodeRabbit's review of 2d91afea8:

- A page event's speed now keeps the start of its first sample, per
  language and unit (`startTimeMs` in ext), and its rows are dated by it.
  A sample that a later page carries after an idle pause stays on the day
  and quarter hour it was read in. Keyed by that millisecond, two pages of
  a book that start in the same second no longer share a key and drop one
  page's speed.
- The push read and the merge push's read of a book's events take the
  write lock. An event and its speed are saved in two statements, and a
  push that read the event alone moved its cursor past the speed.
- Backups write the page events as they are, so they now carry speed
  too. Applying events from another device or a backup keeps only the
  speed this version can read: an entry the table rejects would roll back
  the whole statistics restore.

Verified:
- Each new test fails without its fix on an assertion: "expected [] to
  deeply equal [ { startTimeMs: 86280000, ... } ]" (dated by the carrier),
  "count: 30 to deeply equal count: 60" (same-second pages), "expected
  [ undefined ] to deeply equal [ [ { lang: 'en', ... } ] ]" (push and merge
  reads), "promise rejected ... CHECK constraint failed ... instead of
  resolving" (unreadable speed from a backup). The tracker test fails on
  the missing sample start.
- 6692 tests in 505 files (statistics, components/stats, pages/api, libs,
  services) and pnpm lint pass.
- dev-web on the self-hosted stack with main's server schema, new account,
  two fresh devices: the server rows carry startTimeMs; both devices show
  English 388 words/min, the total of those rows.

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

* fix(sync): keep each speed sample a page event carries

From CodeRabbit's follow-up on 3bc452b5b: summing a page's samples per
language and unit dated the sum by its first sample. When a page carried a
sample from before an idle pause along with its own, the second sample
took the first one's start and could land on the day before. A page
carries one to three samples, so ext now holds each one as it is, with
its own start, and sumPageSpeed goes. Each speed row is one sample again,
as in the table since it shipped.

Verified:
- New tracker test "keeps each sample a page carries, with its own
  start" (page 2 carries page 1's sample from before midnight and its own
  from after) fails without the change: "expected [ [ { lang: 'en', …(4) }
  ] ] to deeply equal [ [ { lang: 'en', …(4) }, …(1) ] ]".
- 176 tests in statistics and components/stats, and pnpm lint, pass.
- dev-web on the self-hosted stack, same account as before: the
  Chinese pages each carry their sample in ext. The second device shows
  Chinese 413 characters/min and English 388 words/min, the server's
  totals.

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

* fix(stats): name speed with no language when showing it (owner: Can the language fill process be defered when displaying the speed data instead of in the migration process, so that it could be safer?)

Speed saved before languages were recorded (v0.12.26) has no language, so
Reading Statistics listed it under Unknown. It now shows it in its book's
language from the library, else in the app's interface language, when that
language is counted in the same unit (words or characters). Otherwise it
stays Unknown. This answers "Can we fill the lang column from the library
book row data (with the current system language as fallback) when migrating
instead of using the Unknown data?", but only when showing: the migration and
the saved rows are unchanged, and nothing is written back. Speed quarters are
read per book so each can be named. If the library can't be read, the speed
shows under Unknown as before.

Tests that fail without it (run against stubs, then the change):
- readingSpeed guessSpeedLanguage: expected '' to be 'fr'.
- readingSpeedStats nameSpeedLanguages: expected [['m1', '', 'words'], ...]
  to deeply equal [['m1', 'fr', 'words'], ...].
- statisticsDb per-book quarters: expected [{ quarter: 1, lang: '', ... }] to
  deeply equal [{ quarter: 1, md5: 'old', ... }].
- ReadingStats dialog: expected 'Französisch100 words/min' to contain
  '200 words/min', and the library read from disk: expected "vi.fn()" to be
  called at least once.
- Without the fallback when the library can't be read: expected null not to
  be null (no Unknown row).

Verified:
- statistics and components/stats: 16 files, 181 tests pass. pnpm lint
  passes; Biome format is clean.
- Linux CEF desktop app (native Turso): a v0.12.26 statistics.db with speed
  for a library book (English), a removed book counted in words and one
  counted in characters, with the app in German. Reading Statistics showed
  Englisch 250 words/min, Deutsch 300 words/min and Unbekannt 400
  characters/min, and the English page listed the library book. The three
  saved rows still had lang '' afterwards.
- dev-web (WASM): a profile from the earlier end-to-end run still shows
  English 388 words/min and Chinese 413 characters/min.

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

* fix(sync): keep a page event's ext when a longer copy has none (owner: add the COALESCE hardening to the server migration)

upsert_stat_pages and upsert_stat_pages_as replace a stat_pages row when the
same event arrives with a strictly longer duration, and replaced its ext
with whatever the copy carried. KOReader and older app versions push events
without ext, so such a copy would drop the reading speed a Readest device
saved in it. Migration 036 keeps the stored ext when the incoming copy has
none; a copy with its own ext still replaces it. Nothing else changes: each
function is 019's / 020's with only the ext line changed.

Test that fails without it: scripts/db/verify-migration-036.sh, on
PostgreSQL 15 (supabase/postgres:15.8.1.085). With 036 re-creating both
functions under the old rule it fails with "ERROR: upsert_stat_pages keeps
ext a longer copy lacks"; with only upsert_stat_pages changed, with
"ERROR: upsert_stat_pages_as keeps ext a longer copy lacks". With the change:
"ALL MIGRATION 036 CHECKS PASSED".

Also run:
- verify-migration-020.sh with 036 applied after 021: all checks pass,
  including the upsert_stat_pages_as merge and that anon/authenticated still
  can't execute it.
- statistics, components/stats, docker, libs, pages/api suites: 95 files,
  850 tests pass. pnpm lint passes.
- Not run: applying 036 to the production database.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 07:57:49 +01:00
Bartolomeo Pasquale
2b4c8e501a
fix(kosync): read a bare DocFragment XPointer as the start of its section (#8088)
Kavita answers a KOSync pull with `/body/DocFragment[N].0` when it has no
element path for the stored position (for example a scroll position saved by
its web reader as an `id("…")` selector). KOReader opens the start of that
DocFragment. Readest classified it as an XPointer, failed in
`XCFI.extractSpineIndex` (which wanted a `/` after the fragment) and then in
`resolveXPointerPath` (which wanted `/body` after it), so the pull ended in
"Sync failed" and the reader did not move.

Both regexes now also accept `/body/DocFragment[N]` and
`/body/DocFragment[N].N`, resolved to the body of section N-1.

Verified:
- New test xcfi.kosync-section-start.test.ts fails on main on all four
  section-start cases ("Cannot extract spine index from XPath") and passes
  with the change, as does its rejection case.
- Full unit suite (vitest run): 1447 files, 17878 tests passed.
- biome lint: no findings in the changed files. tsc: no errors in the
  changed files (the only errors come from the tauri-plugin-turso
  submodule, not checked out here).
- Not run: the Android app against a live Kavita server.

Fixes #8086. Reported by bart1208 on GitHub.

Co-authored-by: Bart <6011032+bart1208@users.noreply.github.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-29 07:38:47 +01:00
Huang Xin
d642655197
feat(xray): underline known names in the text, tap for X-Ray (#8015) (#8080)
* feat(xray): underline known names in the text, tap for X-Ray (#8015)

A new switch under Manage Dictionaries > X-Ray, Underline Names in the
Text, off by default, draws a dotted underline under every name and alias
the X-Ray knows up to the current page. A tap on one opens its X-Ray card,
or shows it in the Notebook's X-Ray tab while that is open. It uses the
stored X-Ray and asks no AI, and the card keeps its spoiler limit.

The underlines are a CSS custom highlight, so the book's DOM is left as it
is for CFIs, annotations and Read Aloud. Links and Word Lens hints are
skipped, and names match on whole words the way X-Ray's mentions do
(CJK names without word boundaries). They are redrawn for each new section
and each X-Ray update. WebKit before 17.2 has no custom highlights and
shows none. The setting syncs with the other dictionary settings, and its
two strings are translated in all 34 locales.

Verification:
- Fails without the change:
  - AnnotatorLookupSurfaces.test.tsx, "opens the X-Ray of the name
    alone": no dictionary-surface. "shows it in the X-Ray tab while that
    is on screen": "expected undefined to be 'Alice'".
  - iframeEventHandlers.test.ts, "opens its X-Ray instead of turning the
    page": dispatch never called with 'xray-name'.
  - CustomDictionaries.test.tsx: no checkbox named "Underline Names in
    the Text".
  - custom-dictionary-store.test.ts (after a load) and the sync
    settings.test.ts round-trip: "expected undefined to be true".
  With the change they pass, with the new useXRayNames.test.ts and
  xrayNames.browser.test.ts (Chromium and WebKit 4/4), and the related
  suites (24 files, 364 tests).
- pnpm lint and pnpm format:check pass, on the change rebased onto main.
- Android 17 emulator, debug APK, Alice in Wonderland:
  - After Update X-Ray, all 23 "Alice"s in Chapter 3 were underlined. A
    tap on one opened its X-Ray card alone, and a tap on plain text
    turned the page.
  - At the start of Chapter 1, before the first X-Ray batch ends, no
    name was underlined. From Chapter 2 on they were. Switched off, none
    was.
  - Checked in light, dark and e-ink.
  Not run: the docked X-Ray tab on a tablet (a unit test covers it), Word
  Lens on at the same time, and iOS. Whether X-Ray is available is read
  when the section changes, so after a sign-in while reading the names
  show from the next section on.

Reported by Zack9476 on GitHub.

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

* fix(xray): underline names as the page and the text change (#8015)

From the review:
- Names were picked once per section. A turn within a section now
  re-reads them, so a name the page reaches is underlined and one ahead
  of it is not. Most turns reach no new name and leave the page alone.
- Word Lens moving a hinted name into a <ruby>, or back out, emptied its
  underline until the section changed. The names are marked again when
  Word Lens or a translation rewrites the text (the annotator's
  contentEpoch).
- A name broken by a line of the source, "White\n    Rabbit", now matches.
  X-Ray's mentions share the pattern.

Verification, each failing before the change:
- useXRayNames.test.ts:
  - "marks a name the page reaches…": "expected [ … ] to have a length
    of 1 but got 2".
  - "marks again once Word Lens or a translation rewrites the text":
    "… to have a length of 2 but got 1".
- AnnotatorPageTurn.test.tsx: the hook got { location: 'ch2.xhtml' }, the
  section, not the page.
- xrayNames.browser.test.ts: "expected [] to deeply equal
  [ 'White\n    Rabbit' ]". Now 5/5 in Chromium and WebKit.

The reader, components, store, sync, xray and dictionaries suites pass
(472 files, 5049 tests). pnpm lint and pnpm format:check pass, on the
branch rebased onto main.

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

* test(xray): keep the view stable in the X-Ray revision and premium tests (#8015)

From the review: both tests built a new view on every render, which reran
the hook's effect on its own, so they passed even without the revision
dependency. With the view built once, dropping `revision` from the deps
fails both: "marks the names a new X-Ray knows" and "clears the names
without premium". With it, the 7 hook tests pass.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 07:37:07 +01:00
Huang Xin
de65f65e8b
feat(reader): offer System Dictionary as a quick action (#8016) (#8079)
* feat(reader): offer System Dictionary as a quick action (#8016)

With System Dictionary on in Manage Dictionaries, the other rows lock.
Turning X-Ray on meant turning System Dictionary off, and a long-pressed
word then opened the in-app popup instead of the OS dictionary.

System Dictionary is now a Quick Action (Settings > Behavior > Annotation
Tools) on macOS, iOS and Android. A long-pressed word goes to the OS while
the in-app dictionaries, X-Ray included, stay on for the Dictionary tool.
A selection longer than one word, or a synced device with no system
dictionary, opens the toolbar. Other platforms don't list it.

Verification:
- Fails without the change:
  - AnnotatorLookupSurfaces.test.tsx, "hands a long-pressed word to the OS
    with the in-app dictionaries on": "expected undefined to be
    'serendipity'".
  - ControlPanelDevice.test.tsx: "expected [ 'None', 'Copy', … ] to
    include 'System Dictionary'".
  - Without the platform guard, "opens the toolbar on a device without a
    system dictionary" saw the OS handoff called once.
  With the change they pass, as do the annotator suites (18 files, 158
  tests).
- pnpm lint and pnpm format:check pass, on the change rebased onto main.
- Android 17 emulator, debug APK:
  Quick Action set to System Dictionary, with X-Ray, Wiktionary and
  Wikipedia on and the System Dictionary row off: a long-pressed
  "looking" started ACTION_PROCESS_TEXT and the device's default handler
  opened.
  Not run: macOS and iOS, and a dictionary app on Android. The emulator's
  only handlers are the Google app and Select to Speak.

Reported by Zack9476 on GitHub.

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

* test(settings): give the ControlPanel suites the app service it now reads (#8016)

ControlPanel lists System Dictionary as a quick action only where the OS
has one, which it asks the app service. ControlPanelScrolledMode and
ControlPanelUpdateReset mocked @/services/environment without
getInitializedAppService, so 13 of their tests failed in CI with 'No
"getInitializedAppService" export is defined on the mock'. The mocks now
return no app service, as on web.

Verification: before this commit, the components and reader suites failed
those 13 tests and passed the other 2701. Now the settings suites pass
(39 files, 269 tests).

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

* docs(reader): say which devices keep the toolbar for the System Dictionary quick action (#8016)

The comment read as if an Android with no dictionary app fell back to the
toolbar. Only a platform without a system dictionary does. On Android the
handoff stays silent when no app takes the word, as the System Dictionary
row does on a long-press. Comment only.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:13:24 +01:00
Huang Xin
aa13f221ce
fix(reader): show each Curl and Page Flip sheet's own bookmark ribbon (#8076) (#8096)
Curl and Page Flip on Android and iOS capture the next and previous
pages with paginator.previewPage(), and the capture includes the
bookmark ribbon overlaid on the page. The ribbon followed the current
page, so the page revealed mid-turn carried the current page's ribbon
state: a ribbon on a page without a bookmark, or none on one with it.

Foliate's preview event now carries the previewed page's CFI
(readest/foliate-js#206). FoliateViewer puts it in the page preview as
its location, and while a preview is up, BookmarkPullDown matches that
location against the book's bookmarks instead of the current page's
state. The bookmark match moves into isLocationBookmarked in
utils/cfi.ts, which BookmarkToggler now uses too.

foliate-js is pinned at its main, 86522d9. The old pin fb174ec (#204)
never reached foliate main: it was stacked on #203 and merged into
#203's branch. readest/foliate-js#205 re-landed it unchanged, so the
code diff from the old pin to this one is #206's view.js change alone.

Verified:
- Tests that fail without the change: in BookmarkPullDown.test.tsx,
  "shows the ribbon on a bookmarked page from a page that isn't"
  (expected null not to be null) and "hides the ribbon on a page
  without a bookmark, then brings it back" (expected <div…> to be
  null); the preview test in foliate-viewer-relocate.test.tsx (progress
  location was the current page's); and "previews the location a turn
  then reaches" in paginator-paginated.browser.test.ts at the old pin
  (no cfi in the preview). All pass with the change.
- 13 related unit test files (218 tests) and the paginator-paginated
  browser file (37 tests) pass. pnpm lint and pnpm format:check pass.
- dev-web, Alice EPUB: with a bookmark on one page, the ribbon at the
  moment each neighbour page is captured matches that page. With the
  preview event dropped, as on main, it shows the current page's state.
- Android API 35 emulator, debug build, each turn held mid-way: Page
  Flip from a bookmarked page reveals a next page without a ribbon (it
  carried one before the fix); Curl from a page without a bookmark
  reveals the bookmarked page with its ribbon (none before the fix).

Not run: iOS. It takes the same code path, but WKWebView takes the
snapshots. Not reproduced: deleting a neighbouring page's bookmark from
a pinned sidebar may leave an already-captured sheet with the old
ribbon until the captures refresh.

Reported by chrox on GitHub

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:09:42 +01:00
Huang Xin
aa574c8500
fix(reader): keep Close on screen when the Go Back title is long (#8098)
The Go Back / Go Forward pill after an in-book jump names the chapter it
returns to. With a long chapter title the name ran past the screen edge on
a phone and took the Close button with it, so the pill could only be
dismissed by waiting out its 15 s timeout. daisyUI's .btn sets
flex-shrink: 0, so the label button kept its full text width and its
truncate class never applied. `shrink` lets the button give up width; the
label is cut with an ellipsis and Close stays in the pill. A short title
is unchanged.

Verified:
- JumpReturn-long-title.browser.test.tsx (new, Chromium at 390px, LTR and
  RTL) fails without the change: "expected 631.46875 to be less than or
  equal to 390" (LTR) and "expected -241.46875 to be greater than or
  equal to 0" (RTL); passes with it, 3/3.
- dev-web, iPhone 13 preset, an EPUB with the reporter's long chapter
  title, real TOC jump: Close at x 611-647 of 390 on main's DOM, 338-374
  with the fix; tapping Close hides the pill. Same in dark mode, e-ink
  (title stays inside the 1px border) and the Arabic UI.
- JumpReturn.test.tsx 3/3, pnpm lint (exit 0; its 1 warning and 1 info
  are in untouched files), pnpm format:check.
Not run: the full unit suite (left to CI); an iOS device.

Reported by calvin011101 on Reddit.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 04:08:28 +01:00
Huang Xin
866944d2bb
fix(sync): drop NUL from reading-stats book titles before saving (#8095) (#8097)
The KOReader plugin's "Push reading stats" failed every time with "The
server is temporarily unavailable". The reporter's KOReader log has the
server's answer: HTTP 500 "unsupported Unicode escape sequence".

PostgreSQL can't store U+0000 in text, so one "\u0000" in a JSON string
fails the whole statement. KOReader's statistics database can hold a book
title or author with a NUL byte, and the plugin's dkjson encoder sends it
as \u0000. The stat_books upsert then returns 500. The push cursor only
advances on success, so every later push resent the same chunk and failed.

Books and notes already strip NUL with sanitizeString in transform.ts.
The stat_books upsert added later never did. Run its title and authors
through the same helper. Since the fix is server-side, older plugins work
once web is deployed.

Verified:
- New test sync-strip-nul.test.ts (its mock rejects \u0000 like
  PostgREST). Without the fix: "expected 500 to be 200". With it: passes.
- PostgreSQL 15: json_populate_recordset with "A\u0000B" gives "unsupported
  Unicode escape sequence"; the same row with "AB" inserts.
- pnpm test: all files pass. pnpm lint: clean.
- Not run: a real push from KOReader against a server with this fix. The
  reporter's device is a Kobo, and which book holds the NUL is unknown.

Reported on Reddit, with the KOReader log sent by email.

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-29 04:07:46 +01:00
Huang Xin
e25de146b8
fix(windows): stop the Explorer preview handler from freezing File Open dialogs (#8081)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* fix(windows): stop the Explorer preview handler from freezing File Open dialogs

With the preview pane on in a File Open dialog (Readest's import, a browser's
upload, any app), selecting an ebook left the pane blank and clicking Open
froze the dialog as "Not Responding".

windows-rs `#[implement]` objects are agile by default: they answer
IAgileObject and hand out the free-threaded marshaler. prevhost.exe then runs
the dialog's calls (Initialize, SetWindow, DoPreview, Unload) directly on RPC
worker threads instead of the STA that created the handler. DoPreview created
the preview window on such a thread, which never pumps messages: the window
never painted, and the dialog blocked forever when it tore the pane down.
The provider is now `Agile = false`, so COM marshals every call to its STA.

The size of the EPUB doesn't matter (a 400 KB book froze the same way), and
DisableProcessIsolation isn't involved: the DLL is loaded by prevhost.exe,
not by the dialog's process. DoPreview took ~110 ms on a 3,100-entry EPUB.

Verified on a Windows 11 24H2 VM with Readest 0.12.26 installed as the
.epub default, preview pane on:
- WinForms Open dialog, select then tap Open, a 12 MB / 3,100-entry EPUB and
  a 400 KB EPUB, two runs each: the shipped 0.12.26 DLL hung 4/4; the fixed
  DLL (MSVC build) previewed the cover and returned 4/4.
- Readest Import Books > From Local File: shipped DLL "Open (Not
  Responding)"; fixed DLL previews the cover and imports the book.
- Edge file upload: shipped DLL "Open (Not Responding)"; fixed DLL passes
  the 11.9 MB file to the page.
- A logging build showed every call on an MTA RPC thread (neutral apartment)
  before the fix and on prevhost's STA after it.

Test: provider_is_not_agile fails without the change ("IAgileObject must not
be implemented, or COM bypasses the provider's apartment") and passes with
it. Crate tests 7 passed under Wine (x86_64-pc-windows-gnu); cargo fmt
--check clean. cargo clippy -D warnings reports the same 3 errors on main
(new clippy 1.98 lints in untouched code; no CI lints this crate). pnpm test
and pnpm lint not run: no app code changed.

Closes #8073. Reported by lilinng-163 on GitHub.

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

* fix(windows): make the preview handler's class factory non-agile too

The factory was still agile. An MTA caller that gets it through
CoGetClassObject (the class is ThreadingModel=Apartment) would receive a
direct pointer and run CreateInstance on its own thread, so the provider and
its preview window would again live on a thread that never pumps messages.
With Agile = false the call is marshaled to the STA that loaded the DLL.
Found by CodeRabbit on #8081.

Test: provider_and_factory_are_not_agile (extended from
provider_is_not_agile) fails without the change with
"ThumbnailProviderFactory must not implement IAgileObject, or COM bypasses
its apartment" and passes with it. Crate tests 7 passed under Wine; cargo fmt
--check clean.

Verified on the Windows 11 24H2 VM with this commit's MSVC build installed in
Readest 0.12.26: WinForms Open dialog with the preview pane on, select then
tap Open, 12 MB and 400 KB EPUBs twice each, returned 4/4. With Explorer
thumbnails turned on, fresh copies of both EPUBs in a new folder showed
their covers as large icons.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 03:19:55 +01:00
Huang Xin
d745a8be26
fix(reader): wrap selection toolbar tools onto more rows (#8013) (#8078)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
The selection toolbar lays its 32 px tools in one row up to the popup's
maximum width: 335 px on a 360 px phone, room for 9. The rest scrolled
sideways with no scrollbar, so a 10th tool such as X-Ray was out of
sight. Tools that don't fit now wrap onto rows of even length (10 tools
make 2 rows of 5), and the highlight colour strip sits past the last row.
A toolbar that fits in one row, or the notes view, is laid out as before.

Verification:
- Fails without the fix:
  - annotation-popup-layout.browser.test.tsx, "a toolbar with more tools
    than fit", in all four placements: "expected 529 to be less than or
    equal to 500", a tool past the popup's edge.
  - AnnotatorSafeArea.test.tsx: "expected { width: 300, height: 44 } to
    deeply equal { width: 220, height: 88, columns: 5 }" for 10 tools.
  With the fix they pass, as do the annotationToolbar.test.ts cases for
  getToolbarGrid and the annotator suites (18 files, 172 tests).
- pnpm lint and pnpm format:check pass, on the change rebased onto main.
- Android 17 emulator, debug APK, 360 dp wide:
  - 12 tools with X-Ray last: on main nine showed whole and a tenth was
    clipped. Share and X-Ray were out of sight (the row's scrollWidth
    400, clientWidth 333). With the fix: 2 rows of 6, all inside the
    popup.
  - 10 tools: 2 rows of 5 in light, dark and e-ink. The X-Ray tool on the
    second row opened the X-Ray.
  Not run: a vertical book on the device. The browser test covers all
  four placements.

Reported by cpuks on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:32:27 +01:00
Huang Xin
c3f9dc73ae
fix(xray): wait out an Android freeze, and name a stalled AI reply (#8013) (#8077)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / build_web_app (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
On Android, X-Ray failed with "Failed to process successful response".
That is the AI SDK's wording for X-Ray's own idle abort, which fires when
a reply goes 60 s without a chunk (5 min before the first). Tauri's HTTP
plugin ends an aborted body with the string "Request cancelled" instead of
an AbortError, so the SDK wraps it as a failed response.

Android freezes an app in the background, and its timers fire late once
it thaws. On an Android 17 emulator, freezing the app and its WebView for
90 s mid-reply made the idle timer fire 6 s after the thaw, while the
server was still streaming. A timer that fires more than 10 s late now
waits again instead of aborting. A real stall reads "The AI provider
stopped responding.", translated in all 34 locales.

Verification:
- Fails without the fix, in xray.test.ts:
  - "says a server gone silent stopped responding" rejected with
    "Failed to process successful response".
  - "waits again for a reply once the app is back from a freeze" saw the
    request aborted 31 s after a 90 s clock jump.
  Both pass with the fix, as do all 26 X-Ray tests.
- pnpm lint and pnpm format:check pass, on the change rebased onto main.
- Android 17 emulator, debug APK, Alice in Wonderland, stub
  OpenAI-compatible server:
  - The app and its WebView frozen for 90 s mid-reply, the reply
    streamed 4 characters every 2 s: on main the request was closed 6 s
    after the thaw and X-Ray showed "Failed to process successful
    response". With the fix both batch requests finished 25 s after the
    thaw and the X-Ray tab listed the character.
  - A reply that drops after two chunks: on main "Failed to process
    successful response" a minute later. With the fix "The AI provider
    stopped responding."
  Not run: the reporter's own AI provider.

Reported by cpuks on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:30:10 +01:00
leehuazhong
1775243427
fix(reader): show each Curl and Page Flip sheet's own page number and chapter (#8068) (#8069)
* fix(reader): preview target page counters and header during native page-turn captures

Pre-captured adjacent sheets in NativePageTurn and PageTurnBuffer use paginator.previewPage(), which intentionally skips relocate events. Because ProgressBar and SectionInfo overlay the full renderer bounds, PixelCopy/snapshot captures previously baked the current page's page number and remaining-page count onto neighbouring sheets.

Add a lightweight display-only pageTurnPreview store (subscribed only by ProgressBar and SectionInfo) that previews the target page's progress, remaining pages, and section label while previewPage() captures an adjacent sheet, and releases only after previewPage() restores containerPosition so live readouts never sample the previewed renderer.page.

Co-Authored-By: Antigravity (Gemini) <noreply@google.com>

* fix(reader): show each Curl and Page Flip sheet's own page number and chapter (#8068)

Native Curl and Page Flip capture the next and previous pages ahead of a
turn with paginator previewPage(), which paints the page without
relocating. The running header and footer sit over the renderer box, so
the captures took them in still showing the page being read: page number,
pages left, progress fill and, at a chapter boundary, the chapter title.
They caught up only once the turn landed.

This reworks the first version, which estimated the neighbour's numbers
in Readest (pageTurnPreview.ts) from section fractions and the renderer's
page count, through hooks in NativePageTurn and PageTurnBuffer. That
estimate can disagree with what foliate reports after the turn (two-column
spreads, lead pages, chunked chapters, which it skipped), and with no
range for the page, the chapter title inside a multi-entry chapter and the
printed page label stayed stale. Now foliate names the previewed page
itself (readest/foliate-js#204, pinned at fb174ec): `preview` carries what
a relocate there reports, then null once the reading position is back.
FoliateViewer keeps it as a display-only PagePreview in readerProgressStore,
built the way setProgress builds progress. ProgressBar, SectionInfo and the
screen-page pair read it; reading progress, history and sync never see it.

Verified:
- Fails without the change: the paginator-paginated browser test
  "previews the location a turn then reaches" (360 and 800 px) fails on
  the old foliate pin with "expected [] to have a length of 2". The new
  ProgressBar, SectionInfo and foliate-viewer-relocate tests fail on
  main's components with "expected '3 / 10' to be '4 / 10'", "expected
  'Chapter 1' to be 'Chapter 2'" and "expected undefined to match object".
  All pass with it.
- 39 paginator and page-turn browser files (464 tests), the 5 browser
  files that mock the progress store, and 92 related unit files (1434
  tests) pass. pnpm lint and pnpm format:check pass.
- Android emulator (API 35, debug x86_64 build of this branch, the Alice
  EPUB, Show Remaining Pages on), each turn held mid-way:
  Curl forward: the revealed page reads 16 / 112 while the outgoing page
  reads 15 / 112. Curl backward: the incoming page reads "11 pages left in
  chapter", as after the turn. At a chapter boundary the next chapter's
  first page shows its own count ("pages left", 19 after the turn) and
  the trace shows its chapter title in the header during the capture.
  Page Flip backward: the incoming half reads "11 pages left in chapter",
  as after the turn.
  With foliate's preview event dropped over CDP (main's behaviour) the
  same curls show 29 / 112 for a page that is 30 / 112, "8 pages left"
  where the turn lands on 9, and "1 page left" on the next chapter's
  first page.
- Not run: iOS (same JS path; WKWebView snapshots).

Reported by leehuazhong on GitHub.

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

---------

Co-authored-by: Antigravity (Gemini) <noreply@google.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 18:28:52 +01:00
Huang Xin
182978aa0c
feat(web): name what web.readest.com does in its title and description (#8074)
Search results show web.readest.com as "Readest — Where You Read, Digest
and Get Insight", which doesn't say it is an ebook reader that runs in
the browser. The default title becomes "Readest Web — Free Online EPUB
Reader", with a description that names the formats, that it is free and
needs no install, and that it syncs with the apps.

The installed apps set their own window titles, and the reader replaces
this one with the book's title.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:15:26 +01:00
Huang Xin
a54ffd6f1c
feat(reader): select the Chinese word on a long-press on Android (#8018) (#8072)
Android's WebView ships ICU without its Chinese dictionary, so both
Intl.Segmenter and the native long-press split Chinese into single
characters: a long-press on 思 in 独立思考 selects 思, where iOS and desktop
select 思考.

In a Chinese book, where the platform splits Chinese by character, a word
selection now widens through jieba (already bundled for Word Lens and
RSVP):

- A long-press publishes the word right away, so the toolbar and instant
  actions use it. The page selection takes the word only at the native
  release. Set from script while the finger is down, it stops the press
  from dragging the selection on. The WebView drops its handles for a
  selection set from script, so the app's own handles take over and still
  adjust by character.
- A double-tap and an Instant Highlight hold select the word too.
- jieba keeps compounds whole (独立思考, 北京大学), so a longer word is split
  into the dictionary words that search mode finds in it, matching what iOS
  selects (思考, 大学). Names jieba's HMM finds stay whole (韩立).
- iOS, desktop and books in other languages are unchanged, and there jieba
  is never loaded for this.

jieba's first lookup builds its dictionary and blocks for about 0.5 s on
the emulator. During a double-tap that made the 250 ms single-click timer
read the double-tap as a tap, and the tap deselected the new word. The
timer now checks that no click came since its own, not how long ago the
last one was.

Tests that fail without the change (main's code put back under them):
- useTextSelector-chineseWord: "a long-press publishes the word...",
  "the release selects the word, on the app handles" and "a double-tap on
  one character selects its word" fail with expected '思' to be '思考'.
- useInstantAnnotation: "a hold on Chinese in a Chinese book on Android
  commits the word" fails with expected '思' to be '思考'.
- iframeEventHandlers: "a double-click whose handling holds the thread
  posts no single click" fails with iframe-single-click posted.
- jieba-word and sel-chinese-word fail with "is not a function" on main,
  since findZhWord and widenToChineseWord are new.

Checks on this commit rebased onto origin/main: pnpm lint, biome format,
and 76 related suites (selection, annotator, instant annotation, click
handling, jieba users), all passing.

Real use on Android emulators, Android 17 (WebView 145) and Android 15
(WebView 124), with a book in Chinese and the same text labelled English:
- long-press on 思 selects 思考 with the app handles and toolbar (both);
- long-press then drag extends natively, 思 → 思考 → 思考是 (both);
- dragging the end handle one character gives 思考是 (both);
- Instant Dictionary on 学 looks up 大学; Instant Highlight on 人 commits
  人民; a double-tap on 思 just after launch keeps 思考 (Android 17);
- single taps with double-tap on still dismiss the selection and toggle
  the bars (Android 17);
- in the English-labelled book a long-press still selects 思 alone, and
  jieba is never fetched (Android 17).

Not run: a physical phone, and e-ink or dark mode (no new UI; the handles
are the existing range editor). The full unit suite runs in CI.

Known limit, not changed here: a double-tap or Instant Highlight hold on
the left half of a Chinese character picks the character before it (立 for
思) on every platform, because a caret on a boundary belongs to the
character before it. With this change that character is widened to its
word (独立).

Reported by Zack9476 on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:37:07 +01:00
Huang Xin
8ded15a20f
feat(vocabulary): language tabs above the status filters (#8022) (#8071)
* feat(vocabulary): language tabs above the status filters (#8022)

Words in two or more languages now get a row of language tabs (All,
English, Chinese, ...) with each language's word count, between the
search bar and the Looked Up / Learning / Mastered chips. Picking a
language narrows the list, and the status chips count within it. The
tabs replace the Language dropdown chip; its "All Languages" string is
no longer used and is removed from the locales. One language shows no
tabs, as before.

Verified:
- VocabularyView.test.tsx "puts language tabs with word counts above the
  filters only when words span languages" and "drops the language filter
  when its last word is deleted" fail without the change with
  `Unable to find an accessible element with the role
  "group" and name "Language"`, and pass with it.
- vitest VocabularyView.test.tsx + filter.test.ts: 73 passed;
  vocabulary-dialog-layout.browser.test.tsx: 9 passed.
- pnpm lint and pnpm format:check pass.
- dev-web (Chromium) with 3 English and 3 Chinese words: phone 390px and
  desktop 1100px in light, dark and e-ink, plus the Chinese UI and
  Arabic (RTL). E-ink outlines the selected tab and keeps text opaque.
- Not run: the full unit suite (CI) and an Android/iOS device.

Reported by Zack9476 on GitHub.

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

* fix(vocabulary): move between language tabs with the arrow keys

DESIGN.md asks for arrow keys on radio-like tab strips. Left and Right
now move to the next or previous language tab and pick it, mirrored in
right-to-left layouts; the last and first tabs stay put. The handler runs
in the capture phase because Dialog stops keydown at its own node.

Verified:
- vocabulary-dialog-layout.browser.test.tsx "moves through the language
  tabs with the arrow keys" (LTR and RTL, inside the real Dialog) fails
  without the handler (focus stays on All) and passes with it; the file
  passes 11/11. VocabularyView.test.tsx + filter.test.ts: 73 passed.
- tsc, biome lint and biome format on the touched files pass.
- dev-web: Right/Left step All -> Chinese -> English -> Chinese on
  desktop; in Arabic (RTL) Left steps forward. The list follows.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:24:19 +01:00
Huang Xin
95ce9d927c
feat(store): localize the App Store and Google Play listings in 8 languages (#8054)
Every storefront showed the English listing, so searches in other languages
matched only the English name and subtitle. Each listing now has its own
title, subtitle or short description, keywords and description in Simplified
and Traditional Chinese, Japanese, German, French, Spanish (Spain and Latin
America) and Brazilian Portuguese.

- App Store (iOS and macOS): name, subtitle, keywords and description per
  locale. The macOS name and subtitle link to the iOS files, since App Store
  Connect keeps one name and subtitle per app. Support and marketing URLs
  link to en-US.
- Google Play: title per locale in metadata-play, with the descriptions in
  metadata/android, which F-Droid reads too.
- deliver's release notes use the "default" key, so every localization gets
  What's New (in English, from release-notes.json). Without it the new
  localizations would block the submission.

Screenshots stay English; the stores fall back to the default language.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:21:08 +01:00
Huang Xin
bef3debcd1
feat(xray): give X-Ray its own Maximum Output Tokens setting (#8020) (#8066)
X-Ray sent no max_tokens, so a server with a low default output cap
(2048 tokens on the reporter's llama.cpp) cut each batch's JSON reply
short, and every entity past the cut was lost. The Context Dictionary's
Maximum Output Tokens applied only to dictionary lookups.

X-Ray now has its own Maximum Output Tokens row under Manage
Dictionaries > X-Ray. It is separate from the dictionary's, because
one X-Ray reply covers a whole batch of text and needs many times the
tokens of a dictionary entry. Blank keeps the provider's default, as
before. The value persists and syncs with the other dictionary
settings. The row reuses the existing "Maximum Output Tokens" and
"Provider Default" strings, so nothing new needs translating.

Tests that fail without the change (run before the implementation):
- xray.test.ts "asks for the output limit set for X-Ray, and the
  provider default without one": expected [undefined, undefined] to
  deeply equal [undefined, 8192]
- CustomDictionaries.test.tsx "saves an X-Ray output limit of its own":
  no spinbutton named "X-Ray: Maximum Output Tokens"
- custom-dictionary-store.test.ts and settings.test.ts (sync): the
  value was dropped on load and not packed for sync
All pass with the change.

Checks run: related suites (xray, dictionaries, custom-dictionary-store,
sync settings adapter, CustomDictionaries, XRayView): 37 files, 471
tests passed. pnpm lint and pnpm format:check passed.

Real use on dev-web (Chromium, Alice in Wonderland EPUB), against a
stub OpenAI-compatible server that caps replies at 2048 tokens when the
request has no max_tokens, like the reporter's server:
- origin/main sources: request max_tokens null, reply cut at 2048
  tokens (finish_reason length), X-Ray kept 24 of 80 characters.
- this branch, 8192 typed into the new field: request max_tokens 8192,
  full reply (finish_reason stop), X-Ray kept all 80. The dictionary's
  field stayed blank. The value survived a reload.
- The settings row was checked in light, dark, e-ink, RTL and at
  390x844.
Not run: a real llama.cpp server (none installed here), and the on-device
Apple Intelligence path, which receives the same limit.

Reported by noideaforeal on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:28:32 +01:00
Huang Xin
a8952c59be
fix(annotator): keep the note editor open when the page re-anchors after a reflow (#8060) (#8064)
The reader dismisses any open popup on a relocate whose CFI changed, so
a page turn doesn't leave it floating over other text. A text selection
holds that off, but Annotate spends the selection when it opens the note
editor. In the "adds a note to the selected text" flake, every section
body changed height about a second after the chapter opened. The
paginator re-anchored to keep the same page (renderer reason 'anchor'),
and the visible range kept its start (…[chapter_460],/2) while its end
moved from /4/22/1:699 to /4/22/1:567. That relocate closed the editor
the test was typing into, and the typed note was dropped with it.

The relocate check now compares where the page starts (CFI.collapse), not
the whole range. A page turn or scroll changes the start, so it still
dismisses. The renderer's reason can't be used for this: 'anchor' also
covers real moves, such as focus moving to another page.

Verified:
- AnnotateNoteEditorFlow "keeps the editor open when the page re-anchors
  after a reflow (#8060)" fails without the change: Unable to find an
  element by: [data-testid="note-editor-popup"] after the re-anchor
  relocate. With the change it passes, and the page-turn relocate in the
  same test still closes the editor.
- On a production build (build-web + next start), the e2e test failed
  4/20 on main and passes 24/24 with the change. A probe that logs
  relocates and the editor's attach/detach passed 24/24. In 5 of those
  runs the re-anchor relocate arrived while the editor was open. The full
  web e2e suite passes 65/65.
- The 18 Annotator unit files (203 tests), pnpm lint and
  pnpm format:check pass.

Not run: Tauri desktop or mobile apps. Checked on web only.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:43:23 +08:00
Huang Xin
532d92179a
feat(reader): hide the unavailable Translate button and keep the instant tools together (#8044) (#8057)
The header kept a greyed-out Translate button for books it can't translate:
PDFs, books with no language, and books already in the target language. On a
tablet that crowds the bar for nothing. TranslationToggler now renders nothing
then, as DuoBookModeToggler does outside its pose. It stays while translation
is on, so it can still be turned off.

Translate and Instant Draw also trade places. Instant Draw is now last in the
left group, beside the Quick Action button, and Translate sits beside Notebook
on the right.

Tests that fail without the change:
- TranslationToggler.test.tsx, the three "leaves the header for ..." cases:
  "expected <button …(3)>…(1)</button> to be null" on main.
- HeaderBar.test.tsx, "puts Instant Draw next to the Quick Action button and
  Translate next to Notebook": "expected [ 'translation-toggler', …(1) ] to
  deeply equal [ 'Instant Draw', …(1) ]" on main.

Checks run:
- pnpm test --run on the HeaderBar, TranslationToggler,
  header-bar-page-turns, LangPanel and HandwritingBars tests: 5 files,
  39 tests passed.
- pnpm lint (tsc + Biome) passed. Its one warning and one info are in files
  this change doesn't touch. pnpm format:check: no changes.
- dev-web with Playwright, an English EPUB (Alice) and a Japanese one, main
  and branch on the same server: Galaxy Tab S4 portrait and landscape, Pixel 7,
  and desktop 1280 in light, dark, e-ink and an Arabic UI. In every case only
  these two buttons moved, and Translate was gone for the English book only.
  The reader header stays left-to-right under an Arabic UI on main too.
- Linux CEF dev app, window at 834x1194 and 1280x800, same two books, main
  and branch: same result.

Not run: a native Android or iOS tablet build. The change is React only, and
the tablet layout was checked on dev-web with an Android tablet user agent.

Reported by noideaforeal on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:40:52 +01:00
Huang Xin
024acbdb8c
fix(reader): keep one Back entry for a slider move made while the last jump loads (#8056) (#8063)
Slider moves, search results and annotation steps share one history entry,
so Back returns to where the run began (#7999). A step continued the run
only if the reader was still where the last step had landed, which is
known only once that step has finished loading. A step made earlier, such
as a slider drag that pauses twice within a chapter load, started a new
run and pushed its own entry. Back then stopped at the earlier slider
position. That is the "returns to the reading position after a
page-number or slider jump" flake: Expected 1, Received 56.

A step made while the run's last step still loads now continues the run.
It still cuts the earlier jump short, as the paginator lets a later jump
win, and it replaces the run's entry only after the earlier step has
pushed it. The run's starting chapter, used by the return control's
label, is now recorded when the run starts. A cut-short step never
moves the page, so its end could not record it.

The e2e test's waits read the footer's page label, which previews the
slider before the jump runs. Go Back could therefore be clicked before the
70% jump had even started. The test now waits for the reader to land
there (ReaderPage.locationFraction).

Verified:
- wrapped-foliate-view.test.ts "keeps one entry for a step made before
  the last one landed" fails without the change, in both orders:
  expected [ 'A', 'B-1', 'C-1' ] / [ 'A', 'C-1', 'B-1' ] to deeply equal
  [ 'A', 'C-1' ]. With only the run-start recording put back, the
  "cut-short step ends first" case fails with expected
  { from: undefined, to: 'C' } to deeply equal { from: 'A', to: 'C' }.
  Without the wait for the earlier step, the "later step lands first"
  case fails with expected [ 'C-1', 'B-1' ] to deeply equal [ 'A', 'C-1' ].
- On a production build (build-web + next start), the original e2e test
  failed 8/20 on main, all with Received 56. The updated test passes
  20/20 with the fix, and reading.spec.ts passes 2x.
- A probe that moves the slider to 70% as soon as the 50% jump starts,
  under 4x CDP CPU throttling so the first jump is still loading: main
  8/8 Back lands on page 56, with the fix 8/8 back on page 1.
- The 12 unit files that drive step navigation or the return control,
  pnpm lint and pnpm format:check pass.

Not run: Tauri desktop or mobile apps. The change is in the shared
foliate view wrapper and was checked on web only.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:34:58 +08:00
Huang Xin
f6e8c52ed5
test(e2e): leave the shown sidebar tab alone when opening it (#8055) (#8062)
"closes the QR code sheet on a phone-sized screen" timed out waiting for
the fourth TOC entry. The book opens at desktop width, where the sidebar
is pinned and open. After the test shrinks the window to 412x839 the
sidebar stays open, so openTocChapter skipped the toggle and clicked the
TOC tab, which was already shown. On a phone, tapping the tab that is
already shown closes the sidebar (Content.tsx handleTabChange), so the
TOC entries never appeared. It failed only when the sidebar had
re-rendered at phone width before the click; until then the click
handler still saw the desktop width and did nothing.

openTocChapter and openAnnotationsTab now click a sidebar tab only when
its aria-pressed is not true.

Verified on a production build (build-web + next start):
- A probe copy of the test with a 1 s wait after the resize failed 3/3
  on main with the CI error (waiting for
  locator('.toc-list [role="treeitem"]').nth(3)) and passes 5/5 with
  this change. The test itself passes 5/5.
- The full web e2e suite: 63 passed, 2 failed. Neither failure runs at
  phone width. "adds a note to the selected text" also fails on main
  (4/20 there, 2/20 with this change) and is filed as #8060. "draws the
  range-edit handles above the selection toolbar" failed once and then
  passed 6/6 with this change and 6/6 on main.
- pnpm lint and pnpm format:check pass. tsc -p e2e/tsconfig.json
  reports the same "page is protected" errors as on main and none in
  ReaderPage.ts; CI does not run it.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:22:46 +08:00
Huang Xin
3cfa120d4c
fix(tts): start system-voice paragraphs without the extra pause and ring (#8037) (#8061)
With a system voice, Read Aloud paused at paragraph starts about twice
as long as with other engines, and the buffering ring flashed at some of
them. The controller waited out the 300 ms paragraph gap, and then the
engine still took its usual 0.2-0.6 s to start the next utterance. Edge
plays the gap as silence while the next paragraph is being prepared, so
its pause is just the gap. The ring showed whenever the player's 400 ms
poll landed in a paragraph's ordinary startup; sentence starts inside a
paragraph are just as slow but never mark the wait.

Engines without gap control (system voices) no longer wait out the
paragraph gap. The ring shows only after a second with no audio, for
every engine.

The two native stop calls at each paragraph start, suspected in the
report, take about 3-5 ms together on the emulator and are unchanged.

Verified: tts-controller.test.ts "a system voice starts the next
paragraph without sleeping the gap first" fails on main (forward not
called) and tts-controller-timeline.test.ts "isBuffering covers a wait
of over a second..." fails on main (ring shown at 999 ms); both pass
with the change. The 18 related unit suites (479 tests), the
tts-auto-advance browser test, pnpm lint and pnpm format:check pass.
On an Android 17 emulator with Google TTS, debug builds of main and this
change, 3 minutes of continuous reading each: paragraph-start silence
went from a median of 679 ms (max 814) to 370 ms (max 483), sentence
silence stayed at about 240 ms, and the ring showed at 7 of 10
paragraph starts on main and none with the change. An Edge voice behind
a 1.5 s network delay still showed the ring about 1.1 s into the
paragraph. Not run on a real phone, iOS, Linux speech-dispatcher or Web
Speech, which also lose the paragraph wait.

Reported by chuttenh on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:21:30 +08:00
Huang Xin
e96e31eafe
fix(vocabulary): put the card dictionary's entry on Export to Anki cards (#8059)
Without AnkiDroid (macOS, Windows, Linux, iOS, web) "Dictionary for
Anki Cards..." wasn't in the menu, and Export to Anki wrote each card's
back as the hint plus the book line. Most looked-up words have no hint,
so their cards showed only the book title and author.

- The menu item now shows everywhere. Without AnkiDroid, its panel says
  Export to Anki uses the dictionary, since there is no Sync to describe.
- Export to Anki looks up every exported word in the chosen dictionary
  and adds the entry under the book line, in the same block Sync's note
  type uses. A toast shows progress. With no dictionary chosen, the file
  is the same as before.
- When the file is imported into the Readest Vocabulary deck and Sync
  on Android reads it back, the entry is not taken as the word's hint.

Card profiles still need Sync (they read note types from AnkiDroid). The
front still shows the word and its sentence, as on Sync's cards.

Verification:
- Fails without the change:
  - export.test.ts "puts a word's dictionary entry under the book line":
    the back has no entry block.
  - anki.test.ts "never takes the dictionary entry of a file-exported
    Readest note as the hint": expected 'spice n.' to be undefined.
  - VocabularyView.test.tsx "puts the chosen dictionary's entry on every
    card of the file export without AnkiDroid": no "Dictionary for Anki
    Cards" menu item.
  All pass with the change.
- pnpm test (1443 files, 17846 tests), pnpm lint, pnpm format:check
  pass. No src-tauri changes.
- dev-web (self-hosted, Chromium, Playwright): looked up "Alice" in the
  Alice EPUB, then Export to Anki. The back had only the book line.
  Chose Wiktionary under Export > Dictionary for Anki Cards... and
  exported again. The back had the book line and then Wiktionary's
  entry (Proper noun, 6 senses). The progress toast showed.
- Not run: the macOS app (the macOS-only step is the save dialog, which
  is unchanged), the iOS app, and importing the file into Anki desktop
  (Anki isn't installed here).

Reported by felisinnn on Discord.

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 19:10:41 +08:00
Huang Xin
65afb78058
fix(opds): load covers from catalogs that block hotlinking (#8058)
The Wenku8 catalog at opds.wol.moe showed no covers in the app, while
other OPDS readers showed them. Its covers sit behind Cloudflare hotlink
protection, which answers 403 to a Referer from another site. On Android
and Windows the webview runs at http://tauri.localhost and sends that
origin as the Referer of every <img>; native readers send none. OPDS
covers are now requested with referrerPolicy no-referrer. The web app
was not affected: it loads covers through its proxy, which sends no
Referer.

  curl cover/934.jpg                              200
  ... -H 'Referer: http://tauri.localhost/'       403
  ... -H 'Referer: http://localhost:3000/'        403
  ... -H 'Referer: https://opds.wol.moe/'         200

Verification:
- New test in cached-image.test.tsx (both the fill and sized renders)
  fails without the change: "expected null to be 'no-referrer'".
- Xiaomi 13, Android release build: on 0.12.20 the lastUpdate feed showed
  9 of 9 covers broken; in the same webview the cover failed with the
  default Referer and loaded (210x301) with no-referrer. On this branch
  the feed shows 9 of 9 covers and the publication page shows its cover.
- pnpm test: 1443 files, 17845 tests passed. pnpm test:browser: 184
  files, 1414 tests passed. pnpm lint: tsc clean; Biome reports only the
  one warning and one info already on main.
- Not checked: macOS/iOS (tauri:// origin), Windows, Linux.

Reported by 德丽莎 on Discord.

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 19:09:57 +08:00
Huang Xin
f9173e8f4b
fix(xray): wrap the Notebook's X-Ray section filters instead of scrolling them (#8053)
The section filters above the X-Ray list scrolled sideways in one line.
At the Notebook's default width only the first three fit and the fourth
was cut at the edge, with no scrollbar or other sign of the rest until the
row was scrolled, so Events, Concepts and Timeline were easy to miss. Let
the row wrap, as the tag rows in Book Details and Sync Info do, so every
section is on screen. Wrapping needs no fade (e-ink has no gradients) and
no hover (touch and e-ink have none).

Verified: the new XRayView.browser.test.tsx case renders all eight
sections in a 280px Notebook and fails on main ("Organizations 1:
expected 287 to be less than or equal to 268") and passes with the fix;
XRayView.test.tsx and pnpm lint pass. On dev-web, with an X-Ray of every
section built through a local stub model: on main the 350px Notebook
showed 3 of 8 filters (row content 661px in a 326px row); with the fix
all 8 show on 3 lines at 1400x900 and 1340x800 and on 2 lines at 390x844,
in light, dark, e-ink and RTL. Not run on Windows; checked in Chromium,
which WebView2 uses.

Reported by notbenites on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:09:06 +08:00
Huang Xin
87abc5630c
fix(ios): show the Copy menu on selected app text like the Notebook's dictionary (#8050)
* fix(ios): show the Copy menu on selected app text like the Notebook's dictionary

On iOS the system edit menu (Copy, Look Up, Translate) was hidden for
every non-editable selection, so text the app shows beside the book could
be selected but not copied: a definition in the Notebook's Dictionary tab,
the dictionary sheet, the translator, X-Ray, notes, AI answers and book
details. It was meant only to keep that menu off Readest's own toolbar.

- ContextMenuSuppressor follows the `menu` flag of set_selection_suppressed,
  which was a no-op on iOS. It starts on, so a late update can only hide
  the menu on app text, never flash it over the annotation toolbar.
- useSystemSelectionMenu, mounted in Providers, lifts it while the app
  document holds a selection outside the footnote popup and paragraph mode,
  which show Readest's toolbar.
- Book frames (useTextSelector) and footnote popup frames set it again on
  their own selections. Selecting in one document leaves the other's
  selection in place and fires no event there, so the latest selection
  decides.

Fails without it:
- useSystemSelectionMenu.test.ts, with the listener removed:
  expected undefined to deeply equal { target: 'menu', suppressed: false }
- useTextSelector-iosSystemMenu.test.ts and the new FootnotePopup.test.tsx
  case, before their calls were added: expected { target: 'menu',
  suppressed: false } to deeply equal { target: 'menu', suppressed: true }
All pass with the change.

Checks: pnpm test (1443 files, 17822 tests passed), pnpm lint (one
warning and one info in files this does not touch), pnpm format:check,
pnpm fmt:check, pnpm clippy:check, pnpm test:rust (217 passed).

Real use, iOS 27.0 simulator (iPhone 17 Pro), release build of this branch
against a 0.12.26-era build:
- before: Notebook's Dictionary text selected with handles, no menu; the
  same in the phone's dictionary sheet
- after: Copy / Look Up / Translate shows on Notebook text, in landscape
  and in the full-screen portrait Notebook; Copy put the text on the
  pasteboard
- after: book text, book text selected while a Notebook selection was
  still live, paragraph mode, and a footnote popup after app text had
  lifted the menu all show Readest's toolbar and no system menu
Not run on iOS 16, the reporter's version.

Fixes #8045. Reported by noideaforeal on GitHub.

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

* fix(ios): let the reader's own selection echoes leave the system menu alone

The reader re-adds a book range itself: after a lookup closes
(restoreSelectionRange), and to drop the native grabbers under a popup
(suppressNativeSelectionHandles). The selectionchange those writes echo
took the system menu back off, so app text the user selected meanwhile
lost its Copy menu. The iOS check now sits after the programmatic-echo
return; WebKit doesn't bring its menu up for a programmatic selection, and
real book selections still turn it off.

Fails without it: useTextSelector-iosSystemMenu.test.ts "an echo of the
reader's own selection write leaves the menu alone": expected "vi.fn()" to
not be called at all, but actually been called 1 times. Passes with it, and
the 52 reader hook test files (449 tests) pass.

Raised by CodeRabbit on #8050.

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

---------

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 17:35:04 +08:00
Huang Xin
f1d4068ffa
fix(tts): keep English text with a stray CJK character on the English voice (#8048)
* fix(tts): keep English text with a stray CJK character on the English voice

Read Aloud switched an English paragraph to a Chinese voice when it held a
single Han character. An English novel that types 一 (U+4E00) for a dash had
33 of its paragraphs read by zh-CN-YunxiNeural, plain sentences included.
inferLangFromScript returned zh for any Han character in `en` or untagged
text, and parseSSMLLang applied that to the whole paragraph.

It now switches to he, ko, ja or zh only when that script carries most of
the words: a run of Latin or Hebrew letters is one word, and so is each CJK
character. Counting letters instead would flip a Chinese sentence with
English terms ("这是一个关于 TypeScript 和 React 的教程") to English.
parseSSMLLang strips the SSML tags before inferring, since the tags' own
words (speak, xmlns, mark) would otherwise outvote a short CJK heading.

An English sentence that quotes a short phrase ("she said, “你好.”") is now
read by the English voice; before, the whole sentence went to the Chinese
one.

franc was measured as the alternative and rejected: on the reported book it
named another language for 19% of sentences and 7% of paragraphs, at about
84 µs a sentence against 0.4 µs.

Verified:
- New tests in lang.test.ts and ssml.test.ts fail without the change
  (expected 'zh' to be 'en'; expected 'he' to be 'en'; expected
  ['zh','zh','zh'] to deeply equal ['en','en','en']) and pass with it.
  Without the tag stripping, three existing parseSSMLLang tests fail.
- The reported book: 0 of 1,873 paragraphs and 0 of 8,273 sentences are
  inferred as anything but en (33 paragraphs before).
- dev-web with Edge TTS: the paragraph sent as `zh | zh-CN-YunxiNeural` on
  main is sent as `en | en-US-BrianNeural`, and so is "He's a good man一 er,
  dwarf."
- pnpm test, pnpm lint, pnpm format:check.

Not run: the Windows app, where it was reported. The reporter also heard a
Finnish voice, which this neither explains nor changes.

Reported by email.

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

* fix(tts): infer one language per sentence, not per tag fragment

Two gaps CodeRabbit found in the previous commit:

- parseSSMLMarks inferred a language for each text fragment between tags,
  so a fragment holding only a stray ideograph still took a Chinese voice.
  #preprocessSSML replaces only the first <break/>, so a line that is just
  一 between two <br>s reached it that way. The language now comes from all
  of a sentence's text within one language scope; an explicit <lang> scope
  keeps its own.
- parseSSMLLang replaced tags with a space, which split a word cut by an
  inline tag: "你好 i<emphasis>Phone</emphasis>" counted two English words
  and came out en. Tags are now removed without a space, the way the marks
  parser joins fragments.

Verified:
- New tests in ssml.test.ts fail without the change (expected
  [ 'en', 'zh', 'en' ] to deeply equal [ 'en', 'en', 'en' ]; expected 'en'
  to be 'zh') and pass with it. A third pins an explicit <lang> fragment
  inside an English sentence to its own language; it passes before and
  after.
- dev-web with Edge TTS on the reported book: 11 requests, all
  `en | en-US-BrianNeural`, including two sentences ending in 一.
- pnpm test (SSML and language suites; the full suite runs at push),
  pnpm lint, pnpm format:check.

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

* refactor(tts): collect the SSML text between tags instead of replacing them

CodeQL read `.replace(/<[^>]*>/g, '')` in parseSSMLLang as an incomplete
HTML sanitizer (js/incomplete-multi-character-sanitization). The text is
never rendered: it only feeds inferLangFromScript's character count. Split
on the tags and join the pieces instead, which says what it does and gives
the same string.

No behavior change. Checked with the tests that pin this path: the short
CJK heading inside its SSML tags stays zh, and "你好 i<emphasis>Phone</emphasis>"
stays zh (ssml.test.ts, lang.test.ts, ssml-extra.test.ts: 133 passed), plus
pnpm lint.

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

* fix(tts): infer a sentence's language from its untrimmed text

CodeRabbit found that 53d3e1f18 joined the sentence's fragments after
cleanTextContent had trimmed each one's leading space, which runs the words
on either side of a tag together: "One<break/> two<break/> three 一二." was
counted as "Onetwothree 一二." (one English word against two Han characters),
so every fragment took the Chinese voice while the paragraph stayed English.
The inference now reads each fragment's untrimmed text. Tags still add no
space, so "i<emphasis>Phone</emphasis>" stays one word.

Verified: the new test `should keep the words apart that a tag and a space
separate` fails without the change (expected [ 'zh', 'zh', 'zh' ] to deeply
equal [ 'en', 'en', 'en' ]) and passes with it. The iPhone test now also
checks the marks (['zh', 'zh']); it passes before and after. SSML and
language suites (163 passed) and pnpm lint; the full suite runs at push.

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

* fix(tts): count the space between two tags when inferring a sentence's language

CodeRabbit found that 0cadb9c4b still dropped text that isn't a fragment
of its own: in "One<break/> <break/>two 一二." the lone space between the
two tags never reached the inference text, so "One" and "two" ran together
and both fragments took the Chinese voice while the paragraph stayed
English. That text is now appended to the previous fragment's inference
text. It holds no letters (only whitespace, punctuation or symbols reach
that branch), so it only separates words.

Verified: the new test `should keep the words apart that a space alone
between two tags separates` fails without the change (expected
[ 'zh', 'zh' ] to deeply equal [ 'en', 'en' ]) and passes with it. SSML
and language suites (164 passed) and pnpm lint; the full suite runs at
push.

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

* fix(tts): group a sentence's text by language scope, not by language

CodeRabbit found two cases where db62f06c6 put text in the wrong group:

- Fragments were grouped by their language string, so an explicit
  <lang xml:lang="en">Hello </lang> was merged with the paragraph's own
  `en` text beside it; with 你好 next to it the group came out zh and
  "Hello" took the Chinese voice (on main it stayed en).
- A space that isn't a fragment of its own was appended to the previous
  fragment, even when that fragment's <lang> scope had ended, so in
  "One<lang xml:lang="fr"> (bonjour)</lang> two 一二." the space went to
  the French group and "One" ran into "two".

The parser now builds each sentence's text per scope as it reads: the
paragraph's own language is one scope and every <lang> block is another.
All text goes to the scope it sits in, spaces included, and each fragment
takes the language inferred from its scope's text.

Verified: the new tests `should infer an explicit language scope apart
from the text around it` and `should count a space after a language scope
with the text it separates` fail without the change (expected
[ 'zh', 'zh', 'en' ] to deeply equal [ 'en', 'zh', 'en' ]; expected
[ 'zh', 'fr', 'zh' ] to deeply equal [ 'en', 'fr', 'en' ]) and pass with
it, along with every earlier SSML test (166 passed). pnpm lint; the full
suite runs at push.

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

* fix(tts): read XML escapes as symbols when inferring a sentence's language

CodeRabbit found that the counted text still held XML escapes. foliate
serializes SSML with XMLSerializer, which writes &, < and > in text as
&amp;, &lt; and &gt;, so each one counted as an English word (`amp`,
`lt`, `gt`) and could tip a CJK sentence near a tie to English:
"&lt;中文&gt;" came out en. Both places that gather text for the count
now read those three escapes as the symbols they stand for.

Verified: the new test `should not count an escaped symbol as an English
word` fails without the change (expected 'en' to be 'zh') and passes with
it. Checked in Chrome that XMLSerializer escapes only &, < and > in text
(quotes stay raw) and writes > in an attribute value as &gt;. SSML and
language suites (167 passed) and pnpm lint; the full suite runs at push.

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

---------

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 10:29:10 +01:00
Huang Xin
105997a085
fix(xray): keep the Notebook's tab bar on screen before the first X-Ray (#8051)
Before an X-Ray is built, XRayView put XRayStatus straight into the
Notebook's flex column. XRayStatus is min-h-full (to centre in the
dictionary popup's scroller), so it took the whole Notebook's height and
the header and tab bar were added on top: the tab bar went off screen and
scrolling to it scrolled the page. Give it the same min-h-0 flex-1
scroller the popup does.

Verified: XRayView.browser.test.tsx fails on main ("expected 704 to be
less than or equal to 600", the tab bar's bottom in a 600px column) and
passes with the fix; XRayView and NotebookTabNavigation unit tests and
pnpm lint pass. On dev-web with no X-Ray built, the tab bar ends at the
window bottom at 1400x900, 1340x800, 800x1280 and 390x844, in light, dark
and e-ink, and a wheel over the panel scrolls nothing (main: tab bar at
944-997 in a 900px window; at 1340x800 the page scrolled 97px and the
header left the screen). Not run on Windows or an Android tablet; checked
in Chromium, which their webviews use.

Reported by notbenites on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:25:54 +08:00
Huang Xin
a84143aeca
fix(android): open the chosen file when "Open with" finds a book open (#8019) (#8049)
Some checks are pending
CodeQL Advanced / CodeQL gate (push) Waiting to run
CodeQL Advanced / Analyze (actions) (push) Blocked by required conditions
CodeQL Advanced / Analyze (javascript-typescript) (push) Blocked by required conditions
CodeQL Advanced / Analyze (python) (push) Blocked by required conditions
CodeQL Advanced / Analyze (rust) (push) Blocked by required conditions
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 / CI gate (push) Waiting to run
PR checks / nix_flake_check (push) Blocked by required conditions
PR checks / rust_lint (push) Blocked by required conditions
PR checks / koplugin_rust_lint (push) Blocked by required conditions
PR checks / build_web_app (push) Blocked by required conditions
PR checks / test_web_app (1) (push) Blocked by required conditions
PR checks / test_web_app (2) (push) Blocked by required conditions
PR checks / test_web_browser (push) Blocked by required conditions
PR checks / test_extensions (push) Blocked by required conditions
PR checks / build_tauri_app (push) Blocked by required conditions
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
With Auto Import on File Open off, Android "Open with Readest" opens the
file without importing it. If a book was open, the app kept that book:
- left on the reader, the file was dropped ("reader already active");
- on a cold start, "Open Last Book" mounted the reader while the file
  loaded, and the router.push that followed changed only the URL, since
  a mounted reader doesn't re-init.

Check for a mounted reader once the file is ready, and switch its book in
place through 'open-book-in-reader', as widget and annotation links do.

That switch pushed the new reader URL, so Back closed the book and landed
on the old book's URL: a reader with no book and a spinner, until a second
Back. Widget links had the same bug. The switch now replaces the URL;
opening a book beside another and closing one of two still push.

Tests that fail without the change:
- useOpenWithBooks.test.tsx "switches an open reader to the chosen file"
  and "switches a reader that mounted while the file was loading":
  expected "vi.fn()" to be called with [ { bookHash: 'pdfHash' } ],
  Number of calls: 0.
- useBooksManager.test.tsx "replaces the reader URL when a link switches
  the open book": expected navigateToReader called with
  objectContaining({ replace: true }).
- nav.test.ts "replaces the current entry when asked": expected push not
  to be called, called 1 time.

Ran on this commit rebased onto main: vitest useOpenWithBooks,
useBooksManager, nav, open-with, useOpenLaunchLinks,
useOpenLaunchLinksColdStart (6 files, 123 passed); tsc --noEmit; biome
check on the changed files; pnpm format:check.

On an Android 17 emulator (WebView 145), debug x86_64 builds of main and
this branch, Files app > Downloads > PDF > Open with > Readest:
- Auto Import off, book left open: main keeps the old book and logs
  "Ignoring Open-with VIEW intent"; branch opens the PDF, Back reaches the
  library, the old book keeps its position, the PDF isn't on the shelf.
- Auto Import off, cold start with Open Last Book: main shows the last
  book under the PDF's URL; branch switches to the PDF, Back reaches the
  library.
- readest://book/<hash> link while reading: Back reached a stuck spinner
  before, the library now.
- Auto Import on, warm and cold with Open Last Book: the PDF is imported
  and opens on main and branch; Back reaches the library.
Not run on a Samsung device or Android 16.

Reported by schoefaz on GitHub. ChuwuYo proposed the same
useOpenWithBooks change in #8041.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 09:59:27 +01:00
Kel
9118387ec6
feat(tts): highlight the sentence or paragraph being read from the player and media notification (#8005)
* feat(tts): highlight the current passage from playback controls

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>

* Keep the Read Aloud highlight action tied to the live passage

Co-Authored-By: Codex (GPT-6) <noreply@openai.com>

* feat(tts): bind the highlight button to the sentence or paragraph (owner: "Can select sentence or paragraph")

The Read Aloud player's Highlight tile and the Android media notification's
Highlight action now press one bindable key, "Highlight Button". By default
it runs Highlight Current Sentence (Shift+M). In Settings > Keyboard
Shortcuts it can be recorded onto the new Highlight Current Paragraph, or any
other action: press "Set key", then the notification button.

- Highlight Current Paragraph (no default key) saves the block the spoken
  sentence starts in, the same block paragraph navigation steps by. A PDF
  text layer has no paragraphs, so there it saves the sentence.
- Only TTS and EPUB 3 Media Overlays know the sentence being read. A paired
  audiobook knows only the chapter, so the tile and the notification action
  are not offered for it and both highlight actions do nothing.
- While the next section opens, the last spoken range still belongs to the
  outgoing section, so nothing is saved until the new one is read. Shift+M
  could save the outgoing text under the new section before.
- The word-level path is dropped: in word mode the button still saves the
  sentence or paragraph.
- The tile joins the Speed / Voice / Sleep Timer row instead of a full-width
  button, and the notification uses the same highlighter icon.

Fails without it: with the PR's code at d4c942b48, 9 of the new or changed
unit tests fail, among them
- useShortcuts "runs the action the highlight button is bound to":
  expected "vi.fn()" to be called once, but got 0 times
- tts-controller "returns null for a paired audiobook":
  expected { cfi: 'cfi-chapter', ... } to be null
- tts-controller "does not save the outgoing text under the next section
  while it opens": expected { cfi: 'cfi-string', ... } to be null
- tts-media-bridge "the native highlight action presses the highlight
  button for its book": expected "vi.fn()" to be called once, but got 0 times
and the browser test tts-auto-advance "Read Aloud resumes on that sentence
and highlights it or its paragraph without pausing" fails with expected
"vi.fn()" to be called 2 times, but got 0 times. All pass with the change.

Checks, on the change merged onto origin/main 59de975f6:
- pnpm test on the 81 files that import the changed modules: 1397 passed,
  30 skipped
- pnpm test:browser on the 4 related files: 62 passed
- pnpm lint, pnpm format:check: pass (one warning and one info, both in
  files this change does not touch)
- pnpm fmt:check, pnpm clippy:check, pnpm test:rust (217 passed) and Gradle
  :tauri-plugin-native-tts:testDebugUnitTest (31 passed), run before the
  merge; main has not changed src-tauri since

Real use:
- dev-web (Chromium) with a hand-built EPUB 3 Media Overlay book: the tile
  saved the sentence being read; with the button bound to Highlight Current
  Paragraph it saved the whole paragraph; Shift+M still saved the sentence.
  The player sheet was checked in light, dark, e-ink, Arabic (RTL) and at
  360 px wide (four 76 px tiles).
- Android 15 emulator (API 35, debug APK): the notification's Highlight
  button saved the sentence being read. Recording it onto Highlight Current
  Paragraph asked to replace the sentence binding, and the next tap saved
  the whole paragraph.
- Android 10 emulator (API 29): the notification's Highlight action saved
  the sentence being read.

Not run: a WearOS watch (the reporter's device) and a physical Android
phone. iOS and desktop have no notification button, so there the tile runs
whatever the button is bound to and cannot be recorded onto another action.

Reported by jeffrto on GitHub.

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

* fix(tts): note the section a re-attached Read Aloud reads

attachView installs the text of the section it captured before its awaits
but left #ttsTextSectionIndex as it was. When headless playback opened the
next section during that prep, the highlight guard passed and the sentence
of the earlier section could be saved under the next section's CFI. The
swap now records the section with the text, as #initTTSForSection does.

Found in review by CodeRabbit.

Fails without it: tts-controller-detach "a section change during attach prep
leaves no sentence to highlight" with expected { cfi: 'epubcfi(/6/2!/4/2)',
... } to be null. Passes with it.

Checks: pnpm test on tts-controller-detach, tts-controller, useTTSControl
and tts-media-bridge (281 passed); pnpm test:browser on
tts-auto-advance (9 passed); pnpm lint and pnpm format:check pass.

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

---------

Co-authored-by: Kel <1563599+kelvinalfaro@users.noreply.github.com>
Co-authored-by: Codex (GPT-6) <noreply@openai.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 08:44:13 +01:00
Huang Xin
e9ca76a11b
fix(auth): send the reader's agent to Supabase in a form that isn't a browser's (#8046)
* fix(auth): send the reader's agent to Supabase in a form that isn't a browser's

The auth-proxy Worker sends password and refresh-token grants with its
secret key, so Supabase honours Sb-Forwarded-For. #7945 made it forward
the reader's User-Agent too, so each session names its device in Manage
Sync. Supabase refuses a secret key on any request whose agent looks like
a browser. Once that Worker was deployed, every web and app password
sign-in through auth-cf.readest.com failed with 401 "Forbidden use of
secret API key in browser", and so did every refresh. It was rolled back
to the version before #7945.

The Worker now sends `ReadestAuthProxy/1 <base64 of the reader's agent>`,
and describeUserAgent decodes that before naming the device. Until this
is deployed, sessions refreshed through the proxy are stored with no
agent and show as "Unknown device", one per session.

Verified:
- auth-proxy.test.ts "passes on the reader's user agent in a form that
  isn't a browser's" (password and refresh_token grants) failed before
  with "expected 'Mozilla/5.0 (Macintosh; Intel Mac OS …' not to match
  /Mozilla|AppleWebKit|Chrome|Safari/". It now also checks that
  describeUserAgent reads the forwarded agent as Chrome on macOS.
- Against production Supabase, through `wrangler dev --remote` (a
  preview, not the live route), with a made-up account and a Chrome
  agent:
  - main's Worker: 401 "Forbidden use of secret API key in browser",
    the outage.
  - this branch: 400 invalid_credentials, the normal answer.
- pnpm test: 1440 files, 17801 tests passed. pnpm lint: clean apart from
  existing warnings in nativePageTurn.ts and
  paginator-goto-preloading.browser.test.ts.

Not run: a real sign-in, and a session's stored agent read back after
one. Both need a real account's password through the live Worker.

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

* fix(auth): encode the forwarded agent as UTF-8 before base64

Answers CodeRabbit's review of #8046.

Workers hands header values over as UTF-8 text, not Latin-1, so an agent
whose device model is outside Latin-1 made btoa throw. The Worker then
answered 502 without calling Supabase, so that reader couldn't sign in or
refresh. The Worker now base64-encodes the agent's UTF-8 bytes, and
describeUserAgent decodes them as UTF-8.

Verified:
- auth-proxy.test.ts "passes on an agent whose device model is in any
  script" (both grants) failed before with "expected 502 to be 200". It
  now also checks that describeUserAgent reads it back as Readest on
  阅读器. Node's Headers can't hold such a value, so the test stubs the
  Worker's view of the request.
- Against production Supabase through `wrangler dev --remote`, with a
  made-up account:
  - before the fix: a Chrome agent got 400 invalid_credentials, and an
    Android agent with model 阅读器 got 502.
  - after the fix: both got 400 invalid_credentials.
- Worker and parser suites: 52 tests passed. pnpm lint: unchanged.

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

---------

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 07:29:16 +01:00
Huang Xin
d362deb6b2
fix(sync): name the KOReader plugin's sessions KOReader in the device list (#8042)
The Readest KOReader plugin signs in and refreshes through KOReader's Spore
client, so Supabase stores its sessions with the agent `lua-Spore`.
describeUserAgent only knew `KOReader/<version> (<device>; ...)`, so each
plugin session was its own "Unknown device": in Manage Sync, on the sign-in
screen a Free account sees at the device limit, and in the count against
that limit. One Kindle that signed in twice took two of three slots.

`lua-Spore` now reads as KOReader with no device name. The plugin's
sessions group into one device, and the list names it "KOReader" (a
product name, not translated) instead of "Unknown device".

Verified:
- New tests failed before the change and pass with it:
  - syncDevices.test.ts "names the KOReader plugin's Spore agent KOReader":
    expected null to deeply equal { client: 'KOReader', os: null }.
  - syncDevices.test.ts "lists the KOReader plugin once": expected [ …(2) ]
    to have a length of 1 but got 2.
  - SyncDeviceList.test.tsx: unable to find an element with the text:
    KOReader.
- pnpm test: 1441 files, 17802 tests passed. pnpm lint: clean apart from
  an existing warning in paginator-goto-preloading.browser.test.ts.

Not run: the Devices list in a browser. /api/auth/sessions reads the
account's sessions with the server key, which wasn't available to use here,
and no local Supabase with migration 035 was set up. After the web deploy,
Manage Sync on an account signed in to the plugin should show "KOReader"
where it showed "Unknown device".

Co-authored-by: Claude Code (Claude Opus 5.5) <noreply@anthropic.com>
2026-11-28 07:28:42 +01:00