feat(tts): Readest Voice, premium read-aloud voices for Plus and Pro (#6720)

* feat(tts): add Readest Voice plan gating and daily quota constants

Plus and Pro only: unlike other premium features, purchase is excluded
because synthesis has a recurring per-character GPU cost.

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

* feat(tts): add Readest Voice catalog and RunPod stream helpers

The route reads the worker-exported catalog from READEST_TTS_CATALOG_URL
(10 minute cache, last good copy on refresh failure) and derives the plan
per engine, failing closed for unknown engines. The RunPod helper starts a
window job, reads it back from /stream, and cancels or warms up best
effort.

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

* feat(tts): per-user in-flight window slots for Readest Voice

Migration 026 adds tts_inflight with acquire/set-job/release RPCs: a new
listen window supersedes the old one (returning its job to cancel), a
second download window is refused, and every slot expires with the
route's window deadline. The route wrappers fail open like the usage
counters.

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

* feat(utils): add NDJSON stream reader

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

* feat(tts): stream Readest Voice windows as NDJSON with quota and cancel

POST /api/tts/readest/stream takes a window of sentences on the listen or
download lane, checks plan, voice tier and the remaining daily quota,
admits it through the per-user slots, starts one RunPod job and streams one
NDJSON line per sentence as it arrives, then a done line. Usage is charged
once for delivered sentences; a client disconnect cancels the RunPod job.

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

* feat(tts): Readest Voice voices and warmup route

GET lists the voices for the caller's plan and doubles as the capability
probe; POST {warmup: true} boots a worker when the voice picker opens.

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

* feat(tts): add windowed prefetch and fatal errors to the speech provider seam

SpeechProvider gains an optional prefetch(reqs, lane, signal, options) for
providers that synthesize several sentences per request. The buffered
client tells such providers about the current mark plus a lookahead of up
to 8 marks or about 30 s of estimated audio, and turns paragraph preloads
into a background prefetch of each paragraph's first two marks instead of
synthesizing whole paragraphs ahead. CachingProvider forwards only
uncached requests and persists every delivered sentence. A new
SpeechSynthesisFatalError (e.g. quota used up) ends a session or download
at once instead of being retried or skipped. Providers without prefetch
(Edge) are unchanged.

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

* refactor(tts): share the TTSLane type with the provider seam

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

* feat(tts): add Readest Voice speech provider with streamed windows

ReadestVoiceProvider requests sentences in windows from
/api/tts/readest/stream and resolves each as its NDJSON line arrives. One
window per lane is in flight: listen windows grow 1 -> 4 -> 8 and serve
the requests playback waits on before background preloads, never mixing
languages; download windows hold up to 64 sentences and retry after BUSY.
A sentence is withdrawn once every caller that asked for it has aborted,
and a window nobody wants is aborted, which cancels its GPU job. Quota
exhaustion is fatal for the session and announced once; a slow first
window announces the cold start once.

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

* feat(tts): register Readest Voice in the TTS controller

The controller builds one per-book cache store and shares it between Edge
and a new BufferedTTSClient over ReadestVoiceProvider (two stores on one
book's cache.db would contend for its OPFS handle). Readest Voice inits
alongside the other engines but never becomes the default; its picker group
appears only when available and opening it warms a worker; setVoice('')
never selects it. Gaps, primary language and shutdown fan out to it, and
chapter downloads use whichever synthetic engine is active.

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

* feat(tts): synthesize chapter downloads on the Readest Voice download lane

The downloader announces each section to a windowed engine before warming
it sentence by sentence, so a chapter synthesizes in a few large download
windows instead of one request per sentence. A fatal failure such as the
daily quota ends the whole download.

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

* feat(tts): Readest Voice quota and slow-start toasts

Toast when the daily synthesis quota is used up and when a cold GPU worker
delays the first premium audio. Translations carried over from the earlier
Readest Voice branch; Georgian added.

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

* fix(tts): do not report an aborted synthesis as a failed attempt

Stopping or seeking aborts the in-flight synthesis on purpose; windowed
providers reject it with an AbortError, which the retry loop logged as a
failure before noticing the abort.

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

* chore(tts): refer to the Readest Voice worker repo by its new name

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

* fix(tts): keep Readest Voice to the languages it has voices for

A remembered Readest Voice choice no longer applies to a book in a
language it cannot voice: Edge, the default engine, reads that book and
the choice stays remembered. Within a book, a sentence in such a language
is skipped instead of being read with a voice of another language; Edge
keeps its multilingual fallback. The picker hides an empty Readest group.

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

* fix(tts): size the windowed lookahead from estimated synthesis lead time

Against the real GPU worker, read-aloud stalled whenever short sentences were
followed by a long one: the lookahead stopped at 30 s of estimated audio from
the scheduler's position, so with long sentences it asked for the current mark
only, and preloads of the next paragraph covered just its first two marks.

A mark is now also asked for while the audio queued ahead of it would play out
before the provider could deliver everything up to it (one window at a time,
3 s overhead, 0.5 synthesis seconds per audio second), on top of the 30 s
horizon and within the 8-mark cap. Preloads use the same rule from the start
of the paragraph instead of a fixed two marks.

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

* fix(tts): buffer Readest Voice minutes ahead and keep preloads in order

End to end against the GPU worker, read-aloud still paused at paragraph
changes and the player's buffer bar never moved ahead of the playhead:

- The caching wrapper filled its cache for every prefetched sentence through
  synthesize(), which the provider took as "the listener is waiting": every
  background preload became foreground, so the current paragraph could not
  preempt preloads of later ones. Cache fills now carry the prefetch options
  and stay at background priority; requests already being filled are still
  forwarded so the provider can promote them when their paragraph starts.
- preloadNextSSML started the next paragraphs' preloads in parallel, so a
  windowed provider queued them in completion order, not reading order. They
  now run one after another.
- The lookahead now covers about three minutes of estimated audio within the
  paragraph (32 marks) and preloads give each upcoming paragraph its first
  minute, replacing the 30 s horizon and the synthesis-lead rule.
- Listen windows hold at most about 20 s of estimated audio, so a sentence
  that falls due never waits long behind the window in flight.
- Windowed prefetch reports each delivered (or already cached) sentence, and
  the client records its duration as an Edge preload does, so it counts as
  buffered.
- The section timeline adopts the client's voice when playback info is read:
  a client whose voices load asynchronously resolves its voice only after
  the timeline was built, and durations are keyed by that voice.

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

* fix(tts): keep minutes of Readest Voice audio buffered and show it

The buffer ran dry and the player's buffer bar never moved ahead:

- preloadNextSSML preloaded a fixed four paragraphs. For a windowed engine
  (new TTSCapabilities.windowedPrefetch), where preloads are hints batched on
  the GPU worker, it now preloads upcoming paragraphs until about three
  minutes of estimated audio (at most 40), so requests always run ahead of
  playback; other clients keep four.
- The buffer bar showed the measured share of the whole section, which only
  reads right when playback started at the section's beginning. It now shows
  where buffered audio ends: from the playing sentence through the run of
  measured sentences after it.
- A punctuation-only fragment from sentence segmentation is never synthesized,
  so it was never measured and stopped that run for good; a sentence with
  nothing to speak now counts as known.

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

* fix(tts): drop the "starting premium voice" notice

A toast on a slow first window tells the user to wait instead of removing the
wait; the delay is to be engineered away (warm worker, buffering) rather
than announced.

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

* fix(tts): keep the mini player up while the first audio is coming

The full mini player hid 5 s after a session started unless the toolbar was
showing, so a slow first sentence (a GPU voice resuming its worker) left the
reader with no sign that anything was happening. It now stays up, with its
spinning play button, for as long as nothing is audible, and starts the 5 s
linger once audio does.

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

* perf(tts): fewer round trips before a Readest Voice window streams

Each window paid five sequential round trips (gate, quota, slot, RunPod
run, slot job id) before audio could flow, then polled /stream every 250 ms;
for Kokoro that overhead is many times the synthesis itself. The quota check
and the slot now run together (a slot taken for a window over quota is given
back), the superseded job is cancelled without waiting on it, the job id is
recorded while the job already streams (a window that turns out to have lost
the slot is cancelled then), and empty polls wait 100 ms.

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

* feat(tts): block Qwen3 voices; Readest Voice serves Kokoro only

Qwen3 is left out of the engine-to-plan table, so the voices route hides
its voices for every plan and the stream route rejects them with
VOICE_TIER_REQUIRED, even though the worker catalog still lists them.

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

* feat(tts): OmniVoice voices for the Pro plan

Readest Voice now serves two engines: Kokoro for Plus and Pro, and
OmniVoice for Pro. Qwen3 stays blocked for every plan.

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

* perf(tts): read a paragraph without walking the chapter before it

Bumps foliate-js: the text walker started every paragraph at the
chapter's first node, so stepping through paragraphs deep in a long
chapter cost seconds of main-thread time. Read-aloud start and paragraph
changes stalled on it (about 30 s before first audio in a long chapter
with a three-minute lookahead).

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

* fix(tts): keep read-aloud responsive and its prefetch on the current voice

- Background preloads share one signal that a voice change or a stop
  aborts, so queued sentences in the old voice are withdrawn instead of
  reaching the worker (and the quota) after the switch. A paragraph
  handover keeps them: they are the next paragraphs' audio.
- The next paragraphs are preloaded once this paragraph is audible:
  stepping through them is synchronous DOM work that otherwise sat in the
  pause between paragraphs.
- A windowed client's preload carries on into the next chapter when this
  one ends inside the lookahead.

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

* perf(tts): play prefetched sentences from memory

The cache keeps recently read or synthesized sentences in memory (up to
16 MB), so a paragraph fetched ahead starts without a store read, which
costs hundreds of ms on device. Also pins that a paragraph handover keeps
the listen window size.

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

* feat(tts): Plus and Pro badges on Readest Voice voices

The voices route tags each voice with the plan that unlocks it, from the
same engine table that gates access, and the voice list shows it as a
badge next to the name.

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

* perf(tts): fewer, bigger Readest Voice requests

- A window of background preloads only may carry about 60 s of audio
  (windows the listener waits on keep the 20 s cap), so OmniVoice batches
  several sentences per request instead of one.
- A window frees the lane as soon as its last sentence arrives instead of
  waiting seconds for the job's final status line.

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

* perf(tts): start read-aloud sooner

- TTS engines initialize concurrently (Edge's probe sentence and the system
  voice list each took seconds, one after another, before every start).
- The book's audio cache opens during engine init, not on the first
  sentence's lookup.
- The next paragraphs are preloaded once this one is audible or after
  0.5 s, whichever comes first, so an uncached start still prefetches.

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

* fix(tts): keep word highlights in step with the audio

A sentence whose audio arrived after the previous one had already ended
never got a chunk-start, so it played with no mark and no word
highlight. The player now announces such a chunk when it schedules it.

The first word of each sentence was barely highlighted while audible:
the forced aligner places words early, the first one often inside the
leading silence the player trims, so the second word lit up as soon as
the first became audible. Boundaries now shift so the first word starts
with the speech, and the playback position trails the context clock by
the output latency.

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

* fix(tts): say TTS is not available for this page

Starting TTS on a page with nothing to read, such as a full-page image,
blamed the whole document.

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

* feat(tts): tint the sounding sentence under the word highlight

In word mode the sentence being read is tinted from the moment its mark
is dispatched, even while its audio is still pending, and stays until
the next sentence replaces it or the session ends. The word highlight
now only marks what is audible: the first word lights when its audio
starts instead of during the pause before it, and the previous
sentence's last word clears when the next sentence begins.

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

* feat(tts): queue Readest Voice windows fairly across users

One user with several devices or windows could keep many GPU jobs
running while others waited in the endpoint's first-come queue. A global
Durable Object now admits every window:

- at most READEST_VOICE_MAX_JOBS windows run at once, one per user and
  lane; a user's other windows wait in that user's queue
- a free slot goes to the waiting user served least recently, listening
  before downloads, with a quarter of the capacity kept for downloads
- an app instance names itself, so its own seek or voice change replaces
  its stale listen window at once while other devices of the user queue
- waits end after 60 s with BUSY, leases after the 180 s window
  deadline, and a request that goes away withdraws its wait

Running leases are persisted so a restarted instance keeps counting the
jobs still on the GPU. Calls fail open, as the per-user slots they
replace did; those slots and their migration are gone.

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

* feat(tts): run Readest Voice downloads as durable jobs any worker can pull

Chapter downloads become jobs held by the TTSDispatcher Durable Object, so
download capacity grows by starting more workers. Listening keeps its
streaming windows.

- The app submits each download window to /api/tts/readest/jobs (up to four
  at a time) and collects the result when done; the same window submitted
  again finds its job. Cancelling a download cancels its jobs.
- Workers pull from /api/tts/readest/workers with a per-worker token: lease
  (long poll, only jobs whose engines they run, optional version pin),
  heartbeat, complete. A lease that runs out puts the job back in the queue.
- The dispatcher starts RunPod jobs that carry only a lease for queued
  downloads, within the downloads' share of the endpoint, so downloads run
  with no other worker too.
- Results wait in the TTS_JOBS_R2 bucket as the stream route's NDJSON lines
  and are deleted once fetched; book text is dropped when a job ends.
- Unfinished jobs count against the daily quota; delivered sentences are
  charged when the job completes.
- Without the Durable Object or bucket (Node dev, self-hosting) the app
  streams downloads as before.

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

* chore(tts): size Readest Voice dispatch to the endpoint and pin worker version

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

* chore(deps): point foliate-js at the merged block-walk fix

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

* fix(tts): keep synthesizing Edge preloads behind the cache

CachingProvider always exposed prefetch, so every cached provider looked
windowed: Edge (cached on every platform) took the windowed preload path,
which only hints a provider that has no prefetch, and stopped synthesizing
upcoming paragraphs. The cache now offers prefetch only when its inner
provider has it.

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

* fix(tts): keep delivered Readest Voice sentences until playback takes them

A window that ended dropped every entry, answered ones included, so a
sentence prefetched before its turn was synthesized (and charged) again when
playback asked for it, whenever no cache sat in front of the provider. Only
unanswered sentences fail now; withdrawing delivered ones no longer resets
the listen window size.

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

* fix(tts): pass on only the validated fields of a Readest Voice window

Extra segment properties went to RunPod and into stored download jobs
without counting toward the window limits. Segments are rebuilt from their
id, text and voice.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-10-12 02:30:40 +08:00 • committed by GitHub
parent 385a322b8c
commit 0409a6172f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
104 changed files with 6742 additions and 167 deletions

View file

@ -12,6 +12,7 @@ Self-hosted premium TTS ("Readest Voice"): Kokoro v1.0 + v1.1-zh (Plus tier, EN/
**Documents (all on dev, plans dir is local-only/gitignored):**
- Spec: `docs/superpowers/specs/2026-07-08-selfhosted-premium-tts-design.md`
- Service plan (separate repo `readest-tts-server`): `.agents/plans/2026-07-08-readest-tts-server.md`
- 2026-10-09: the worker repo is now `readest-voice` (formerly `readest-tts-server`); v2 plans: `.agents/plans/2026-10-09-readest-tts-server-v2.md`, `.agents/plans/2026-10-09-readest-tts-app-v2.md`.
- App integration plan: `.agents/plans/2026-07-08-readest-tts-integration.md` (contains all 3 review reports + 30-row decision audit trail)
**Key user decisions (do not re-litigate):** gating plus/pro ONLY (purchase excluded — recurring GPU cost); quotas 100K/300K chars/day; self-hosted kept over managed-API despite both review models challenging it (cloning path + supplier independence); word-level alignment kept in v1; cold starts accepted but softened by warmup ping on voice-picker open (adopted at gate) + slow-start toast; usage meter and free-user upsell entry DECLINED; Edge stays default engine (premium is opt-in, `setVoice('')` must never match readest voices).

View file

@ -1,3 +1,16 @@
NEXT_PUBLIC_APP_PLATFORM=web
AI_GATEWAY_API_KEY=your_key_here
NEXT_PUBLIC_AI_GATEWAY_API_KEY=your_key_here
# Readest Voice (self-hosted premium TTS on RunPod Serverless). Unset either of
# the first two to disable it: the /api/tts/readest routes answer 503 and the
# engine hides (kill switch).
RUNPOD_API_KEY=
RUNPOD_TTS_ENDPOINT_ID=
# Voice catalog exported by the TTS worker (scripts/export_catalog.py).
READEST_TTS_CATALOG_URL=
# Optional: fixed daily TTS character quota for every plan (nonzero).
TTS_FIXED_QUOTA=
# Local development against the worker's Docker emulator:
# RUNPOD_API_BASE=http://localhost:8801
# RUNPOD_TTS_ENDPOINT_ID=local
# READEST_TTS_CATALOG_URL=http://localhost:8801/catalog.json

View file

@ -444,7 +444,6 @@
"Terms of Service": "شروط الخدمة",
"Privacy Policy": "سياسة الخصوصية",
"Disable Double Click": "تعطيل النقر المزدوج",
"TTS not supported for this document": "تكنولوجيا تحويل النص إلى كلام غير مدعومة لهذا المستند.",
"Reset Password": "إعادة تعيين",
"Reading Progress Style": "نمط تقدم القراءة",
"Page Number": "رقم الصفحة",
@ -2834,5 +2833,9 @@
"Book Info": "معلومات الكتاب",
"QR Code": "رمز QR",
"Links to this passage in Readest": "رابط إلى هذا المقطع في Readest",
"via {{app}}": "عبر {{app}}"
"via {{app}}": "عبر {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "تم الوصول إلى الحد اليومي لـ TTS. قم بترقية خطتك أو حاول مرة أخرى غداً.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "تحويل النص إلى كلام غير متاح لهذه الصفحة"
}

View file

@ -298,7 +298,6 @@
"Table of Contents": "সূচিপত্র",
"Sidebar": "সাইডবার",
"Disable Translation": "অনুবাদ নিষ্ক্রিয়",
"TTS not supported for this document": "এই ডকুমেন্টের জন্য TTS সমর্থিত নয়",
"No Timeout": "কোন টাইমআউট নেই",
"{{value}} minute": "{{value}} মিনিট",
"{{value}} minutes": "{{value}} মিনিট",
@ -2578,5 +2577,9 @@
"Book Info": "বইয়ের তথ্য",
"QR Code": "QR কোড",
"Links to this passage in Readest": "Readest-এ এই অংশের লিংক",
"via {{app}}": "{{app}}-এর মাধ্যমে"
"via {{app}}": "{{app}}-এর মাধ্যমে",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "দৈনিক TTS সীমা পৌঁছেছে। আপনার পরিকল্পনা আপগ্রেড করুন বা আগামীকাল আবার চেষ্টা করুন।",
"Pro": "প্রো",
"Plus": "প্লাস",
"TTS not available for this page": "এই পৃষ্ঠার জন্য TTS উপলব্ধ নয়"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "ཞབས་འདེགས་ཀྱི་ཆ་རྐྱེན།",
"Privacy Policy": "སྒེར་གསང་གི་སྲིད་ཇུས།",
"Disable Double Click": "ཐེངས་གཉིས་མནན་པ་སྒོ་བརྒྱབ།",
"TTS not supported for this document": "ཡིག་ཆ་འདིར་ TTS རྒྱབ་སྐྱོར་མི་བྱེད།",
"Reset Password": "གསང་ཨང་བསྐྱར་སྒྲིག",
"Reading Progress Style": "ཀློག་པའི་ཡར་འཕེལ་གྱི་རྣམ་པ།",
"Page Number": "ཤོག་ཨང་།",
@ -2514,5 +2513,9 @@
"Book Info": "དཔེ་དེབ་ཀྱི་ཆ་འཕྲིན།",
"QR Code": "QR ཨང་རྟགས།",
"Links to this passage in Readest": "Readest ནང་གི་ཚིག་ཚན་འདིར་སྦྲེལ་མཐུད།",
"via {{app}}": "{{app}} བརྒྱུད་"
"via {{app}}": "{{app}} བརྒྱུད་",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "ཉིན་རེའི་TTS ཚད་མར་སླེབས་སོང་། ཁྱོད་ཀྱི་འཇོག་ཐབས་མར་སྤར་གྱིས་ཡང་ན་སང་ཉིན་ཚོད་ལྟ་བྱོས།",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "ཤོག་ངོས་འདིར་ TTS མེད།"
}

View file

@ -428,7 +428,6 @@
"Terms of Service": "Allgemeine Geschäftsbedingungen",
"Privacy Policy": "Datenschutzbestimmungen",
"Disable Double Click": "Doppelklick deaktivieren",
"TTS not supported for this document": "TTS wird für dieses Dokument nicht unterstützt",
"Reset Password": "Passwort zurücksetzen",
"Reading Progress Style": "Lesefortschritt-Stil",
"Page Number": "Seitenzahl",
@ -2578,5 +2577,9 @@
"Book Info": "Buchinfo",
"QR Code": "QR-Code",
"Links to this passage in Readest": "Verweist auf diese Stelle in Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Tägliches TTS-Limit erreicht. Upgraden Sie Ihren Plan oder versuchen Sie es morgen erneut.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS ist für diese Seite nicht verfügbar"
}

View file

@ -428,7 +428,6 @@
"Terms of Service": "Όροι χρήσης",
"Privacy Policy": "Πολιτική απορρήτου",
"Disable Double Click": "Απενεργοποίηση διπλού κλικ",
"TTS not supported for this document": "Η τεχνολογία TTS δεν υποστηρίζεται για αυτό το έγγραφο.",
"Reset Password": "Επαναφορά κωδικού",
"Reading Progress Style": "Στυλ προόδου ανάγνωσης",
"Page Number": "Αριθμός σελίδας",
@ -2578,5 +2577,9 @@
"Book Info": "Στοιχεία βιβλίου",
"QR Code": "Κωδικός QR",
"Links to this passage in Readest": "Παραπέμπει σε αυτό το απόσπασμα στο Readest",
"via {{app}}": "μέσω {{app}}"
"via {{app}}": "μέσω {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Το ημερήσιο όριο TTS έχει επιτευχθεί. Αναβαθμίστε το πλάνο σας ή δοκιμάστε ξανά αύριο.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "Το TTS δεν είναι διαθέσιμο για αυτή τη σελίδα"
}

View file

@ -455,7 +455,6 @@
"Terms of Service": "Condiciones del servicio",
"Privacy Policy": "Política de privacidad",
"Disable Double Click": "Deshabilitar Doble Clic",
"TTS not supported for this document": "TTS no es compatible con este documento.",
"Reset Password": "Restablecer contraseña",
"Reading Progress Style": "Estilo de progreso de lectura",
"Percentage": "Porcentaje",
@ -2642,5 +2641,9 @@
"Book Info": "Información del libro",
"QR Code": "Código QR",
"Links to this passage in Readest": "Enlaza a este pasaje en Readest",
"via {{app}}": "vía {{app}}"
"via {{app}}": "vía {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Límite diario de TTS alcanzado. Actualiza tu plan o inténtalo de nuevo mañana.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS no está disponible para esta página"
}

View file

@ -428,7 +428,6 @@
"Terms of Service": "شرایط و قوانین",
"Privacy Policy": "سیاست حفظ حریم خصوصی",
"Disable Double Click": "غیرفعال کردن کلیک دوبل",
"TTS not supported for this document": "قابلیت تبدیل متن به گفتار برای این سند پشتیبانی نمی‌شود",
"Reset Password": "بازنشانی رمز عبور",
"Reading Progress Style": "سبک نمایش وضعیت مطالعه",
"Page Number": "شماره صفحه",
@ -2578,5 +2577,9 @@
"Book Info": "اطلاعات کتاب",
"QR Code": "کد QR",
"Links to this passage in Readest": "پیوند به این بخش در Readest",
"via {{app}}": "از طریق {{app}}"
"via {{app}}": "از طریق {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "محدودیت روزانه TTS به پایان رسید. پلن خود را ارتقا دهید یا فردا دوباره امتحان کنید.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "تبدیل متن به گفتار برای این صفحه در دسترس نیست"
}

View file

@ -432,7 +432,6 @@
"Terms of Service": "Conditions d'utilisation",
"Privacy Policy": "Politique de confidentialité",
"Disable Double Click": "Désactiver le double-clic",
"TTS not supported for this document": "TTS non pris en charge pour ce document",
"Reset Password": "Nouveau mot de passe",
"Reading Progress Style": "Style de progression",
"Page Number": "Numéro de page",
@ -2642,5 +2641,9 @@
"Book Info": "Infos du livre",
"QR Code": "Code QR",
"Links to this passage in Readest": "Renvoie vers ce passage dans Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Limite TTS quotidienne atteinte. Améliorez votre abonnement ou réessayez demain.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS non disponible pour cette page"
}

View file

@ -551,7 +551,6 @@
"Previous Sentence": "משפט קודם",
"Next Sentence": "משפט הבא",
"Please log in to use advanced TTS features": "אנא התחבר כדי להשתמש בתכונות TTS מתקדמות",
"TTS not supported for this document": "TTS אינו נתמך עבור מסמך זה",
"No Timeout": "ללא הגבלת זמן",
"{{value}} minute": "דקה {{value}}",
"{{value}} minutes": "{{value}} דקות",
@ -2642,5 +2641,9 @@
"Book Info": "פרטי הספר",
"QR Code": "קוד QR",
"Links to this passage in Readest": "קישור לקטע הזה ב-Readest",
"via {{app}}": "דרך {{app}}"
"via {{app}}": "דרך {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "הגעת למגבלת ה-TTS היומית. שדרג את התוכנית שלך או נסה שוב מחר.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS אינו זמין עבור עמוד זה"
}

View file

@ -428,7 +428,6 @@
"Terms of Service": "सेवा की शर्तें",
"Privacy Policy": "गोपनीयता नीति",
"Disable Double Click": "डबल क्लिक अक्षम करें",
"TTS not supported for this document": "TTS इस दस्तावेज़ के लिए समर्थित नहीं है",
"Reset Password": "पासवर्ड रीसेट करें",
"Reading Progress Style": "पढ़ने की प्रगति शैली",
"Page Number": "पृष्ठ संख्या",
@ -2578,5 +2577,9 @@
"Book Info": "पुस्तक जानकारी",
"QR Code": "QR कोड",
"Links to this passage in Readest": "Readest में इस अंश का लिंक",
"via {{app}}": "{{app}} के ज़रिए"
"via {{app}}": "{{app}} के ज़रिए",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "दैनिक TTS सीमा पहुँच गई। अपना प्लान अपग्रेड करें या कल पुनः प्रयास करें।",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "इस पृष्ठ के लिए TTS उपलब्ध नहीं है"
}

View file

@ -653,7 +653,6 @@
"Readwise sync failed: {{error}}": "Readwise szinkronizálás sikertelen: {{error}}",
"Translating...": "Fordítás...",
"Please log in to use advanced TTS features": "Kérjük, jelentkezzen be a haladó TTS-funkciók használatához",
"TTS not supported for this document": "A TTS nem támogatott ehhez a dokumentumhoz",
"Delete Your Account?": "Törli a fiókját?",
"This action cannot be undone. All your data in the cloud will be permanently deleted.": "Ez a művelet nem vonható vissza. Minden felhőbeli adata véglegesen törlődik.",
"Delete Permanently": "Végleges törlés",
@ -2578,5 +2577,9 @@
"Book Info": "Könyvadatok",
"QR Code": "QR-kód",
"Links to this passage in Readest": "Erre a részre mutat a Readestben",
"via {{app}}": "a(z) {{app}} segítségével"
"via {{app}}": "a(z) {{app}} segítségével",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Napi TTS-korlát elérve. Frissítse tervét, vagy próbálja újra holnap.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "A TTS nem érhető el ezen az oldalon"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "Ketentuan Layanan",
"Privacy Policy": "Kebijakan Privasi",
"Disable Double Click": "Nonaktifkan Klik Ganda",
"TTS not supported for this document": "TTS tidak didukung untuk dokumen ini",
"Reset Password": "Reset Kata Sandi",
"Reading Progress Style": "Gaya Progres Membaca",
"Page Number": "Nomor Halaman",
@ -2514,5 +2513,9 @@
"Book Info": "Info Buku",
"QR Code": "Kode QR",
"Links to this passage in Readest": "Tautan ke bagian ini di Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Batas TTS harian tercapai. Tingkatkan paket Anda atau coba lagi besok.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS tidak tersedia untuk halaman ini"
}

View file

@ -432,7 +432,6 @@
"Terms of Service": "Termini di servizio",
"Privacy Policy": "Informativa sulla privacy",
"Disable Double Click": "Disabilita Doppio Clic",
"TTS not supported for this document": "TTS non supportato per questo documento",
"Reset Password": "Reimposta Password",
"Reading Progress Style": "Stile di Progresso Lettura",
"Page Number": "Numero di Pagina",
@ -2642,5 +2641,9 @@
"Book Info": "Info libro",
"QR Code": "Codice QR",
"Links to this passage in Readest": "Rimanda a questo passo in Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Limite TTS giornaliero raggiunto. Aggiorna il tuo piano o riprova domani.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS non disponibile per questa pagina"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "利用規約",
"Privacy Policy": "プライバシーポリシー",
"Disable Double Click": "ダブルクリック無効",
"TTS not supported for this document": "TTSはこのドキュメントではサポートされていません",
"Reset Password": "パスワードをリセット",
"Reading Progress Style": "読書進捗スタイル",
"Page Number": "ページ番号",
@ -2514,5 +2513,9 @@
"Book Info": "書籍情報",
"QR Code": "QRコード",
"Links to this passage in Readest": "Readest のこの箇所へのリンク",
"via {{app}}": "{{app}} より"
"via {{app}}": "{{app}} より",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "1日のTTS制限に達しました。プランをアップグレードするか、明日再試行してください。",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "このページではTTSを利用できません"
}

View file

@ -988,7 +988,6 @@
"Readwise sync failed: {{error}}": "Readwise-ის სინქრონიზაცია ვერ მოხერხდა: {{error}}",
"Translating...": "მიმდინარეობს თარგმნა...",
"Please log in to use advanced TTS features": "გაფართოებული TTS ფუნქციების გამოსაყენებლად გთხოვთ, შეხვიდეთ",
"TTS not supported for this document": "TTS არ არის მხარდაჭერილი ამ დოკუმენტისთვის",
"Section {{index}}": "სექცია {{index}}",
"Expires in {{count}} days_one": "ვადა იწურება {{count}} დღეში",
"Expires in {{count}} days_other": "ვადა იწურება {{count}} დღეში",
@ -2578,5 +2577,9 @@
"Book Info": "წიგნის ინფორმაცია",
"QR Code": "QR კოდი",
"Links to this passage in Readest": "ბმული ამ მონაკვეთზე Readest-ში",
"via {{app}}": "{{app}}-ის მეშვეობით"
"via {{app}}": "{{app}}-ის მეშვეობით",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "TTS-ის დღიური ლიმიტი ამოიწურა. განაახლეთ გეგმა ან სცადეთ ხვალ.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS მიუწვდომელია ამ გვერდისთვის"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "서비스 약관",
"Privacy Policy": "개인정보 보호정책",
"Disable Double Click": "더블 클릭 비활성화",
"TTS not supported for this document": "TTS가 이 문서에서 지원되지 않습니다",
"Reset Password": "비밀번호 재설정",
"Reading Progress Style": "읽기 진행 상황 스타일",
"Page Number": "페이지 번호",
@ -2514,5 +2513,9 @@
"Book Info": "책 정보",
"QR Code": "QR 코드",
"Links to this passage in Readest": "Readest에서 이 구절로 연결됩니다",
"via {{app}}": "{{app}}에서"
"via {{app}}": "{{app}}에서",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "일일 TTS 한도에 도달했습니다. 플랜을 업그레이드하거나 내일 다시 시도하세요.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "이 페이지에서는 TTS를 사용할 수 없습니다"
}

View file

@ -284,7 +284,6 @@
"Play": "Main",
"Next Sentence": "Ayat Seterusnya",
"Next Paragraph": "Perenggan Seterusnya",
"TTS not supported for this document": "TTS tidak disokong untuk dokumen ini",
"No Timeout": "Tiada Had Masa",
"{{value}} minute": "{{value}} minit",
"{{value}} minutes": "{{value}} minit",
@ -2514,5 +2513,9 @@
"Book Info": "Maklumat Buku",
"QR Code": "Kod QR",
"Links to this passage in Readest": "Pautan ke petikan ini dalam Readest",
"via {{app}}": "melalui {{app}}"
"via {{app}}": "melalui {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Had TTS harian dicapai. Naik taraf pelan anda atau cuba lagi esok.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS tidak tersedia untuk halaman ini"
}

View file

@ -428,7 +428,6 @@
"Terms of Service": "Gebruiksvoorwaarden",
"Privacy Policy": "Privacybeleid",
"Disable Double Click": "Dubbelklikken uitschakelen",
"TTS not supported for this document": "TTS niet ondersteund voor dit document",
"Reset Password": "Wachtwoord resetten",
"Reading Progress Style": "Stijl van leesvoortgang",
"Page Number": "Pagina nummer",
@ -2578,5 +2577,9 @@
"Book Info": "Boekinfo",
"QR Code": "QR-code",
"Links to this passage in Readest": "Linkt naar deze passage in Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Dagelijkse TTS-limiet bereikt. Upgrade uw abonnement of probeer het morgen opnieuw.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS niet beschikbaar voor deze pagina"
}

View file

@ -436,7 +436,6 @@
"Terms of Service": "Warunki korzystania z usługi",
"Privacy Policy": "Polityka prywatności",
"Disable Double Click": "Wyłącz podwójne kliknięcie",
"TTS not supported for this document": "TTS nie jest obsługiwane dla tego dokumentu",
"Reset Password": "Zresetuj hasło",
"Reading Progress Style": "Styl postępu czytania",
"Page Number": "Numer strony",
@ -2706,5 +2705,9 @@
"Book Info": "Informacje o książce",
"QR Code": "Kod QR",
"Links to this passage in Readest": "Prowadzi do tego fragmentu w Readest",
"via {{app}}": "przez {{app}}"
"via {{app}}": "przez {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Osiągnięto dzienny limit TTS. Ulepsz plan lub spróbuj ponownie jutro.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS jest niedostępne dla tej strony"
}

View file

@ -725,7 +725,6 @@
"Readwise sync failed: {{error}}": "Falha na sincronização com o Readwise: {{error}}",
"Translating...": "Traduzindo...",
"Please log in to use advanced TTS features": "Faça login para usar recursos avançados de TTS",
"TTS not supported for this document": "TTS não suportado para este documento",
"Expires in {{count}} days_one": "Expira em 1 dia",
"Expires in {{count}} days_many": "Expira em {{count}} dias",
"Expires in {{count}} days_other": "Expira em {{count}} dias",
@ -2642,5 +2641,9 @@
"Book Info": "Informações do livro",
"QR Code": "Código QR",
"Links to this passage in Readest": "Leva a este trecho no Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Limite diário de TTS atingido. Atualize seu plano ou tente novamente amanhã.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS não disponível para esta página"
}

View file

@ -432,7 +432,6 @@
"Terms of Service": "Termos de Serviço",
"Privacy Policy": "Política de Privacidade",
"Disable Double Click": "Desativar Clique Duplo",
"TTS not supported for this document": "TTS não suportado para este documento",
"Reset Password": "Redefinir Senha",
"Reading Progress Style": "Estilo de Progresso de Leitura",
"Page Number": "Número da Página",
@ -2642,5 +2641,9 @@
"Book Info": "Informações do livro",
"QR Code": "Código QR",
"Links to this passage in Readest": "Leva a este trecho no Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Limite diário de TTS atingido. Atualize o seu plano ou tente novamente amanhã.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS não disponível para esta página"
}

View file

@ -644,7 +644,6 @@
"Readwise sync failed: {{error}}": "Sincronizarea Readwise a eșuat: {{error}}",
"Translating...": "Se traduce...",
"Please log in to use advanced TTS features": "Vă rugăm să vă conectați pentru a utiliza funcțiile TTS avansate",
"TTS not supported for this document": "TTS nu este acceptat pentru acest document",
"Delete Your Account?": "Ștergeți contul dvs.?",
"This action cannot be undone. All your data in the cloud will be permanently deleted.": "Această acțiune nu poate fi anulată. Toate datele dvs. din cloud vor fi șterse permanent.",
"Delete Permanently": "Șterge definitiv",
@ -2642,5 +2641,9 @@
"Book Info": "Informații carte",
"QR Code": "Cod QR",
"Links to this passage in Readest": "Trimite la acest pasaj în Readest",
"via {{app}}": "prin {{app}}"
"via {{app}}": "prin {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Limita zilnică TTS a fost atinsă. Faceți upgrade la planul dvs. sau încercați din nou mâine.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS nu este disponibil pentru această pagină"
}

View file

@ -436,7 +436,6 @@
"Terms of Service": "Условия использования",
"Privacy Policy": "Политика конфиденциальности",
"Disable Double Click": "Отключить двойной клик",
"TTS not supported for this document": "TTS не поддерживается для этого документа",
"Reset Password": "Сбросить пароль",
"Reading Progress Style": "Стиль прогресса чтения",
"Page Number": "Номер страницы",
@ -2706,5 +2705,9 @@
"Book Info": "Сведения о книге",
"QR Code": "QR-код",
"Links to this passage in Readest": "Ссылка на этот отрывок в Readest",
"via {{app}}": "через {{app}}"
"via {{app}}": "через {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Достигнут дневной лимит TTS. Обновите план или повторите попытку завтра.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS недоступен для этой страницы"
}

View file

@ -298,7 +298,6 @@
"Table of Contents": "සූචිය",
"Sidebar": "පැති තීරුව",
"Disable Translation": "පරිවර්තනය අබල කරන්න",
"TTS not supported for this document": "මෙම ලේඛනය සඳහා TTS සහාය නොදක්වයි",
"No Timeout": "කාල සීමාවක් නැත",
"{{value}} minute": "මිනිත්තු {{value}}",
"{{value}} minutes": "මිනිත්තු {{value}}",
@ -2578,5 +2577,9 @@
"Book Info": "පොතේ තොරතුරු",
"QR Code": "QR කේතය",
"Links to this passage in Readest": "Readest හි මෙම කොටසට සබැඳිය",
"via {{app}}": "{{app}} හරහා"
"via {{app}}": "{{app}} හරහා",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "දෛනික TTS සීමාවට ළඟා විය. ඔබේ සැලැස්ම උසස් කරන්න හෝ හෙට නැවත උත්සාහ කරන්න.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "මෙම පිටුව සඳහා TTS ලබා ගත නොහැක"
}

View file

@ -618,7 +618,6 @@
"Readwise sync failed: {{error}}": "Sinhronizacija z Readwise ni uspela: {{error}}",
"Translating...": "Prevajanje...",
"Please log in to use advanced TTS features": "Prosimo, prijavite se za uporabo naprednih TTS funkcij",
"TTS not supported for this document": "TTS ni podprt za ta dokument",
"Delete Your Account?": "Izbrišem vaš račun?",
"This action cannot be undone. All your data in the cloud will be permanently deleted.": "Tega dejanja ni mogoče razveljaviti. Vsi vaši podatki v oblaku bodo trajno izbrisani.",
"Delete Permanently": "Trajno izbriši",
@ -2706,5 +2705,9 @@
"Book Info": "Podatki o knjigi",
"QR Code": "Koda QR",
"Links to this passage in Readest": "Povezava do tega odlomka v Readest",
"via {{app}}": "prek {{app}}"
"via {{app}}": "prek {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Dosežena dnevna omejitev TTS. Nadgradite svojo naročnino ali poskusite jutri znova.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS ni na voljo za to stran"
}

View file

@ -267,7 +267,6 @@
"Play": "Spela",
"Next Sentence": "Nästa mening",
"Next Paragraph": "Nästa stycke",
"TTS not supported for this document": "Uppläsning stöds inte för detta dokument",
"No Timeout": "Ingen timeout",
"{{value}} minute": "{{value}} minut",
"{{value}} minutes": "{{value}} minuter",
@ -2578,5 +2577,9 @@
"Book Info": "Bokinfo",
"QR Code": "QR-kod",
"Links to this passage in Readest": "Länkar till det här stycket i Readest",
"via {{app}}": "via {{app}}"
"via {{app}}": "via {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Daglig TTS-gräns nådd. Uppgradera din plan eller försök igen imorgon.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "Uppläsning är inte tillgänglig för den här sidan"
}

View file

@ -298,7 +298,6 @@
"Table of Contents": "உள்ளடக்கம்",
"Sidebar": "பக்கப்பட்டி",
"Disable Translation": "மொழிபெயர்ப்பை முடக்கவும்",
"TTS not supported for this document": "இந்த ஆவணத்திற்கு TTS ஆதரிக்கப்படவில்லை",
"No Timeout": "நேர வரம்பு இல்லை",
"{{value}} minute": "{{value}} நிமிடம்",
"{{value}} minutes": "{{value}} நிமிடங்கள்",
@ -2578,5 +2577,9 @@
"Book Info": "புத்தகத் தகவல்",
"QR Code": "QR குறியீடு",
"Links to this passage in Readest": "Readest-இல் இந்தப் பகுதிக்கான இணைப்பு",
"via {{app}}": "{{app}} வழியாக"
"via {{app}}": "{{app}} வழியாக",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "தினசரி TTS வரம்பை எட்டிவிட்டது. உங்கள் திட்டத்தை மேம்படுத்துங்கள் அல்லது நாளை மீண்டும் முயற்சிக்கவும்.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "இந்தப் பக்கத்திற்கு TTS கிடைக்கவில்லை"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "ข้อกำหนดในการให้บริการ",
"Privacy Policy": "นโยบายความเป็นส่วนตัว",
"Disable Double Click": "ปิดการคลิกสองครั้ง",
"TTS not supported for this document": "ไม่รองรับ TTS สำหรับเอกสารนี้",
"Reset Password": "รีเซ็ตพาสเวิร์ด",
"Reading Progress Style": "สไตล์ความก้าวหน้าในการอ่าน",
"Page Number": "หมายเลขหน้า",
@ -2514,5 +2513,9 @@
"Book Info": "ข้อมูลหนังสือ",
"QR Code": "คิวอาร์โค้ด",
"Links to this passage in Readest": "ลิงก์ไปยังข้อความนี้ใน Readest",
"via {{app}}": "ผ่าน {{app}}"
"via {{app}}": "ผ่าน {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "ถึงขีดจำกัด TTS รายวันแล้ว อัพเกรดแผนของคุณหรือลองใหม่อีกครั้งในวันพรุ่งนี้",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "ไม่มี TTS สำหรับหน้านี้"
}

View file

@ -428,7 +428,6 @@
"Terms of Service": "Hizmet Şartları",
"Privacy Policy": "Gizlilik Politikası",
"Disable Double Click": "Çift Tıklamayı Devre Dışı Bırak",
"TTS not supported for this document": "TTS bu belge için desteklenmiyor",
"Reset Password": "Şifreyi Sıfırla",
"Reading Progress Style": "Okuma İlerlemesi Stili",
"Page Number": "Sayfa Numarası",
@ -2578,5 +2577,9 @@
"Book Info": "Kitap Bilgisi",
"QR Code": "QR Kodu",
"Links to this passage in Readest": "Readest'te bu bölüme bağlantı verir",
"via {{app}}": "{{app}} ile"
"via {{app}}": "{{app}} ile",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Günlük TTS limitine ulaşıldı. Planınızı yükseltin veya yarın tekrar deneyin.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS bu sayfa için kullanılamıyor"
}

View file

@ -436,7 +436,6 @@
"Terms of Service": "Умови обслуговування",
"Privacy Policy": "Політика конфіденційності",
"Disable Double Click": "Вимкнути подвійне натискання",
"TTS not supported for this document": "TTS не підтримується в цьому документі",
"Reset Password": "Скинути пароль",
"Reading Progress Style": "Стиль проґресу читання",
"Page Number": "Номер сторінки",
@ -2706,5 +2705,9 @@
"Book Info": "Інформація про книгу",
"QR Code": "QR-код",
"Links to this passage in Readest": "Посилання на цей уривок у Readest",
"via {{app}}": "через {{app}}"
"via {{app}}": "через {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Досягнуто щоденного ліміту TTS. Оновіть план або спробуйте знову завтра.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS недоступний для цієї сторінки"
}

View file

@ -712,7 +712,6 @@
"Readwise sync failed: {{error}}": "Readwise sinxronlashda xato: {{error}}",
"Translating...": "Tarjima qilinmoqda...",
"Please log in to use advanced TTS features": "Kengaytirilgan TTS xususiyatlaridan foydalanish uchun tizimga kiring",
"TTS not supported for this document": "Ushbu hujjat uchun TTS qoʻllab-quvvatlanmaydi",
"Expires in {{count}} days_one": "{{count}} kunda muddati tugaydi",
"Expires in {{count}} days_other": "{{count}} kunda muddati tugaydi",
"Expires in {{count}} hours_one": "{{count}} soatda muddati tugaydi",
@ -2578,5 +2577,9 @@
"Book Info": "Kitob ma’lumoti",
"QR Code": "QR kod",
"Links to this passage in Readest": "Readest’dagi ushbu parchaga havola",
"via {{app}}": "{{app}} orqali"
"via {{app}}": "{{app}} orqali",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Kunlik TTS chegarasiga yetildi. Rejangizni yangilang yoki ertaga qayta urinib ko'ring.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "Ushbu sahifa uchun TTS mavjud emas"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "Điều khoản dịch vụ",
"Privacy Policy": "Chính sách bảo mật",
"Disable Double Click": "Tắt Nhấp Đôi",
"TTS not supported for this document": "TTS không được hỗ trợ cho tài liệu này",
"Reset Password": "Đặt lại mật khẩu",
"Reading Progress Style": "Phong cách tiến độ đọc",
"Page Number": "Số trang",
@ -2514,5 +2513,9 @@
"Book Info": "Thông tin sách",
"QR Code": "Mã QR",
"Links to this passage in Readest": "Liên kết đến đoạn này trong Readest",
"via {{app}}": "qua {{app}}"
"via {{app}}": "qua {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "Đã đạt giới hạn TTS hàng ngày. Nâng cấp gói của bạn hoặc thử lại vào ngày mai.",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "TTS không khả dụng cho trang này"
}

View file

@ -425,7 +425,6 @@
"Terms of Service": "服务条款",
"Privacy Policy": "隐私政策",
"Disable Double Click": "禁用双击",
"TTS not supported for this document": "TTS 不支持此文档",
"Reset Password": "重置密码",
"Reading Progress Style": "阅读进度样式",
"Page Number": "页码",
@ -2514,5 +2513,9 @@
"Book Info": "书籍信息",
"QR Code": "二维码",
"Links to this passage in Readest": "链接到 Readest 中的这段文字",
"via {{app}}": "来自 {{app}}"
"via {{app}}": "来自 {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "已达到每日 TTS 限额。请升级您的计划或明天再试。",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "此页面无法使用 TTS"
}

View file

@ -424,7 +424,6 @@
"Terms of Service": "服務條款",
"Privacy Policy": "隱私政策",
"Disable Double Click": "禁用雙擊",
"TTS not supported for this document": "TTS 不支援此文件",
"Reset Password": "重設密碼",
"Reading Progress Style": "閱讀進度樣式",
"Page Number": "頁碼",
@ -2514,5 +2513,9 @@
"Book Info": "書籍資訊",
"QR Code": "QR 碼",
"Links to this passage in Readest": "連結到 Readest 中的這段文字",
"via {{app}}": "來自 {{app}}"
"via {{app}}": "來自 {{app}}",
"Daily TTS limit reached. Upgrade your plan or try again tomorrow.": "已達到每日 TTS 限制。請升級您的方案或明天再試。",
"Pro": "Pro",
"Plus": "Plus",
"TTS not available for this page": "此頁面無法使用 TTS"
}

View file

@ -0,0 +1,211 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextRequest } from 'next/server';
const m = vi.hoisted(() => ({
validateUserAndToken: vi.fn(),
getSubscriptionPlan: vi.fn(),
getCatalog: vi.fn(),
getRunPodConfig: vi.fn(),
getCurrentUsage: vi.fn(),
dispatcher: {
submitJob: vi.fn(),
waitJob: vi.fn(),
cancelJob: vi.fn(),
forgetJob: vi.fn(),
},
bucket: { put: vi.fn(), get: vi.fn(), delete: vi.fn() },
bound: true,
}));
vi.mock('@/utils/access', async (orig) => ({
...(await orig<typeof import('@/utils/access')>()),
validateUserAndToken: m.validateUserAndToken,
getSubscriptionPlan: m.getSubscriptionPlan,
}));
vi.mock('@/libs/readestVoice/catalog', async (orig) => ({
...(await orig<typeof import('@/libs/readestVoice/catalog')>()),
getCatalog: m.getCatalog,
}));
vi.mock('@/libs/readestVoice/runpod', () => ({ getRunPodConfig: m.getRunPodConfig }));
vi.mock('@/libs/readestVoice/bindings', async (orig) => ({
...(await orig<typeof import('@/libs/readestVoice/bindings')>()),
getDispatcher: () => (m.bound ? m.dispatcher : null),
getResultBucket: () => (m.bound ? m.bucket : null),
}));
vi.mock('@/utils/usage', async (orig) => ({
...(await orig<typeof import('@/utils/usage')>()),
UsageStatsManager: { getCurrentUsage: m.getCurrentUsage },
}));
import { POST } from '@/app/api/tts/readest/jobs/route';
import { DELETE, GET } from '@/app/api/tts/readest/jobs/[id]/route';
const CATALOG = [
{ id: 'kokoro:af_heart', engine: 'kokoro', name: 'Heart', langs: ['en-US'] },
{ id: 'omnivoice:clara', engine: 'omnivoice', name: 'Clara', langs: ['en-US'] },
];
const JOB_ID = 'a'.repeat(32);
const seg = (id: string, text = 'Hello world.', voice = 'kokoro:af_heart') => ({ id, text, voice });
const download = (...segments: ReturnType<typeof seg>[]) => ({
client: 'phone',
lane: 'download',
lang: 'en-US',
segments,
});
const request = (method: string, path: string, body?: unknown) =>
new NextRequest(`https://web.readest.com/api/tts/readest/jobs${path}`, {
method,
headers: { authorization: 'Bearer tok', 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const params = (id = JOB_ID) => ({ params: Promise.resolve({ id }) });
beforeEach(() => {
for (const fn of [
m.validateUserAndToken,
m.getSubscriptionPlan,
m.getCatalog,
m.getRunPodConfig,
m.getCurrentUsage,
...Object.values(m.dispatcher),
...Object.values(m.bucket),
]) {
fn.mockReset();
}
m.bound = true;
m.validateUserAndToken.mockResolvedValue({ user: { id: 'user-1' }, token: 'tok' });
m.getSubscriptionPlan.mockReturnValue('pro');
m.getCatalog.mockResolvedValue(CATALOG);
m.getRunPodConfig.mockReturnValue({ apiKey: 'k', endpointId: 'ep', base: 'https://rp.test' });
m.getCurrentUsage.mockResolvedValue(1_000);
m.dispatcher.submitJob.mockResolvedValue({ ok: true, state: 'queued' });
m.dispatcher.forgetJob.mockResolvedValue(undefined);
m.bucket.delete.mockResolvedValue(undefined);
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => vi.restoreAllMocks());
describe('POST /jobs', () => {
it('queues the window with its engines and the quota left, under a stable id', async () => {
const body = download(seg('s0'), seg('s1', 'Hi there.', 'omnivoice:clara'));
const res = await POST(request('POST', '', body));
expect(res.status).toBe(200);
const { jobId, state } = await res.json();
expect(jobId).toMatch(/^[0-9a-f]{32}$/);
expect(state).toBe('queued');
expect(m.dispatcher.submitJob).toHaveBeenCalledWith({
id: jobId,
userId: 'user-1',
plan: 'pro',
lang: 'en-US',
segments: body.segments,
engines: ['kokoro', 'omnivoice'],
quotaLeft: 300 * 1024 - 1_000,
});
// The same window gets the same id.
const again = await POST(request('POST', '', body));
expect((await again.json()).jobId).toBe(jobId);
});
it('keeps only the validated segment fields', async () => {
const padded = { ...seg('s0'), notes: 'x'.repeat(100_000) };
await POST(request('POST', '', { ...download(), segments: [padded] }));
expect(m.dispatcher.submitJob).toHaveBeenCalledWith(
expect.objectContaining({ segments: [seg('s0')] }),
);
});
it('refuses listen windows and plan-locked voices', async () => {
let res = await POST(request('POST', '', { ...download(seg('s0')), lane: 'listen' }));
expect(res.status).toBe(400);
m.getSubscriptionPlan.mockReturnValue('plus');
res = await POST(request('POST', '', download(seg('s0', 'Hi.', 'omnivoice:clara'))));
expect(res.status).toBe(403);
expect(m.dispatcher.submitJob).not.toHaveBeenCalled();
});
it('passes on BUSY with a retry hint and a spent quota', async () => {
m.dispatcher.submitJob.mockResolvedValueOnce({ ok: false, error: 'BUSY' });
let res = await POST(request('POST', '', download(seg('s0'))));
expect(res.status).toBe(429);
expect(res.headers.get('Retry-After')).toBe('5');
expect(await res.json()).toEqual({ error: 'BUSY' });
m.dispatcher.submitJob.mockResolvedValueOnce({ ok: false, error: 'DAILY_QUOTA_EXCEEDED' });
res = await POST(request('POST', '', download(seg('s0'))));
expect(await res.json()).toEqual({ error: 'DAILY_QUOTA_EXCEEDED' });
});
it('says jobs are unavailable off Workers or when the dispatcher fails', async () => {
m.bound = false;
let res = await POST(request('POST', '', download(seg('s0'))));
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'JOBS_UNAVAILABLE' });
m.bound = true;
m.dispatcher.submitJob.mockRejectedValueOnce(new Error('reset'));
res = await POST(request('POST', '', download(seg('s0'))));
expect(await res.json()).toEqual({ error: 'JOBS_UNAVAILABLE' });
});
});
describe('GET /jobs/:id', () => {
it('answers 202 while the job runs', async () => {
m.dispatcher.waitJob.mockResolvedValueOnce('leased');
const res = await GET(request('GET', `/${JOB_ID}`), params());
expect(res.status).toBe(202);
expect(await res.json()).toEqual({ state: 'leased' });
expect(m.dispatcher.waitJob).toHaveBeenCalledWith(JOB_ID, 'user-1', expect.any(Number));
});
it('hands over the result once, then drops it', async () => {
m.dispatcher.waitJob.mockResolvedValueOnce('done');
const result = '{"id":"s0","audio":"AAA","boundaries":[]}\n{"done":true,"charged":12}\n';
m.bucket.get.mockResolvedValueOnce({ text: () => Promise.resolve(result) });
const res = await GET(request('GET', `/${JOB_ID}`), params());
expect(res.status).toBe(200);
expect(res.headers.get('Content-Type')).toBe('application/x-ndjson');
expect(await res.text()).toBe(result);
expect(m.bucket.get).toHaveBeenCalledWith(`tts-jobs/${JOB_ID}`);
expect(m.bucket.delete).toHaveBeenCalledWith(`tts-jobs/${JOB_ID}`);
expect(m.dispatcher.forgetJob).toHaveBeenCalledWith(JOB_ID, 'user-1');
});
it.each([
[null, 404, 'NOT_FOUND'],
['failed', 502, 'UPSTREAM_FAILED'],
['cancelled', 409, 'CANCELLED'],
])('maps a %s job to %i', async (state, status, error) => {
m.dispatcher.waitJob.mockResolvedValueOnce(state);
const res = await GET(request('GET', `/${JOB_ID}`), params());
expect(res.status).toBe(status);
expect(await res.json()).toEqual({ error });
});
it('treats a done job whose result is gone as not found', async () => {
m.dispatcher.waitJob.mockResolvedValueOnce('done');
m.bucket.get.mockResolvedValueOnce(null);
const res = await GET(request('GET', `/${JOB_ID}`), params());
expect(res.status).toBe(404);
expect(m.dispatcher.forgetJob).toHaveBeenCalledWith(JOB_ID, 'user-1');
});
it('400s on a malformed id', async () => {
const res = await GET(request('GET', '/nope'), params('nope'));
expect(res.status).toBe(400);
expect(m.dispatcher.waitJob).not.toHaveBeenCalled();
});
});
describe('DELETE /jobs/:id', () => {
it('cancels the job and drops anything it left', async () => {
m.dispatcher.cancelJob.mockResolvedValueOnce(true);
const res = await DELETE(request('DELETE', `/${JOB_ID}`), params());
expect(res.status).toBe(204);
expect(m.dispatcher.cancelJob).toHaveBeenCalledWith(JOB_ID, 'user-1');
expect(m.dispatcher.forgetJob).toHaveBeenCalledWith(JOB_ID, 'user-1');
expect(m.bucket.delete).toHaveBeenCalledWith(`tts-jobs/${JOB_ID}`);
});
});

View file

@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextRequest } from 'next/server';
const m = vi.hoisted(() => ({
validateUserAndToken: vi.fn(),
getSubscriptionPlan: vi.fn(),
getCatalog: vi.fn(),
getRunPodConfig: vi.fn(),
warmup: vi.fn(),
}));
vi.mock('@/utils/access', async (orig) => ({
...(await orig<typeof import('@/utils/access')>()),
validateUserAndToken: m.validateUserAndToken,
getSubscriptionPlan: m.getSubscriptionPlan,
}));
vi.mock('@/libs/readestVoice/catalog', async (orig) => ({
...(await orig<typeof import('@/libs/readestVoice/catalog')>()),
getCatalog: m.getCatalog,
}));
vi.mock('@/libs/readestVoice/runpod', () => ({
getRunPodConfig: m.getRunPodConfig,
warmup: m.warmup,
}));
import { GET, POST } from '@/app/api/tts/readest/route';
const CATALOG = [
{ id: 'kokoro:af_heart', engine: 'kokoro', name: 'Heart', langs: ['en-US'] },
{ id: 'qwen3:serena', engine: 'qwen3', name: 'Serena', langs: ['en-US', 'de-DE'] },
{ id: 'omnivoice:clara', engine: 'omnivoice', name: 'Clara', langs: ['en-US'] },
];
const CFG = { apiKey: 'k', endpointId: 'ep', base: 'https://rp.test/v2' };
const req = (method: 'GET' | 'POST', body?: unknown) =>
new NextRequest('https://web.readest.com/api/tts/readest', {
method,
headers: { authorization: 'Bearer tok', 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
beforeEach(() => {
for (const fn of Object.values(m)) fn.mockReset();
m.validateUserAndToken.mockResolvedValue({ user: { id: 'user-1' }, token: 'tok' });
m.getSubscriptionPlan.mockReturnValue('pro');
m.getCatalog.mockResolvedValue(CATALOG);
m.getRunPodConfig.mockReturnValue(CFG);
m.warmup.mockResolvedValue(undefined);
});
afterEach(() => vi.restoreAllMocks());
describe('GET /api/tts/readest', () => {
it('403s when unauthenticated', async () => {
m.validateUserAndToken.mockResolvedValue({});
const res = await GET(req('GET'));
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: 'NOT_AUTHENTICATED' });
});
it('503s when RunPod or the catalog is missing', async () => {
m.getRunPodConfig.mockReturnValueOnce(null);
expect((await GET(req('GET'))).status).toBe(503);
m.getCatalog.mockResolvedValueOnce(null);
expect((await GET(req('GET'))).status).toBe(503);
});
it.each(['free', 'purchase'])('403s PLAN_REQUIRED for %s', async (plan) => {
m.getSubscriptionPlan.mockReturnValue(plan);
expect(await (await GET(req('GET'))).json()).toEqual({ error: 'PLAN_REQUIRED' });
});
it('lists Kokoro for Plus, Kokoro and OmniVoice for Pro', async () => {
m.getSubscriptionPlan.mockReturnValue('plus');
expect(await (await GET(req('GET'))).json()).toEqual({
voices: [{ id: 'kokoro:af_heart', name: 'Heart', lang: 'en-US', tier: 'plus' }],
});
m.getSubscriptionPlan.mockReturnValue('pro');
expect(await (await GET(req('GET'))).json()).toEqual({
voices: [
{ id: 'kokoro:af_heart', name: 'Heart', lang: 'en-US', tier: 'plus' },
{ id: 'omnivoice:clara', name: 'Clara', lang: 'en-US', tier: 'pro' },
],
});
});
});
describe('POST /api/tts/readest', () => {
it('fires a RunPod warmup', async () => {
const res = await POST(req('POST', { warmup: true }));
expect(await res.json()).toEqual({ ok: true });
expect(m.warmup).toHaveBeenCalledWith(CFG);
});
it('is gated like GET', async () => {
m.getSubscriptionPlan.mockReturnValue('free');
expect((await POST(req('POST', { warmup: true }))).status).toBe(403);
expect(m.warmup).not.toHaveBeenCalled();
});
it('400s on anything but a warmup', async () => {
const res = await POST(req('POST', { input: 'Hello' }));
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'INVALID_INPUT' });
});
});

View file

@ -0,0 +1,378 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextRequest } from 'next/server';
import type { StreamEvent } from '@/libs/readestVoice/runpod';
import { readNDJSON } from '@/utils/ndjson';
const m = vi.hoisted(() => ({
validateUserAndToken: vi.fn(),
getSubscriptionPlan: vi.fn(),
getCatalog: vi.fn(),
getRunPodConfig: vi.fn(),
startJob: vi.fn(),
streamJob: vi.fn(),
cancelJob: vi.fn(),
acquireSlot: vi.fn(),
setSlotJob: vi.fn(),
releaseSlot: vi.fn(),
getCurrentUsage: vi.fn(),
trackUsage: vi.fn(),
}));
vi.mock('@/utils/access', async (orig) => ({
...(await orig<typeof import('@/utils/access')>()),
validateUserAndToken: m.validateUserAndToken,
getSubscriptionPlan: m.getSubscriptionPlan,
}));
vi.mock('@/libs/readestVoice/catalog', async (orig) => ({
...(await orig<typeof import('@/libs/readestVoice/catalog')>()),
getCatalog: m.getCatalog,
}));
vi.mock('@/libs/readestVoice/runpod', () => ({
getRunPodConfig: m.getRunPodConfig,
startJob: m.startJob,
streamJob: m.streamJob,
cancelJob: m.cancelJob,
}));
vi.mock('@/libs/readestVoice/admission', async (orig) => ({
...(await orig<typeof import('@/libs/readestVoice/admission')>()),
acquireSlot: m.acquireSlot,
setSlotJob: m.setSlotJob,
releaseSlot: m.releaseSlot,
}));
vi.mock('@/utils/usage', async (orig) => {
const actual = await orig<typeof import('@/utils/usage')>();
return {
...actual,
UsageStatsManager: { getCurrentUsage: m.getCurrentUsage, trackUsage: m.trackUsage },
};
});
import { POST } from '@/app/api/tts/readest/stream/route';
const CATALOG = [
{ id: 'kokoro:af_heart', engine: 'kokoro', name: 'Heart', langs: ['en-US'] },
{ id: 'qwen3:ryan', engine: 'qwen3', name: 'Ryan', langs: ['en-US'] },
{ id: 'omnivoice:clara', engine: 'omnivoice', name: 'Clara', langs: ['en-US'] },
];
const CFG = { apiKey: 'k', endpointId: 'ep', base: 'https://rp.test/v2' };
const B = [{ offset: 0, duration: 5_000_000, text: 'Hello' }];
const seg = (id: string, text = 'Hello world.', voice = 'kokoro:af_heart') => ({ id, text, voice });
const post = (body: unknown, signal?: AbortSignal) =>
new NextRequest('https://web.readest.com/api/tts/readest/stream', {
method: 'POST',
headers: { authorization: 'Bearer tok', 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
});
const listen = (...segments: ReturnType<typeof seg>[]) => ({
lane: 'listen',
lang: 'en-US',
segments,
});
const lines = async (res: Response) => {
const out: Record<string, unknown>[] = [];
for await (const line of readNDJSON(res.body!)) out.push(line as Record<string, unknown>);
return out;
};
// streamJob stand-in: yields the given events, then (if `hang`) waits for the
// abort signal like a long-poll that never gets more frames.
const fakeStream = (events: StreamEvent[], hang = false) =>
async function* (_cfg: unknown, _job: string, signal: AbortSignal) {
for (const e of events) yield e;
if (hang) {
await new Promise((_, reject) =>
signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true }),
);
}
};
const flush = () => new Promise((r) => setTimeout(r, 0));
beforeEach(() => {
for (const fn of Object.values(m)) fn.mockReset();
m.validateUserAndToken.mockResolvedValue({ user: { id: 'user-1' }, token: 'tok' });
m.getSubscriptionPlan.mockReturnValue('plus');
m.getCatalog.mockResolvedValue(CATALOG);
m.getRunPodConfig.mockReturnValue(CFG);
m.startJob.mockResolvedValue('job-1');
m.streamJob.mockImplementation(
fakeStream([{ output: { id: 's0', audio: 'AAA', boundaries: B } }, { status: 'COMPLETED' }]),
);
m.cancelJob.mockResolvedValue(undefined);
m.acquireSlot.mockResolvedValue({ acquired: true, previousJobId: null });
m.setSlotJob.mockResolvedValue(true);
m.releaseSlot.mockResolvedValue(undefined);
m.getCurrentUsage.mockResolvedValue(0);
m.trackUsage.mockResolvedValue(0);
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => vi.restoreAllMocks());
describe('gating', () => {
it('403s when unauthenticated', async () => {
m.validateUserAndToken.mockResolvedValue({});
const res = await POST(post(listen(seg('s0'))));
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: 'NOT_AUTHENTICATED' });
});
it('503s when RunPod is unconfigured (kill switch) or the catalog is down', async () => {
m.getRunPodConfig.mockReturnValueOnce(null);
expect((await POST(post(listen(seg('s0'))))).status).toBe(503);
m.getCatalog.mockResolvedValueOnce(null);
const res = await POST(post(listen(seg('s0'))));
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'NOT_CONFIGURED' });
});
it.each(['free', 'purchase'])('403s PLAN_REQUIRED for %s', async (plan) => {
m.getSubscriptionPlan.mockReturnValue(plan);
const res = await POST(post(listen(seg('s0'))));
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: 'PLAN_REQUIRED' });
});
it('rejects a Pro voice for Plus and an unknown voice', async () => {
let res = await POST(post(listen(seg('s0', 'Hi.', 'omnivoice:clara'))));
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: 'VOICE_TIER_REQUIRED' });
res = await POST(post(listen(seg('s0', 'Hi.', 'kokoro:nope'))));
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'UNKNOWN_VOICE' });
expect(m.startJob).not.toHaveBeenCalled();
});
it('rejects Qwen3 voices for Pro too', async () => {
m.getSubscriptionPlan.mockReturnValue('pro');
const res = await POST(post(listen(seg('s0', 'Hi.', 'qwen3:ryan'))));
expect(res.status).toBe(403);
expect(await res.json()).toEqual({ error: 'VOICE_TIER_REQUIRED' });
expect(m.startJob).not.toHaveBeenCalled();
});
});
describe('window validation', () => {
it.each([
['9 listen segments', listen(...Array.from({ length: 9 }, (_, i) => seg(`s${i}`)))],
['2,001-char segment', listen(seg('s0', 'a'.repeat(2001)))],
['listen over 2,000 chars', listen(seg('s0', 'a'.repeat(1500)), seg('s1', 'a'.repeat(600)))],
['duplicate ids', listen(seg('s0'), seg('s0'))],
['empty text', listen(seg('s0', ' '))],
['no segments', listen()],
['bad lane', { lane: 'bulk', lang: 'en', segments: [seg('s0')] }],
])('400s on %s', async (_name, body) => {
const res = await POST(post(body));
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: 'INVALID_INPUT' });
});
it('accepts 64 download segments', async () => {
const body = {
lane: 'download',
lang: 'en-US',
segments: Array.from({ length: 64 }, (_, i) => seg(`s${i}`, 'Hi.')),
};
expect((await POST(post(body))).status).toBe(200);
});
});
describe('quota and admission', () => {
it('429s when the window would exceed the daily quota, before starting a job', async () => {
m.getCurrentUsage.mockResolvedValue(100 * 1024 - 100);
const res = await POST(post(listen(seg('s0', 'a'.repeat(200)))));
expect(res.status).toBe(429);
expect(await res.json()).toEqual({ error: 'DAILY_QUOTA_EXCEEDED' });
expect(m.startJob).not.toHaveBeenCalled();
// The slot was taken alongside the quota check: give it back.
expect(m.releaseSlot).toHaveBeenCalledWith(expect.any(String));
});
it('checks the quota and takes the slot at the same time', async () => {
let resolveUsage!: (used: number) => void;
m.getCurrentUsage.mockReturnValue(new Promise<number>((r) => (resolveUsage = r)));
const pending = POST(post(listen(seg('s0'))));
await flush();
expect(m.acquireSlot).toHaveBeenCalled();
resolveUsage(0);
await lines(await pending);
});
it('queues as the client the request names, or as one shared client for older apps', async () => {
await lines(await POST(post({ ...listen(seg('s0')), client: 'phone' })));
expect(m.acquireSlot).toHaveBeenLastCalledWith('user-1', 'phone', 'listen', expect.any(String));
await lines(await POST(post(listen(seg('s0')))));
expect(m.acquireSlot).toHaveBeenLastCalledWith(
'user-1',
'default',
'listen',
expect.any(String),
);
const res = await POST(post({ ...listen(seg('s0')), client: 'x'.repeat(65) }));
expect(res.status).toBe(400);
});
it('withdraws a waiting window when the client goes away', async () => {
let admit!: (result: { acquired: boolean; previousJobId: null }) => void;
m.acquireSlot.mockReturnValue(new Promise((r) => (admit = r)));
const controller = new AbortController();
const pending = POST(post(listen(seg('s0')), controller.signal));
await flush();
controller.abort();
const token = m.acquireSlot.mock.calls[0]![3];
expect(m.releaseSlot).toHaveBeenCalledWith(token);
// Admitted in the same moment: the window must not start anyway.
admit({ acquired: true, previousJobId: null });
await pending;
expect(m.startJob).not.toHaveBeenCalled();
expect(m.releaseSlot).toHaveBeenLastCalledWith(token);
});
it('429s BUSY with Retry-After when the window waited too long or was refused', async () => {
m.acquireSlot.mockResolvedValue({ acquired: false, previousJobId: null });
const res = await POST(post({ lane: 'download', lang: 'en', segments: [seg('s0')] }));
expect(res.status).toBe(429);
expect(res.headers.get('Retry-After')).toBe('5');
expect(await res.json()).toEqual({ error: 'BUSY' });
expect(m.startJob).not.toHaveBeenCalled();
});
it('cancels the superseded listen job without waiting on it', async () => {
m.acquireSlot.mockResolvedValue({ acquired: true, previousJobId: 'old-job' });
m.cancelJob.mockReturnValue(new Promise(() => {}));
const res = await POST(post(listen(seg('s0'))));
await lines(res);
expect(m.cancelJob).toHaveBeenCalledWith(CFG, 'old-job');
expect(m.startJob).toHaveBeenCalled();
});
it('streams without waiting for the job id to be recorded on the slot', async () => {
m.setSlotJob.mockReturnValue(new Promise(() => {}));
const res = await POST(post(listen(seg('s0'))));
expect(await lines(res)).toEqual([
{ id: 's0', audio: 'AAA', boundaries: B },
{ done: true, charged: 'Hello world.'.length },
]);
});
it('cancels its own job when it turns out to have lost the slot race', async () => {
m.setSlotJob.mockResolvedValue(false);
m.streamJob.mockImplementation(fakeStream([], true));
const res = await POST(post(listen(seg('s0'))));
expect(await lines(res)).toEqual([{ done: true, charged: 0 }]);
expect(m.cancelJob).toHaveBeenCalledWith(CFG, 'job-1');
});
it('502s and frees the slot when the job cannot start', async () => {
m.startJob.mockRejectedValue(new Error('RunPod run failed: 500'));
const res = await POST(post(listen(seg('s0'))));
expect(res.status).toBe(502);
expect(await res.json()).toEqual({ error: 'UPSTREAM_FAILED' });
expect(m.releaseSlot).toHaveBeenCalled();
});
});
describe('streaming', () => {
it('streams ordered lines and charges delivered segments once', async () => {
m.streamJob.mockImplementation(
fakeStream([
{ output: { id: 's0', audio: 'AAA', boundaries: B } },
{ output: { id: 's1', failed: true } },
{ output: { id: 's2', audio: 'BBB', boundaries: B } },
{ status: 'COMPLETED' },
]),
);
const res = await POST(
post(listen(seg('s0', 'Hello.'), seg('s1', 'Bad one.'), seg('s2', 'Third!!'))),
);
expect(res.status).toBe(200);
expect(res.headers.get('Content-Type')).toBe('application/x-ndjson');
expect(await lines(res)).toEqual([
{ id: 's0', audio: 'AAA', boundaries: B },
{ id: 's1', error: 'synthesis failed' },
{ id: 's2', audio: 'BBB', boundaries: B },
{ done: true, charged: 13 },
]);
expect(m.startJob).toHaveBeenCalledWith(CFG, {
lang: 'en-US',
segments: [seg('s0', 'Hello.'), seg('s1', 'Bad one.'), seg('s2', 'Third!!')],
});
expect(m.trackUsage).toHaveBeenCalledTimes(1);
expect(m.trackUsage).toHaveBeenCalledWith('user-1', 'tts_chars', 13, {
plan: 'plus',
lane: 'listen',
segments: 3,
});
expect(m.releaseSlot).toHaveBeenCalledWith(expect.any(String));
});
it('charges only what was delivered when the job fails mid-window', async () => {
m.streamJob.mockImplementation(
fakeStream([
{ output: { id: 's0', audio: 'AAA', boundaries: B } },
{ status: 'FAILED', error: 'synthesis failed' },
]),
);
const res = await POST(post(listen(seg('s0', 'Hello.'), seg('s1', 'World.'))));
expect(await lines(res)).toEqual([
{ id: 's0', audio: 'AAA', boundaries: B },
{ done: true, charged: 6, error: 'UPSTREAM_FAILED' },
]);
expect(m.trackUsage).toHaveBeenCalledWith('user-1', 'tts_chars', 6, expect.any(Object));
});
it('does not charge a window that delivered nothing', async () => {
m.streamJob.mockImplementation(fakeStream([{ status: 'CANCELLED' }]));
const res = await POST(post(listen(seg('s0'))));
expect(await lines(res)).toEqual([{ done: true, charged: 0, error: 'CANCELLED' }]);
expect(m.trackUsage).not.toHaveBeenCalled();
});
it('ignores frames for ids outside the window', async () => {
m.streamJob.mockImplementation(
fakeStream([{ output: { id: 'zz', audio: 'X', boundaries: [] } }, { status: 'COMPLETED' }]),
);
expect(await lines(await POST(post(listen(seg('s0')))))).toEqual([{ done: true, charged: 0 }]);
});
it('turns a polling error into a terminal line and cancels the job', async () => {
m.streamJob.mockImplementation(async function* () {
yield { output: { id: 's0', audio: 'AAA', boundaries: B } };
throw new Error('RunPod stream failed: 502');
});
const res = await POST(post(listen(seg('s0', 'Hello.'), seg('s1'))));
expect(await lines(res)).toEqual([
{ id: 's0', audio: 'AAA', boundaries: B },
{ done: true, charged: 6, error: 'UPSTREAM_FAILED' },
]);
expect(m.cancelJob).toHaveBeenCalledWith(CFG, 'job-1');
});
it('still closes the stream when charging fails (fail open)', async () => {
m.trackUsage.mockRejectedValue(new Error('db down'));
const res = await POST(post(listen(seg('s0'))));
expect((await lines(res)).at(-1)).toEqual({ done: true, charged: 12 });
});
it('on client disconnect: cancels the job, charges delivered only, frees the slot', async () => {
m.streamJob.mockImplementation(
fakeStream([{ output: { id: 's0', audio: 'AAA', boundaries: B } }], true),
);
const client = new AbortController();
const res = await POST(post(listen(seg('s0', 'Hello.'), seg('s1')), client.signal));
const reader = readNDJSON(res.body!);
expect((await reader.next()).value).toEqual({ id: 's0', audio: 'AAA', boundaries: B });
client.abort();
await reader.return(undefined);
await vi.waitFor(() => expect(m.releaseSlot).toHaveBeenCalled());
await flush();
expect(m.cancelJob).toHaveBeenCalledWith(CFG, 'job-1');
expect(m.trackUsage).toHaveBeenCalledTimes(1);
expect(m.trackUsage).toHaveBeenCalledWith('user-1', 'tts_chars', 6, expect.any(Object));
});
});

View file

@ -0,0 +1,177 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { NextRequest } from 'next/server';
const m = vi.hoisted(() => ({
trackUsage: vi.fn(),
dispatcher: {
leaseJob: vi.fn(),
leasedJob: vi.fn(),
heartbeat: vi.fn(),
completeJob: vi.fn(),
},
bucket: { put: vi.fn(), get: vi.fn(), delete: vi.fn() },
bound: true,
}));
vi.mock('@/libs/readestVoice/bindings', async (orig) => ({
...(await orig<typeof import('@/libs/readestVoice/bindings')>()),
getDispatcher: () => (m.bound ? m.dispatcher : null),
getResultBucket: () => (m.bound ? m.bucket : null),
}));
vi.mock('@/utils/usage', async (orig) => ({
...(await orig<typeof import('@/utils/usage')>()),
UsageStatsManager: { trackUsage: m.trackUsage },
}));
import { POST } from '@/app/api/tts/readest/workers/route';
const JOB = {
jobId: 'a'.repeat(32),
lease: 'lease-1',
lang: 'en-US',
segments: [
{ id: 's0', text: 'Hello world.', voice: 'kokoro:af_heart' },
{ id: 's1', text: 'Bye.', voice: 'kokoro:af_heart' },
],
};
const B = [{ offset: 0, duration: 5_000_000, text: 'Hello' }];
const post = (body: unknown, token?: string) =>
new NextRequest('https://web.readest.com/api/tts/readest/workers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(token ? { authorization: `Bearer ${token}` } : {}),
},
body: JSON.stringify(body),
});
beforeEach(() => {
for (const fn of [m.trackUsage, ...Object.values(m.dispatcher), ...Object.values(m.bucket)]) {
fn.mockReset();
}
m.bound = true;
vi.stubEnv('READEST_VOICE_WORKER_TOKENS', 'gpu-box:secret-1,lab:secret-2');
vi.stubEnv('READEST_VOICE_WORKER_VERSION', '2.3.0');
m.bucket.put.mockResolvedValue(undefined);
m.bucket.delete.mockResolvedValue(undefined);
m.trackUsage.mockResolvedValue(0);
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
describe('lease', () => {
const lease = { action: 'lease', engines: ['kokoro', 'omnivoice'], version: '2.3.0' };
it('long-polls the dispatcher under the worker name its token maps to', async () => {
m.dispatcher.leaseJob.mockResolvedValueOnce(JOB);
const res = await POST(post(lease, 'secret-2'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual(JOB);
expect(m.dispatcher.leaseJob).toHaveBeenCalledWith(
'lab',
['kokoro', 'omnivoice'],
expect.any(Number),
);
});
it('answers 204 when no job came', async () => {
m.dispatcher.leaseJob.mockResolvedValueOnce(null);
expect((await POST(post(lease, 'secret-1'))).status).toBe(204);
});
it('refuses unknown tokens and other worker versions', async () => {
let res = await POST(post(lease, 'guess'));
expect(res.status).toBe(401);
res = await POST(post(lease));
expect(res.status).toBe(401);
res = await POST(post({ ...lease, version: '2.2.0' }, 'secret-1'));
expect(res.status).toBe(409);
expect(await res.json()).toEqual({ error: 'VERSION_MISMATCH' });
expect(m.dispatcher.leaseJob).not.toHaveBeenCalled();
});
it('refuses every worker when no tokens are configured', async () => {
vi.stubEnv('READEST_VOICE_WORKER_TOKENS', '');
expect((await POST(post(lease, ''))).status).toBe(401);
});
it('400s on malformed engines', async () => {
const res = await POST(post({ ...lease, engines: 'kokoro' }, 'secret-1'));
expect(res.status).toBe(400);
});
});
describe('lease holders', () => {
it('fetch their window by lease alone (a bridged RunPod job)', async () => {
m.dispatcher.leasedJob.mockResolvedValueOnce(JOB).mockResolvedValueOnce(null);
let res = await POST(post({ action: 'job', lease: 'lease-1' }));
expect(await res.json()).toEqual(JOB);
res = await POST(post({ action: 'job', lease: 'lease-1' }));
expect(res.status).toBe(410);
});
it('renew the lease and learn when to stop', async () => {
m.dispatcher.heartbeat.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
expect(await (await POST(post({ action: 'heartbeat', lease: 'lease-1' }))).json()).toEqual({
live: true,
});
expect(await (await POST(post({ action: 'heartbeat', lease: 'lease-1' }))).json()).toEqual({
live: false,
});
});
});
describe('complete', () => {
const frames = [
{ id: 's0', audio: 'AAA', boundaries: B },
{ id: 's1', failed: true },
];
it('stores the result as the app reads it and charges what was delivered', async () => {
m.dispatcher.leasedJob.mockResolvedValueOnce(JOB);
m.dispatcher.completeJob.mockResolvedValueOnce({ userId: 'user-1', plan: 'pro' });
const res = await POST(post({ action: 'complete', lease: 'lease-1', frames }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ charged: 12 });
expect(m.bucket.put).toHaveBeenCalledWith(
`tts-jobs/${JOB.jobId}`,
[
JSON.stringify({ id: 's0', audio: 'AAA', boundaries: B }),
JSON.stringify({ id: 's1', error: 'synthesis failed' }),
JSON.stringify({ done: true, charged: 12 }),
'',
].join('\n'),
);
expect(m.trackUsage).toHaveBeenCalledWith('user-1', 'tts_chars', 12, {
plan: 'pro',
lane: 'download',
segments: 2,
});
});
it('drops the result of a lease that is no longer live', async () => {
m.dispatcher.leasedJob.mockResolvedValueOnce(null);
let res = await POST(post({ action: 'complete', lease: 'lease-1', frames }));
expect(res.status).toBe(410);
expect(m.bucket.put).not.toHaveBeenCalled();
// Cancelled while the result uploaded.
m.dispatcher.leasedJob.mockResolvedValueOnce(JOB);
m.dispatcher.completeJob.mockResolvedValueOnce(null);
res = await POST(post({ action: 'complete', lease: 'lease-1', frames }));
expect(res.status).toBe(410);
expect(m.bucket.delete).toHaveBeenCalledWith(`tts-jobs/${JOB.jobId}`);
expect(m.trackUsage).not.toHaveBeenCalled();
});
});
it('503s off Workers and 400s on unknown actions', async () => {
expect((await POST(post({ action: 'dance' }))).status).toBe(400);
m.bound = false;
expect((await POST(post({ action: 'job', lease: 'x' }))).status).toBe(503);
});

View file

@ -564,6 +564,26 @@ describe('TTSPlayerSheet', () => {
expect(viewSettings['ttsUseNarration']).toBeUndefined();
});
test('premium voices show the plan that unlocks them', async () => {
const groups = [
{
id: 'readest',
name: 'Readest Voice',
voices: [
{ id: 'kokoro:zf_001', name: 'Zifang', lang: 'zh-CN', tier: 'plus' as const },
{ id: 'omnivoice:xiaoyu', name: 'Xiaoyu', lang: 'zh-CN', tier: 'pro' as const },
],
},
...voiceGroups,
];
render(<TTSPlayerSheet {...makeProps({ onGetVoices: vi.fn().mockResolvedValue(groups) })} />);
fireEvent.click(screen.getByLabelText('Voice'));
const row = (name: string) => screen.getByText(name).closest('button')!;
expect((await waitFor(() => row('Xiaoyu'))).textContent).toBe('XiaoyuPro');
expect(row('Zifang').textContent).toBe('ZifangPlus');
expect(row('Guy').textContent).toBe('Guy');
});
test('reopening the sheet returns to the main view', async () => {
const props = makeProps();
const { rerender } = render(<TTSPlayerSheet {...props} />);

View file

@ -42,6 +42,30 @@ describe('useMiniPlayerAutoHide', () => {
expect(result.current).toBe(false);
});
it('keeps the full player up while buffering, then hides 5s after audio starts', () => {
// A cold GPU worker can take far longer than 5s for the first sentence: the
// spinning play button must stay in sight until something is heard.
let buffering = true;
const { result, rerender } = renderHook(() =>
useMiniPlayerAutoHide(BOOK, 'full', true, buffering),
);
act(() => {
vi.advanceTimersByTime(30_000);
});
expect(result.current).toBe(true);
buffering = false;
rerender();
act(() => {
vi.advanceTimersByTime(4999);
});
expect(result.current).toBe(true);
act(() => {
vi.advanceTimersByTime(1);
});
expect(result.current).toBe(false);
});
it('keeps the full player up for as long as the toolbar is shown', () => {
setHovered(BOOK);
const { result } = renderHook(() => useMiniPlayerAutoHide(BOOK, 'full', true));

View file

@ -0,0 +1,78 @@
import { describe, expect, test } from 'vitest';
import { textWalker } from 'foliate-js/text-walker.js';
// A chapter's paragraphs usually share one ancestor (the body or a wrapper),
// so a paragraph's range has that ancestor as its commonAncestorContainer.
// Walking it must start at the paragraph, not at the chapter's first node:
// otherwise reading paragraph N costs N paragraphs of DOM work (and node
// filter calls), and a long chapter stalls the main thread for seconds.
const makeChapter = (paragraphs: number): Document =>
new DOMParser().parseFromString(
`<!DOCTYPE html><html><body><div>${Array.from(
{ length: paragraphs },
(_, i) => `<p>Paragraph ${i} has <em>some</em> text.</p>`,
).join('')}</div></body></html>`,
'text/html',
);
const paragraphRange = (doc: Document, index: number): Range => {
const ps = doc.querySelectorAll('p');
const range = doc.createRange();
range.setStart(ps[index]!, 0);
range.setEndBefore(ps[index + 1]!);
return range;
};
const collect = (range: Range, filter: (node: Node) => number) => {
const texts: string[] = [];
for (const text of textWalker(range, (strs: string[]) => [strs.join('')], filter)) {
texts.push(text as string);
}
return texts;
};
describe('textWalker on a paragraph of a long chapter', () => {
test('collects only the paragraph text', () => {
const doc = makeChapter(50);
const accept = (node: Node) =>
node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
expect(collect(paragraphRange(doc, 40), accept)).toEqual(['Paragraph 40 has some text.']);
expect(collect(paragraphRange(doc, 0), accept)).toEqual(['Paragraph 0 has some text.']);
});
test('never visits nodes before the paragraph', () => {
const doc = makeChapter(500);
let visited = 0;
const counting = (node: Node) => {
visited++;
return node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
};
expect(collect(paragraphRange(doc, 400), counting)).toEqual(['Paragraph 400 has some text.']);
// The paragraph's own nodes plus the first node past it, not 400 paragraphs.
expect(visited).toBeLessThan(20);
});
test('respects a filter that rejects part of the paragraph', () => {
const doc = makeChapter(10);
const noEm = (node: Node) => {
if (node.nodeType === Node.ELEMENT_NODE && (node as Element).tagName === 'EM')
return NodeFilter.FILTER_REJECT;
return node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
};
expect(collect(paragraphRange(doc, 5), noEm)).toEqual(['Paragraph 5 has text.']);
});
test('a range starting inside a rejected element stays rejected', () => {
const doc = makeChapter(3);
const em = doc.querySelectorAll('em')[1]!;
const range = doc.createRange();
range.setStart(em.firstChild!, 0);
range.setEndBefore(doc.querySelectorAll('p')[2]!);
const noEm = (node: Node) => {
if (node.nodeType === Node.ELEMENT_NODE && (node as Element).tagName === 'EM')
return NodeFilter.FILTER_REJECT;
return node.nodeType === Node.TEXT_NODE ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
};
expect(collect(range, noEm)).toEqual([' text.']);
});
});

View file

@ -1261,3 +1261,45 @@ describe('useTTSControl gap control (handleSetSentenceGap / handleSupportsGapCon
expect(controller.setParagraphGap).toHaveBeenCalledWith(0.24);
});
});
describe('useTTSControl quota toast', () => {
beforeEach(() => {
ttsControllerInstances.length = 0;
pendingInitResolvers.length = 0;
mockSessionManager.claim.mockClear();
mockSessionManager.getSessionByHash.mockReturnValue(null);
mockSessionManager.getActiveSession.mockReturnValue(null);
});
afterEach(() => {
cleanup();
});
const startSession = async () => {
render(<Harness />);
await act(async () => {
const p = eventDispatcher.dispatch('tts-speak', { bookKey: 'book-1' });
for (let i = 0; i < 10; i++) await Promise.resolve();
while (pendingInitResolvers.length > 0) pendingInitResolvers.shift()!();
await p;
});
await act(async () => {
for (let i = 0; i < 5; i++) await Promise.resolve();
});
};
it('shows a toast when the premium TTS quota is exceeded', async () => {
await startSession();
const controller = ttsControllerInstances[0] as {
addEventListener: ReturnType<typeof vi.fn>;
};
const call = controller.addEventListener.mock.calls.find(
(args: unknown[]) => args[0] === 'tts-quota-exceeded',
);
expect(call).toBeDefined();
const dispatchSpy = vi.spyOn(eventDispatcher, 'dispatch');
(call![1] as () => void)();
expect(dispatchSpy).toHaveBeenCalledWith('toast', expect.objectContaining({ type: 'error' }));
dispatchSpy.mockRestore();
});
});

View file

@ -0,0 +1,72 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const stub = { acquire: vi.fn(), setJob: vi.fn(), release: vi.fn() };
const namespace = { idFromName: vi.fn(() => 'global-id'), get: vi.fn(() => stub) };
let env: Record<string, unknown> = {};
vi.mock('@opennextjs/cloudflare', () => ({
getCloudflareContext: () => ({ env }),
}));
import { acquireSlot, releaseSlot, setSlotJob } from '@/libs/readestVoice/admission';
const ADMITTED = { acquired: true, previousJobId: null };
beforeEach(() => {
vi.clearAllMocks();
env = { TTS_DISPATCHER: namespace };
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
describe('acquireSlot', () => {
it('asks the global dispatcher and returns its answer', async () => {
stub.acquire.mockResolvedValueOnce({ acquired: true, previousJobId: 'old-job' });
await expect(acquireSlot('u1', 'phone', 'listen', 'tok')).resolves.toEqual({
acquired: true,
previousJobId: 'old-job',
});
expect(namespace.idFromName).toHaveBeenCalledWith('global');
expect(stub.acquire).toHaveBeenCalledWith({
userId: 'u1',
clientId: 'phone',
lane: 'listen',
token: 'tok',
});
});
it('reports a refused window', async () => {
stub.acquire.mockResolvedValueOnce({ acquired: false, previousJobId: null });
await expect(acquireSlot('u1', 'phone', 'download', 'tok')).resolves.toEqual({
acquired: false,
previousJobId: null,
});
});
it('admits when the dispatcher fails or is not bound', async () => {
stub.acquire.mockRejectedValueOnce(new Error('reset'));
await expect(acquireSlot('u1', 'phone', 'listen', 'tok')).resolves.toEqual(ADMITTED);
env = {};
await expect(acquireSlot('u1', 'phone', 'listen', 'tok')).resolves.toEqual(ADMITTED);
});
});
describe('setSlotJob', () => {
it('records the job, false when the slot is gone', async () => {
stub.setJob.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
await expect(setSlotJob('tok', 'job-1')).resolves.toBe(true);
await expect(setSlotJob('tok', 'job-1')).resolves.toBe(false);
expect(stub.setJob).toHaveBeenCalledWith('tok', 'job-1');
});
it('keeps the job when the dispatcher fails', async () => {
stub.setJob.mockRejectedValueOnce(new Error('reset'));
await expect(setSlotJob('tok', 'job-1')).resolves.toBe(true);
});
});
describe('releaseSlot', () => {
it('releases by token and swallows failures', async () => {
stub.release.mockRejectedValueOnce(new Error('reset'));
await expect(releaseSlot('tok')).resolves.toBeUndefined();
expect(stub.release).toHaveBeenCalledWith('tok');
});
});

View file

@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CatalogVoice } from '@/libs/readestVoice/catalog';
const CATALOG: CatalogVoice[] = [
{ id: 'kokoro:af_heart', engine: 'kokoro', name: 'Heart', langs: ['en-US'] },
{ id: 'qwen3:serena', engine: 'qwen3', name: 'Serena', langs: ['en-US', 'de-DE'] },
{ id: 'future:x', engine: 'future', name: 'X', langs: ['en-US'] },
{ id: 'omnivoice:clara', engine: 'omnivoice', name: 'Clara', langs: ['en-US'] },
];
const fetchMock = vi.fn();
// Fresh module per test: the catalog cache is module state.
const load = async () => {
vi.resetModules();
return import('@/libs/readestVoice/catalog');
};
beforeEach(() => {
vi.stubGlobal('fetch', fetchMock);
vi.stubEnv('READEST_TTS_CATALOG_URL', 'https://example.test/catalog.json');
fetchMock
.mockReset()
.mockImplementation(async () => Response.json({ version: 1, voices: CATALOG }));
});
afterEach(() => {
vi.unstubAllEnvs();
vi.useRealTimers();
});
describe('getCatalog', () => {
it('fetches the catalog once per TTL', async () => {
vi.useFakeTimers();
const { getCatalog } = await load();
expect(await getCatalog()).toEqual(CATALOG);
expect(await getCatalog()).toEqual(CATALOG);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith('https://example.test/catalog.json');
vi.advanceTimersByTime(10 * 60 * 1000 + 1);
await getCatalog();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('returns null when unconfigured or unreachable', async () => {
let { getCatalog } = await load();
vi.stubEnv('READEST_TTS_CATALOG_URL', '');
expect(await getCatalog()).toBeNull();
vi.stubEnv('READEST_TTS_CATALOG_URL', 'https://example.test/catalog.json');
({ getCatalog } = await load());
fetchMock.mockRejectedValueOnce(new Error('offline'));
expect(await getCatalog()).toBeNull();
fetchMock.mockResolvedValueOnce(new Response('nope', { status: 500 }));
expect(await getCatalog()).toBeNull();
});
it('keeps serving the last good catalog when a refresh fails', async () => {
vi.useFakeTimers();
const { getCatalog } = await load();
await getCatalog();
vi.advanceTimersByTime(10 * 60 * 1000 + 1);
fetchMock.mockRejectedValueOnce(new Error('offline'));
expect(await getCatalog()).toEqual(CATALOG);
});
it('drops malformed rows', async () => {
fetchMock.mockResolvedValueOnce(
Response.json({ voices: [CATALOG[0], { id: 'bad' }, null, { ...CATALOG[1], langs: 'en' }] }),
);
const { getCatalog } = await load();
expect(await getCatalog()).toEqual([CATALOG[0]]);
});
});
describe('plan filtering', () => {
it('gives Plus Kokoro, Pro Kokoro and OmniVoice, others nothing', async () => {
// Qwen3 voices are blocked for every plan, even though the catalog lists them.
const { voicesForPlan } = await load();
expect(voicesForPlan(CATALOG, 'plus')).toEqual([
{ id: 'kokoro:af_heart', name: 'Heart', lang: 'en-US', tier: 'plus' },
]);
expect(voicesForPlan(CATALOG, 'pro')).toEqual([
{ id: 'kokoro:af_heart', name: 'Heart', lang: 'en-US', tier: 'plus' },
{ id: 'omnivoice:clara', name: 'Clara', lang: 'en-US', tier: 'pro' },
]);
expect(voicesForPlan(CATALOG, 'free')).toEqual([]);
expect(voicesForPlan(CATALOG, 'purchase')).toEqual([]);
});
it('hides engines without a configured minimum plan (fail closed)', async () => {
const { isVoiceInPlan } = await load();
expect(isVoiceInPlan(CATALOG[2]!, 'pro')).toBe(false);
});
it('finds voices by id', async () => {
const { findVoice } = await load();
expect(findVoice(CATALOG, 'qwen3:serena')?.name).toBe('Serena');
expect(findVoice(CATALOG, 'kokoro:nope')).toBeUndefined();
});
});

View file

@ -0,0 +1,217 @@
import { describe, expect, it } from 'vitest';
import { DispatchQueue, type SlotRequest } from '@/libs/readestVoice/dispatchQueue';
const LEASE_MS = 180_000;
const WAIT_MS = 60_000;
// Unique across queues, as request tokens are.
let n = 0;
const setup = (capacity: number) => {
let now = 1_000;
const queue = new DispatchQueue(
{ capacity, leaseMs: LEASE_MS, waitMs: WAIT_MS, maxWaiting: 2 },
() => now,
);
const ask = (userId: string, lane: SlotRequest['lane'] = 'listen', clientId = `${userId}-c`) => {
const token = `t${++n}`;
let result: Awaited<ReturnType<DispatchQueue['acquire']>> | undefined;
void queue.acquire({ userId, clientId, lane, token }).then((r) => (result = r));
return { token, result: () => result };
};
const advance = (ms: number) => {
now += ms;
queue.sweep();
};
return { queue, ask, advance };
};
// Promise callbacks run as microtasks.
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('DispatchQueue', () => {
it('admits up to capacity, then queues until a slot frees', async () => {
const { queue, ask } = setup(2);
const a = ask('a');
const b = ask('b');
const c = ask('c');
await flush();
expect(a.result()).toEqual({ acquired: true, previousJobId: null });
expect(b.result()?.acquired).toBe(true);
expect(c.result()).toBeUndefined();
queue.release(a.token);
await flush();
expect(c.result()?.acquired).toBe(true);
});
it('runs one window per user and lane; another device of the user waits its turn', async () => {
const { queue, ask } = setup(4);
const first = ask('a', 'listen', 'phone');
const second = ask('a', 'listen', 'tablet');
const download = ask('a', 'download', 'phone');
await flush();
expect(first.result()?.acquired).toBe(true);
expect(second.result()).toBeUndefined();
expect(download.result()?.acquired).toBe(true);
queue.release(first.token);
await flush();
expect(second.result()?.acquired).toBe(true);
});
it('serves the user served least recently first', async () => {
const { queue, ask } = setup(1);
const a1 = ask('a', 'listen', 'phone');
const a2 = ask('a', 'listen', 'tablet');
const b = ask('b');
await flush();
expect(a1.result()?.acquired).toBe(true);
// a's second device asked before b, but a was just served.
queue.release(a1.token);
await flush();
expect(b.result()?.acquired).toBe(true);
expect(a2.result()).toBeUndefined();
// a's next window arrives only after b was served: a is now due first.
queue.release(b.token);
await flush();
expect(a2.result()?.acquired).toBe(true);
});
it('serves listening first but keeps a share for downloads', async () => {
const { queue, ask } = setup(2);
const a = ask('a');
const b = ask('b');
const listen = ask('c');
const download = ask('d', 'download');
await flush();
// No download running: the reserved slot goes to the waiting download.
queue.release(a.token);
await flush();
expect(download.result()?.acquired).toBe(true);
expect(listen.result()).toBeUndefined();
queue.release(b.token);
await flush();
expect(listen.result()?.acquired).toBe(true);
});
it('lets a client replace its own running listen window without queueing', async () => {
const { queue, ask } = setup(1);
const old = ask('a');
const other = ask('b');
await flush();
queue.setJob(old.token, 'job-1');
// A seek: the same client asks again while the slot is full.
const seek = ask('a');
await flush();
expect(seek.result()).toEqual({ acquired: true, previousJobId: 'job-1' });
expect(queue.setJob(old.token, 'job-x')).toBe(false);
expect(other.result()).toBeUndefined();
// The stale request's late release must not free the new window's slot.
queue.release(old.token);
await flush();
expect(other.result()).toBeUndefined();
});
it('drops a waiting listen window its client replaced', async () => {
const { ask } = setup(1);
ask('b');
const stale = ask('a');
const fresh = ask('a');
await flush();
expect(stale.result()).toEqual({ acquired: false, previousJobId: null });
expect(fresh.result()).toBeUndefined();
});
it('refuses a user who already has the most windows waiting in a lane', async () => {
const { ask } = setup(1);
ask('a', 'download', 'phone');
ask('a', 'download', 'tablet');
ask('a', 'download', 'laptop');
const extra = ask('a', 'download', 'tv');
await flush();
expect(extra.result()?.acquired).toBe(false);
});
it('withdraws a waiting window when its request goes away', async () => {
const { queue, ask } = setup(1);
const a = ask('a');
const b = ask('b');
const c = ask('c');
queue.release(b.token);
await flush();
expect(b.result()?.acquired).toBe(false);
queue.release(a.token);
await flush();
expect(c.result()?.acquired).toBe(true);
});
it('gives up on long waits and frees expired leases', async () => {
const { queue, ask, advance } = setup(1);
const a = ask('a');
const b = ask('b');
await flush();
expect(queue.nextDeadline()).toBe(1_000 + WAIT_MS);
advance(WAIT_MS);
await flush();
expect(b.result()?.acquired).toBe(false);
advance(LEASE_MS - WAIT_MS - 10_000);
const c = ask('c');
advance(10_000);
await flush();
expect(c.result()?.acquired).toBe(true);
expect(queue.setJob(a.token, 'job')).toBe(false);
});
it('keeps restored leases counting against capacity', async () => {
const first = setup(1);
const a = first.ask('a');
await flush();
first.queue.setJob(a.token, 'job-1');
const { queue, ask } = setup(1);
queue.restore(first.queue.snapshot());
const b = ask('b');
await flush();
expect(b.result()).toBeUndefined();
queue.release(a.token);
await flush();
expect(b.result()?.acquired).toBe(true);
});
it('admits a bridged download at once only within its share while listening waits', async () => {
const { queue, ask } = setup(4);
const bridged = (token: string) =>
queue.tryAcquire({ userId: 'bridge', clientId: 'bridge', lane: 'download', token });
expect(bridged('d1')).toBe(true);
ask('a');
ask('b');
ask('a', 'listen', 'tablet');
await flush();
// One slot left, a listen window waits, and downloads have their share.
expect(bridged('d2')).toBe(false);
// Back within the share once the first ends.
queue.release('d1');
expect(bridged('d3')).toBe(true);
});
it('renews a running lease so it outlives the window deadline', async () => {
const { queue, ask, advance } = setup(1);
const a = ask('a');
await flush();
advance(LEASE_MS - 1_000);
expect(queue.renew(a.token)).toBe(true);
advance(2_000);
expect(queue.setJob(a.token, 'job-1')).toBe(true);
expect(queue.renew('missing')).toBe(false);
});
});

View file

@ -0,0 +1,208 @@
import { describe, expect, it } from 'vitest';
import { JobQueue, type JobSubmission } from '@/libs/readestVoice/jobQueue';
const LEASE_MS = 120_000;
const RETAIN_MS = 86_400_000;
const setup = (maxQueuedPerUser = 3) => {
let now = 1_000;
const queue = new JobQueue(
{ leaseMs: LEASE_MS, maxAttempts: 2, maxQueuedPerUser, retainMs: RETAIN_MS },
() => now,
);
let n = 0;
const submit = (userId: string, overrides: Partial<JobSubmission> = {}) => {
const id = overrides.id ?? `job${++n}`;
const result = queue.submit({
id,
userId,
plan: 'pro',
lang: 'en',
segments: [{ id: 's0', text: 'Hello there.', voice: 'kokoro:af_heart' }],
engines: ['kokoro'],
quotaLeft: 1_000,
...overrides,
});
return { id, result };
};
const advance = (ms: number) => {
now += ms;
queue.sweep();
};
return { queue, submit, advance };
};
// Promise callbacks run as microtasks.
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
describe('JobQueue', () => {
it('leases a queued job with its window, then completes it once', () => {
const { queue, submit } = setup();
const { id, result } = submit('a');
expect(result).toEqual({ ok: true, state: 'queued' });
expect(queue.hasQueued()).toBe(true);
const leased = queue.leaseNow('w1', ['kokoro']);
expect(leased).toMatchObject({ jobId: id, lang: 'en' });
expect(queue.hasQueued()).toBe(false);
expect(leased?.segments).toHaveLength(1);
expect(queue.job(leased!.lease)).toEqual(leased);
expect(queue.status(id, 'a')).toBe('leased');
expect(queue.complete(leased!.lease)).toEqual({ userId: 'a', plan: 'pro' });
expect(queue.complete(leased!.lease)).toBeNull();
expect(queue.status(id, 'a')).toBe('done');
expect(queue.job(leased!.lease)).toBeNull();
});
it('returns the existing job when the same window is submitted again', () => {
const { queue, submit } = setup();
submit('a', { id: 'same' });
expect(submit('a', { id: 'same' }).result).toEqual({ ok: true, state: 'queued' });
queue.leaseNow('w1', ['kokoro']);
expect(queue.leaseNow('w1', ['kokoro'])).toBeNull();
});
it('hands each worker only jobs whose engines it runs', () => {
const { queue, submit } = setup();
const { id } = submit('a', { engines: ['omnivoice'] });
expect(queue.leaseNow('w1', ['kokoro'])).toBeNull();
expect(queue.leaseNow('w2', ['kokoro', 'omnivoice'])?.jobId).toBe(id);
});
it('leases to a worker that runs every engine under a lease named up front', () => {
const { queue, submit } = setup();
submit('a', { engines: ['omnivoice'] });
expect(queue.leaseNow('bridge', null, 'named')?.lease).toBe('named');
expect(queue.isLeaseLive('named')).toBe(true);
});
it('serves the user served least recently first, several jobs when alone', () => {
const { queue, submit } = setup();
const a1 = submit('a').id;
const a2 = submit('a').id;
const b1 = submit('b').id;
expect(queue.leaseNow('w1', ['kokoro'])?.jobId).toBe(a1);
// a asked first, but was just served.
expect(queue.leaseNow('w2', ['kokoro'])?.jobId).toBe(b1);
// Nobody else waits: a's next job runs beside its first.
expect(queue.leaseNow('w3', ['kokoro'])?.jobId).toBe(a2);
});
it('refuses a user with too many queued jobs or not enough quota left', () => {
const { submit } = setup(2);
submit('a');
submit('a');
expect(submit('a').result).toEqual({ ok: false, error: 'BUSY' });
// 12 chars per job: an unfinished job plus this one need 24.
expect(submit('b', { quotaLeft: 20 }).result).toEqual({ ok: true, state: 'queued' });
expect(submit('b', { quotaLeft: 20 }).result).toEqual({
ok: false,
error: 'DAILY_QUOTA_EXCEEDED',
});
});
it('wakes a waiting worker when a job arrives, or gives up at the deadline', async () => {
const { queue, submit, advance } = setup();
let got: unknown = 'pending';
void queue.lease('w1', ['kokoro'], 25_000).then((job) => (got = job));
await flush();
expect(got).toBe('pending');
const { id } = submit('a');
await flush();
expect(got).toMatchObject({ jobId: id });
let idle: unknown = 'pending';
void queue.lease('w1', ['kokoro'], 25_000).then((job) => (idle = job));
expect(queue.nextDeadline()).toBe(1_000 + 25_000);
advance(25_000);
await flush();
expect(idle).toBeNull();
});
it('requeues a job whose lease ran out, and fails it after the last attempt', () => {
const { queue, submit, advance } = setup();
const { id } = submit('a');
const first = queue.leaseNow('w1', ['kokoro'])!;
advance(LEASE_MS / 2);
expect(queue.heartbeat(first.lease)).toBe(true);
advance(LEASE_MS - 1);
expect(queue.status(id, 'a')).toBe('leased');
advance(1);
expect(queue.status(id, 'a')).toBe('queued');
expect(queue.heartbeat(first.lease)).toBe(false);
expect(queue.complete(first.lease)).toBeNull();
queue.leaseNow('w2', ['kokoro']);
advance(LEASE_MS);
expect(queue.status(id, 'a')).toBe('failed');
});
it('cancels a job for its owner only and stops its worker', () => {
const { queue, submit } = setup();
const { id } = submit('a');
const leased = queue.leaseNow('w1', ['kokoro'])!;
expect(queue.cancel(id, 'b')).toBe(false);
expect(queue.cancel(id, 'a')).toBe(true);
expect(queue.status(id, 'a')).toBe('cancelled');
expect(queue.heartbeat(leased.lease)).toBe(false);
expect(queue.complete(leased.lease)).toBeNull();
// A cancelled job submitted again runs again.
expect(submit('a', { id }).result).toEqual({ ok: true, state: 'queued' });
});
it('answers a waiting app when its job ends or at the deadline', async () => {
const { queue, submit, advance } = setup();
const { id } = submit('a');
let state: unknown = 'pending';
void queue.wait(id, 'a', 25_000).then((s) => (state = s));
const leased = queue.leaseNow('w1', ['kokoro'])!;
await flush();
expect(state).toBe('pending');
queue.complete(leased.lease);
await flush();
expect(state).toBe('done');
const other = submit('a').id;
let timedOut: unknown = 'pending';
void queue.wait(other, 'a', 25_000).then((s) => (timedOut = s));
advance(25_000);
await flush();
expect(timedOut).toBe('queued');
await expect(queue.wait('missing', 'a', 25_000)).resolves.toBeNull();
});
it('keeps no book text once a job ends and forgets it after the retention', () => {
const { queue, submit, advance } = setup();
const { id } = submit('a');
queue.complete(queue.leaseNow('w1', ['kokoro'])!.lease);
const { put } = queue.takeChanges();
expect(put.find((job) => job.id === id)?.segments).toEqual([]);
advance(RETAIN_MS);
expect(queue.status(id, 'a')).toBeNull();
expect(queue.takeChanges().deleted).toEqual([id]);
});
it('forgets a fetched job for its owner', () => {
const { queue, submit } = setup();
const { id } = submit('a');
queue.forget(id, 'b');
expect(queue.status(id, 'a')).toBe('queued');
queue.forget(id, 'a');
expect(queue.status(id, 'a')).toBeNull();
});
it('restores persisted jobs, leases included', () => {
const first = setup();
const { id } = first.submit('a');
const leased = first.queue.leaseNow('w1', ['kokoro'])!;
const { put } = first.queue.takeChanges();
const { queue } = setup();
queue.restore(put);
expect(queue.status(id, 'a')).toBe('leased');
expect(queue.isLeaseLive(leased.lease)).toBe(true);
expect(queue.complete(leased.lease)).toEqual({ userId: 'a', plan: 'pro' });
});
});

View file

@ -0,0 +1,116 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
cancelJob,
getRunPodConfig,
startJob,
streamJob,
warmup,
type RunPodConfig,
type StreamEvent,
} from '@/libs/readestVoice/runpod';
const fetchMock = vi.fn();
const cfg: RunPodConfig = { apiKey: 'rp-key', endpointId: 'ep1', base: 'https://rp.test/v2' };
const collect = async (gen: AsyncGenerator<StreamEvent>) => {
const out: StreamEvent[] = [];
for await (const e of gen) out.push(e);
return out;
};
beforeEach(() => {
vi.stubGlobal('fetch', fetchMock);
fetchMock.mockReset();
});
afterEach(() => vi.unstubAllEnvs());
describe('getRunPodConfig', () => {
it('is null unless both key and endpoint are set (kill switch)', () => {
vi.stubEnv('RUNPOD_API_KEY', 'k');
vi.stubEnv('RUNPOD_TTS_ENDPOINT_ID', '');
expect(getRunPodConfig()).toBeNull();
vi.stubEnv('RUNPOD_TTS_ENDPOINT_ID', 'ep');
expect(getRunPodConfig()).toEqual({
apiKey: 'k',
endpointId: 'ep',
base: 'https://api.runpod.ai/v2',
});
vi.stubEnv('RUNPOD_API_BASE', 'http://localhost:8801');
expect(getRunPodConfig()?.base).toBe('http://localhost:8801');
});
});
describe('startJob', () => {
it('posts the input to /run with the bearer key and returns the job id', async () => {
fetchMock.mockResolvedValueOnce(Response.json({ id: 'job-1', status: 'IN_QUEUE' }));
expect(await startJob(cfg, { segments: [] })).toBe('job-1');
const [url, init] = fetchMock.mock.calls[0]!;
expect(url).toBe('https://rp.test/v2/ep1/run');
expect(init.method).toBe('POST');
expect(init.headers.Authorization).toBe('Bearer rp-key');
expect(JSON.parse(init.body)).toEqual({ input: { segments: [] } });
});
it('throws on a non-OK response or a missing id', async () => {
fetchMock.mockResolvedValueOnce(new Response('x', { status: 500 }));
await expect(startJob(cfg, {})).rejects.toThrow('500');
fetchMock.mockResolvedValueOnce(Response.json({}));
await expect(startJob(cfg, {})).rejects.toThrow();
});
});
describe('streamJob', () => {
it('yields outputs across polls in order, then the terminal status', async () => {
fetchMock
.mockResolvedValueOnce(
Response.json({ status: 'IN_PROGRESS', stream: [{ output: { id: 's0' } }] }),
)
.mockResolvedValueOnce(Response.json({ status: 'IN_PROGRESS', stream: [] }))
.mockResolvedValueOnce(
Response.json({ status: 'COMPLETED', stream: [{ output: { id: 's1' } }] }),
);
const events = await collect(streamJob(cfg, 'job-1', new AbortController().signal));
expect(events).toEqual([
{ output: { id: 's0' } },
{ output: { id: 's1' } },
{ status: 'COMPLETED', error: undefined },
]);
expect(fetchMock.mock.calls[0]![0]).toBe('https://rp.test/v2/ep1/stream/job-1');
});
it.each(['FAILED', 'CANCELLED', 'TIMED_OUT'])('ends on %s', async (status) => {
fetchMock.mockResolvedValueOnce(Response.json({ status, stream: [], error: 'boom' }));
const events = await collect(streamJob(cfg, 'job-1', new AbortController().signal));
expect(events).toEqual([{ status, error: 'boom' }]);
});
it('throws when a poll fails', async () => {
fetchMock.mockResolvedValueOnce(new Response('x', { status: 502 }));
await expect(collect(streamJob(cfg, 'j', new AbortController().signal))).rejects.toThrow('502');
});
it('passes the abort signal to every poll', async () => {
const controller = new AbortController();
fetchMock.mockResolvedValueOnce(Response.json({ status: 'COMPLETED', stream: [] }));
await collect(streamJob(cfg, 'j', controller.signal));
expect(fetchMock.mock.calls[0]![1].signal).toBe(controller.signal);
});
});
describe('best-effort calls', () => {
it('cancelJob posts /cancel and never throws', async () => {
fetchMock.mockRejectedValueOnce(new Error('down'));
await expect(cancelJob(cfg, 'job-1')).resolves.toBeUndefined();
expect(fetchMock.mock.calls[0]![0]).toBe('https://rp.test/v2/ep1/cancel/job-1');
expect(fetchMock.mock.calls[0]![1].method).toBe('POST');
});
it('warmup posts a warmup job to /run and never throws', async () => {
fetchMock.mockRejectedValueOnce(new Error('down'));
await expect(warmup(cfg)).resolves.toBeUndefined();
const [url, init] = fetchMock.mock.calls[0]!;
expect(url).toBe('https://rp.test/v2/ep1/run');
expect(JSON.parse(init.body)).toEqual({ input: { warmup: true } });
});
});

View file

@ -0,0 +1,346 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { TTSMessageEvent } from '@/services/tts/TTSClient';
import type { TTSController } from '@/services/tts/TTSController';
import type {
SpeechProvider,
SpeechSynthesisRequest,
SpeechSynthesisResult,
} from '@/services/tts/providers/types';
import { FakeAudioContext } from './tts-fake-audio';
// Scheduler behavior for providers that synthesize in windows (Readest Voice):
// fatal errors end the session, the scheduler prefetches a bounded lookahead,
// and paragraph preloads become background prefetches instead of synthesis.
let parsedMarks: Array<{ name: string; text: string; language: string }> = [];
vi.mock('@/utils/ssml', () => ({
parseSSMLMarks: vi.fn(() => ({ marks: parsedMarks })),
}));
vi.mock('@/utils/misc', () => ({
getUserLocale: vi.fn((lang: string) => (lang === 'en' ? 'en-US' : lang)),
getOSPlatform: vi.fn(() => 'macos'),
stubTranslation: (key: string) => key,
}));
vi.mock('@/services/environment', async (importOriginal) => ({
...(await importOriginal<typeof import('@/services/environment')>()),
isTauriAppPlatform: () => false,
}));
vi.mock('@/services/tts/TTSUtils', () => ({
TTSUtils: {
getPreferredVoice: vi.fn(() => null),
sortVoicesPreferLocaleFunc: () => () => 0,
},
}));
vi.spyOn(console, 'warn').mockImplementation(() => {});
vi.spyOn(console, 'log').mockImplementation(() => {});
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
const audio = (): SpeechSynthesisResult => ({ audio: new ArrayBuffer(24000), boundaries: [] });
type Types = typeof import('@/services/tts/providers/types');
type Client = typeof import('@/services/tts/BufferedTTSClient').BufferedTTSClient;
describe('BufferedTTSClient with a windowed provider', () => {
let BufferedTTSClient: Client;
let types: Types;
let controller: TTSController;
beforeEach(async () => {
vi.resetModules();
// Duration estimates calibrate per voice in localStorage; isolate tests.
localStorage.clear();
FakeAudioContext.instances = [];
vi.stubGlobal('AudioContext', FakeAudioContext);
vi.stubGlobal('requestAnimationFrame', () => 1);
vi.stubGlobal('cancelAnimationFrame', () => {});
parsedMarks = [
{ name: '0', text: 'First sentence.', language: 'en' },
{ name: '1', text: 'Second sentence.', language: 'en' },
];
controller = {
dispatchSpeakMark: vi.fn(),
prepareSpeakWords: vi.fn(),
dispatchSpeakWord: vi.fn(),
} as unknown as TTSController;
// Enter at EdgeTTSClient: constants.ts circularly imports it.
await import('@/services/tts/EdgeTTSClient');
({ BufferedTTSClient } = await import('@/services/tts/BufferedTTSClient'));
types = await import('@/services/tts/providers/types');
});
afterEach(() => vi.unstubAllGlobals());
const makeProvider = (overrides: Partial<SpeechProvider> = {}): SpeechProvider => ({
id: 'windowed',
label: 'Windowed',
init: async () => true,
getAllVoices: async () => [{ id: 'v1', name: 'Voice 1', lang: 'en-US' }],
synthesize: vi.fn(async () => audio()),
...overrides,
});
const start = async (provider: SpeechProvider) => {
const client = new BufferedTTSClient(provider, controller);
await client.init();
return client;
};
const speak = (client: InstanceType<Client>, signal: AbortSignal, preload = false) => {
const events: TTSMessageEvent[] = [];
const done = (async () => {
for await (const event of await client.speak('<ssml/>', signal, preload)) events.push(event);
})();
return { events, done };
};
describe('fatal errors', () => {
test('end the session at once: no retry, no skip, no further marks', async () => {
const synthesize = vi.fn(async () => {
throw new types.SpeechSynthesisFatalError('DAILY_QUOTA_EXCEEDED');
});
const client = await start(makeProvider({ synthesize }));
const { events, done } = speak(client, new AbortController().signal);
await done;
expect(events.map((e) => e.code)).toEqual(['error']);
expect(events[0]!.message).toBe('DAILY_QUOTA_EXCEEDED');
expect(synthesize).toHaveBeenCalledTimes(1);
});
test('warmSentence rethrows them; other failures still return false', async () => {
const { CachingProvider } = await import('@/services/tts/providers/cache');
const store = { get: async () => null, put: async () => {} };
const fatal = makeProvider({
synthesize: vi.fn(async () => {
throw new types.SpeechSynthesisFatalError('DAILY_QUOTA_EXCEEDED');
}),
});
const client = await start(new CachingProvider(fatal, store));
await expect(client.warmSentence(0, 0, 'en', 'Hi.')).rejects.toBeInstanceOf(
types.SpeechSynthesisFatalError,
);
const permanent = makeProvider({
synthesize: vi.fn(async () => {
throw new types.SpeechSynthesisPermanentError('no audio');
}),
});
const other = await start(new CachingProvider(permanent, store));
await expect(other.warmSentence(0, 0, 'en', 'Hi.')).resolves.toBe(false);
});
});
describe('voice language', () => {
test('a provider that only voices its own languages gets no voice for others', async () => {
const client = await start(makeProvider({ sameLanguageVoicesOnly: true }));
await client.setVoice('v1'); // it has been reading English
expect(await client.getVoiceIdFromLang('en')).toBe('v1');
// No voice: the provider skips the sentence instead of reading German
// with an English voice.
expect(await client.getVoiceIdFromLang('de')).toBe('');
});
test('other providers still fall back to a voice of another language', async () => {
const client = await start(makeProvider());
await client.setVoice('v1');
expect(await client.getVoiceIdFromLang('de')).toBe('v1');
});
});
describe('aborts', () => {
test('an aborted synthesis is not reported as a failed attempt', async () => {
const warn = vi.mocked(console.warn);
warn.mockClear();
const synthesize = vi.fn(
(_req: SpeechSynthesisRequest, signal: AbortSignal) =>
new Promise<SpeechSynthesisResult>((_, reject) =>
signal.addEventListener('abort', () =>
reject(new DOMException('Aborted', 'AbortError')),
),
),
);
const client = await start(makeProvider({ synthesize }));
const controller = new AbortController();
const { done } = speak(client, controller.signal);
await flush();
controller.abort();
await done;
expect(synthesize).toHaveBeenCalledTimes(1);
expect(warn.mock.calls.some(([m]) => String(m).includes('synthesis attempt'))).toBe(false);
});
});
describe('listen prefetch', () => {
const prefetchCalls = (provider: SpeechProvider) =>
vi.mocked(provider.prefetch!).mock.calls.map(([reqs, lane, , options]) => ({
texts: (reqs as SpeechSynthesisRequest[]).map((r) => r.text),
lane,
options,
}));
test('prefetches the current mark and its lookahead before synthesizing it', async () => {
const order: string[] = [];
const provider = makeProvider({
prefetch: vi.fn((reqs: SpeechSynthesisRequest[]) => {
order.push(`prefetch:${reqs[0]!.text}`);
}),
synthesize: vi.fn(async (req: SpeechSynthesisRequest) => {
order.push(`synth:${req.text}`);
return audio();
}),
});
const client = await start(provider);
speak(client, new AbortController().signal);
await flush();
await flush();
expect(prefetchCalls(provider)[0]).toEqual({
texts: ['First sentence.', 'Second sentence.'],
lane: 'listen',
options: { onDelivered: expect.any(Function) },
});
expect(order.slice(0, 2)).toEqual(['prefetch:First sentence.', 'synth:First sentence.']);
});
// At the default estimate (15 Latin chars/s) 30 chars is about 2 s, 160
// about 10.7 s and 300 about 20 s.
const marksOf = (...lengths: number[]) =>
lengths.map((length, i) => ({
name: String(i),
text: `${i}`.padEnd(length, 'a'),
language: 'en',
}));
test('caps the lookahead at 32 marks', async () => {
parsedMarks = Array.from({ length: 40 }, (_, i) => ({
name: String(i),
text: `Sentence ${i}.`,
language: 'en',
}));
const provider = makeProvider({ prefetch: vi.fn() });
const client = await start(provider);
speak(client, new AbortController().signal);
await flush();
expect(prefetchCalls(provider)[0]!.texts).toHaveLength(32);
});
test('caps the lookahead at about three minutes of estimated audio', async () => {
// Sixteen 10.7 s marks fit in 180 s, seventeen do not.
parsedMarks = marksOf(...Array.from({ length: 20 }, () => 160));
const provider = makeProvider({ prefetch: vi.fn() });
const client = await start(provider);
speak(client, new AbortController().signal);
await flush();
expect(prefetchCalls(provider)[0]!.texts).toHaveLength(16);
});
test('asks for long marks behind short ones well before they are due', async () => {
parsedMarks = marksOf(30, 30, 300, 300, 300);
const provider = makeProvider({ prefetch: vi.fn() });
const client = await start(provider);
speak(client, new AbortController().signal);
await flush();
expect(prefetchCalls(provider)[0]!.texts).toHaveLength(5);
});
test('preloads at most about a minute of each upcoming paragraph', async () => {
// Three 20 s marks fit in 60 s, four do not.
parsedMarks = marksOf(300, 300, 300, 300, 300);
const provider = makeProvider({ prefetch: vi.fn() });
const client = await start(provider);
await speak(client, new AbortController().signal, true).done;
expect(prefetchCalls(provider)[0]!.texts).toHaveLength(3);
});
test('preloads become a background prefetch of the opening marks, never synthesis', async () => {
parsedMarks = Array.from({ length: 5 }, (_, i) => ({
name: String(i),
text: `Sentence ${i}.`,
language: 'en',
}));
const provider = makeProvider({ prefetch: vi.fn() });
const client = await start(provider);
const { events, done } = speak(client, new AbortController().signal, true);
await done;
expect(events.map((e) => e.code)).toEqual(['end']);
expect(prefetchCalls(provider)).toEqual([
{
texts: ['Sentence 0.', 'Sentence 1.', 'Sentence 2.', 'Sentence 3.', 'Sentence 4.'],
lane: 'listen',
options: { background: true, onDelivered: expect.any(Function) },
},
]);
expect(provider.synthesize).not.toHaveBeenCalled();
});
test('counts prefetched sentences as buffered as their audio arrives', async () => {
// The player's buffer bar shows the share of sentences with a duration.
const { getMeasuredDuration } = await import('@/services/tts/ttsDuration');
const delivered = {
audio: new ArrayBuffer(24000),
boundaries: [{ offset: 0, duration: 20_000_000, text: 'x' }],
};
const provider = makeProvider({
prefetch: vi.fn((reqs: SpeechSynthesisRequest[], _lane, _signal, options) =>
options?.onDelivered?.(reqs[1]!, delivered),
),
// Playback never gets past the first sentence: only the prefetch counts.
synthesize: vi.fn(() => new Promise<SpeechSynthesisResult>(() => {})),
});
const client = await start(provider);
speak(client, new AbortController().signal);
await flush();
expect(getMeasuredDuration('v1', 'Second sentence.')).toBeGreaterThan(0);
});
test('reports windowed prefetch only for providers that take it', async () => {
expect(
(await start(makeProvider({ prefetch: vi.fn() }))).getCapabilities().windowedPrefetch,
).toBe(true);
expect((await start(makeProvider())).getCapabilities().windowedPrefetch).toBe(false);
});
test('providers without prefetch keep synthesizing preloads', async () => {
const provider = makeProvider();
const client = await start(provider);
await speak(client, new AbortController().signal, true).done;
expect(provider.synthesize).toHaveBeenCalled();
});
test('a cache around a provider without prefetch keeps preloads synthesizing', async () => {
// Edge runs behind a CachingProvider on every platform.
const { CachingProvider } = await import('@/services/tts/providers/cache');
const store = { get: async () => null, put: async () => {} };
const provider = makeProvider();
const client = await start(new CachingProvider(provider, store));
expect(client.getCapabilities().windowedPrefetch).toBe(false);
await speak(client, new AbortController().signal, true).done;
expect(provider.synthesize).toHaveBeenCalled();
});
});
describe('downloads', () => {
test('prefetchSentences hands a section to the provider on the download lane', async () => {
const prefetch = vi.fn();
const client = await start(makeProvider({ prefetch }));
const signal = new AbortController().signal;
await client.prefetchSentences(
[
{ lang: 'en', text: 'A.' },
{ lang: 'en', text: 'B.' },
],
signal,
);
expect(prefetch).toHaveBeenCalledWith(
[
{ lang: 'en', text: 'A.', voice: 'v1', pitch: 1 },
{ lang: 'en', text: 'B.', voice: 'v1', pitch: 1 },
],
'download',
signal,
);
});
});
});

View file

@ -46,6 +46,20 @@ describe('CachingProvider', () => {
provider = new CachingProvider(inner, store);
});
test('mirrors the inner provider voice-language policy', () => {
expect(provider.sameLanguageVoicesOnly).toBeUndefined();
const strict = new CachingProvider(makeInner({ sameLanguageVoicesOnly: true }), store);
expect(strict.sameLanguageVoicesOnly).toBe(true);
});
test('init starts opening the store, so the first lookup does not pay for it', async () => {
const opening = Object.assign(new MemoryStore(), {
open: vi.fn().mockResolvedValue(undefined),
});
await new CachingProvider(inner, opening).init();
expect(opening.open).toHaveBeenCalledTimes(1);
});
test('mirrors the inner provider identity', () => {
expect(provider.id).toBe('fake');
expect(provider.label).toBe('Fake');
@ -66,6 +80,31 @@ describe('CachingProvider', () => {
expect(inner.synthesize).toHaveBeenCalledTimes(1);
});
test('a sentence synthesized ahead plays from memory, without a store read', async () => {
// Store reads cost hundreds of ms on device; the paragraph that was just
// prefetched must not wait on one at the paragraph boundary.
await provider.synthesize(req(), signal());
store.get.mockClear();
const result = await provider.synthesize(req(), signal());
expect(result.boundaries).toEqual(BOUNDARIES);
expect(store.get).not.toHaveBeenCalled();
expect(inner.synthesize).toHaveBeenCalledTimes(1);
});
test('a sentence found by a prefetch plays from memory, without a second store read', async () => {
store.map.set(
(await import('@/services/tts/providers/cache')).computeTTSCacheKey('fake', req('old')),
{ audio: new ArrayBuffer(8), boundaries: BOUNDARIES },
);
const withPrefetch = new CachingProvider(makeInner({ prefetch: vi.fn() }), store);
withPrefetch.prefetch?.([req('old')], 'listen', signal());
await new Promise((resolve) => setTimeout(resolve, 0));
store.get.mockClear();
const result = await withPrefetch.synthesize(req('old'), signal());
expect(result.audio.byteLength).toBe(8);
expect(store.get).not.toHaveBeenCalled();
});
test('hits hand out an independent buffer per call', async () => {
// decodeAudioData detaches its input; a shared cached buffer would break
// the second playback of the same sentence.
@ -161,3 +200,129 @@ describe('CachingProvider', () => {
expect(provider.fallbackVoiceId).toBe('v-fallback');
});
});
describe('CachingProvider.prefetch', () => {
const flush = () => new Promise((r) => setTimeout(r, 0));
// An inner provider whose synthesize resolves only when the test delivers,
// like a windowed provider waiting on a streamed frame.
const windowed = () => {
const pending = new Map<string, (r: SpeechSynthesisResult) => void>();
const inner = makeInner({
prefetch: vi.fn(),
synthesize: vi
.fn()
.mockImplementation(
(r: { text: string }) =>
new Promise<SpeechSynthesisResult>((resolve) => pending.set(r.text, resolve)),
),
});
const deliver = (text: string) =>
pending.get(text)!({ audio: new ArrayBuffer(4), boundaries: BOUNDARIES });
return { inner, deliver };
};
test('forwards only uncached requests, in order, with lane and options', async () => {
const { inner, deliver } = windowed();
const store = new MemoryStore();
const provider = new CachingProvider(inner, store);
const cached = provider.synthesize(req('b'), signal());
await flush();
deliver('b');
await cached;
const s = signal();
provider.prefetch!([req('a'), req('b'), req('c')], 'listen', s, { background: true });
await flush();
expect(inner.prefetch).toHaveBeenCalledWith([req('a'), req('c')], 'listen', s, {
background: true,
});
});
test('persists a delivered sentence without a later synthesize call', async () => {
const { inner, deliver } = windowed();
const store = new MemoryStore();
const provider = new CachingProvider(inner, store);
provider.prefetch!([req('a')], 'download', signal());
await flush();
deliver('a');
await flush();
expect(store.put).toHaveBeenCalledTimes(1);
});
test('fills the cache of a background prefetch without making it foreground', async () => {
const { inner } = windowed();
const provider = new CachingProvider(inner, new MemoryStore());
const s = signal();
provider.prefetch!([req('a')], 'listen', s, { background: true });
await flush();
expect(inner.synthesize).toHaveBeenCalledWith(req('a'), s, { background: true });
});
test('reports cached sentences to onDelivered instead of forwarding them', async () => {
const { inner, deliver } = windowed();
const provider = new CachingProvider(inner, new MemoryStore());
const cached = provider.synthesize(req('b'), signal());
await flush();
deliver('b');
await cached;
const onDelivered = vi.fn();
provider.prefetch!([req('b')], 'listen', signal(), { onDelivered });
await flush();
expect(onDelivered).toHaveBeenCalledWith(
req('b'),
expect.objectContaining({ boundaries: BOUNDARIES }),
);
expect(inner.prefetch).not.toHaveBeenCalled();
});
test('a later synthesize joins the prefetch (inner synthesizes once)', async () => {
const { inner, deliver } = windowed();
const provider = new CachingProvider(inner, new MemoryStore());
provider.prefetch!([req('a')], 'listen', signal());
await flush();
const joined = provider.synthesize(req('a'), signal());
deliver('a');
expect((await joined).audio.byteLength).toBe(4);
expect(inner.synthesize).toHaveBeenCalledTimes(1);
});
test('still forwards requests already in flight, without a second synthesis', async () => {
// A preload's cache fill may already be running when its paragraph starts:
// the foreground prefetch must reach the provider so it can raise its priority.
const { inner } = windowed();
const provider = new CachingProvider(inner, new MemoryStore());
void provider.synthesize(req('a'), signal());
provider.prefetch!([req('a'), req('b')], 'listen', signal());
await flush();
expect(vi.mocked(inner.prefetch!).mock.calls[0]![0]).toEqual([req('a'), req('b')]);
expect(vi.mocked(inner.synthesize).mock.calls.map(([r]) => r.text)).toEqual(['a', 'b']);
});
test('cacheable: false forwards everything and starts no synthesis', async () => {
const { inner } = windowed();
Object.assign(inner, { cacheable: false });
const provider = new CachingProvider(inner, new MemoryStore());
provider.prefetch!([req('a')], 'listen', signal());
await flush();
expect(inner.prefetch).toHaveBeenCalledWith([req('a')], 'listen', expect.anything(), undefined);
expect(inner.synthesize).not.toHaveBeenCalled();
});
test('swallows failures of the detached synthesis', async () => {
const inner = makeInner({
prefetch: vi.fn(),
synthesize: vi.fn().mockRejectedValue(new SpeechSynthesisPermanentError('no audio')),
});
const provider = new CachingProvider(inner, new MemoryStore());
provider.prefetch!([req('a')], 'listen', signal());
await flush();
await flush();
expect(inner.synthesize).toHaveBeenCalledTimes(1);
});
test('offers prefetch only when the inner provider has one', () => {
expect(new CachingProvider(makeInner(), new MemoryStore()).prefetch).toBeUndefined();
const windowed = makeInner({ prefetch: vi.fn() });
expect(new CachingProvider(windowed, new MemoryStore()).prefetch).toBeTypeOf('function');
});
});

View file

@ -40,6 +40,9 @@ vi.mock('@/services/tts/WebSpeechClient', () => ({
}),
}));
vi.mock('@/services/tts/EdgeTTSClient', () => ({
// constants.ts imports this named const from the same module; the mock
// factory replaces the whole module, so it must re-export it too.
DEFAULT_SENTENCE_GAP_SEC: 0.15,
EdgeTTSClient: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, makeMockClient('edge-tts'));
}),

View file

@ -41,6 +41,9 @@ vi.mock('@/services/tts/WebSpeechClient', () => ({
}),
}));
vi.mock('@/services/tts/EdgeTTSClient', () => ({
// constants.ts imports this named const from the same module; the mock
// factory replaces the whole module, so it must re-export it too.
DEFAULT_SENTENCE_GAP_SEC: 0.15,
EdgeTTSClient: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, makeMockClient('edge-tts'));
}),

View file

@ -0,0 +1,288 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { TTSClient, TTSMessageEvent } from '@/services/tts/TTSClient';
import type { TTSGranularity, TTSVoice } from '@/services/tts/types';
import type { FoliateView } from '@/types/view';
import type { AppService } from '@/types/system';
// Controller wiring of Readest Voice: a BufferedTTSClient over the Readest
// provider, sharing Edge's per-book cache store, registered everywhere the
// controller used to know only Edge.
const h = vi.hoisted(() => ({
edgeArgs: [] as unknown[][],
bufferedArgs: [] as unknown[][],
readestClient: null as Record<string, unknown> | null,
warmup: vi.fn(),
store: { get: async () => null, put: async () => {} },
readestInit: true,
readestVoices: [] as TTSVoice[],
}));
function mockClient(name: string): TTSClient {
return {
name,
initialized: false,
init: vi.fn().mockImplementation(async function (this: { initialized: boolean }) {
this.initialized = true;
return true;
}),
shutdown: vi.fn().mockResolvedValue(undefined),
speak: vi.fn().mockImplementation(async function* (): AsyncGenerator<TTSMessageEvent> {
yield { code: 'end' };
}),
pause: vi.fn().mockResolvedValue(true),
resume: vi.fn().mockResolvedValue(true),
stop: vi.fn().mockResolvedValue(undefined),
setPrimaryLang: vi.fn(),
setRate: vi.fn().mockResolvedValue(undefined),
setPitch: vi.fn().mockResolvedValue(undefined),
setVoice: vi.fn().mockResolvedValue(undefined),
getAllVoices: vi.fn().mockResolvedValue([]),
getVoices: vi.fn().mockResolvedValue([]),
getGranularities: vi.fn().mockReturnValue(['sentence'] as TTSGranularity[]),
getCapabilities: vi.fn().mockReturnValue({
wordBoundaries: true,
mediaClock: true,
gapControl: true,
liveRateChange: false,
}),
getVoiceId: vi.fn().mockReturnValue('voice-1'),
getSpeakingLang: vi.fn().mockReturnValue('en'),
};
}
const bufferedExtras = () => ({
setSentenceGap: vi.fn(),
setParagraphGap: vi.fn(),
canDownload: vi.fn().mockReturnValue(true),
getSectionCacheStatuses: vi.fn().mockResolvedValue(new Map()),
getCacheBytes: vi.fn().mockResolvedValue(0),
beginDownloadSections: vi.fn(),
completeDownloadSections: vi.fn(),
cancelDownloadSections: vi.fn(),
clearDownloads: vi.fn(),
});
vi.mock('@/services/tts/WebSpeechClient', () => ({
WebSpeechClient: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, mockClient('web-speech'));
}),
}));
vi.mock('@/services/tts/EdgeTTSClient', () => ({
// constants.ts imports this from here (circular import in production code).
DEFAULT_SENTENCE_GAP_SEC: 0.15,
EdgeTTSClient: vi.fn().mockImplementation(function (
this: Record<string, unknown>,
...args: unknown[]
) {
h.edgeArgs.push(args);
Object.assign(this, mockClient('edge-tts'), bufferedExtras());
(this['getAllVoices'] as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: 'en-US-AriaNeural', name: 'Aria', lang: 'en-US' },
]);
}),
}));
vi.mock('@/services/tts/NativeTTSClient', () => ({
NativeTTSClient: vi.fn(),
}));
vi.mock('@/services/tts/BufferedTTSClient', () => ({
BufferedTTSClient: vi.fn().mockImplementation(function (
this: Record<string, unknown>,
...args: unknown[]
) {
h.bufferedArgs.push(args);
Object.assign(this, mockClient('readest-tts'), bufferedExtras());
(this['init'] as ReturnType<typeof vi.fn>).mockImplementation(async function (this: {
initialized: boolean;
}) {
this.initialized = h.readestInit;
return h.readestInit;
});
(this['getAllVoices'] as ReturnType<typeof vi.fn>).mockImplementation(
async () => h.readestVoices,
);
h.readestClient = this;
}),
}));
vi.mock('@/services/tts/providers/readest', () => ({
ReadestVoiceProvider: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, { id: 'readest-tts', warmup: h.warmup });
}),
}));
vi.mock('@/services/tts/providers/bookCacheStore', async (orig) => ({
...(await orig<typeof import('@/services/tts/providers/bookCacheStore')>()),
createBookTTSCacheStore: vi.fn(() => h.store),
}));
vi.mock('@/services/tts/TTSUtils', () => ({
TTSUtils: {
getPreferredClient: vi.fn().mockReturnValue(null),
setPreferredClient: vi.fn(),
setPreferredVoice: vi.fn(),
getPreferredVoice: vi.fn().mockReturnValue(null),
},
}));
vi.mock('foliate-js/overlayer.js', () => ({ Overlayer: { highlight: 'highlightFn' } }));
vi.mock('@/utils/node', () => ({ createRejectFilter: vi.fn(() => () => 1) }));
import { TTSController } from '@/services/tts/TTSController';
import { TTSUtils } from '@/services/tts/TTSUtils';
import { CachingProvider } from '@/services/tts/providers/cache';
import { createBookTTSCacheStore } from '@/services/tts/providers/bookCacheStore';
const READEST_VOICES = [{ id: 'kokoro:af_heart', name: 'Heart', lang: 'en-US' }];
const view = {
renderer: { primaryIndex: 0, getContents: vi.fn().mockReturnValue([]) },
book: { sections: [] },
language: { isCJK: false },
tts: null,
} as unknown as FoliateView;
const appService = { isAndroidApp: false, isIOSApp: false } as unknown as AppService;
let controller: TTSController;
const readest = () => h.readestClient as unknown as TTSClient & ReturnType<typeof bufferedExtras>;
const edge = () => controller.ttsEdgeClient as unknown as ReturnType<typeof bufferedExtras>;
beforeEach(() => {
h.edgeArgs = [];
h.bufferedArgs = [];
h.readestInit = true;
h.readestVoices = READEST_VOICES;
h.warmup.mockReset();
vi.mocked(TTSUtils.getPreferredClient).mockReturnValue(null);
vi.mocked(createBookTTSCacheStore).mockClear();
controller = new TTSController(appService, view, true);
});
afterEach(() => vi.clearAllMocks());
describe('construction', () => {
test('Edge and Readest share one per-book cache store', () => {
expect(createBookTTSCacheStore).toHaveBeenCalledTimes(1);
expect(h.edgeArgs[0]![2]).toBe(h.store);
const provider = h.bufferedArgs[0]![0];
expect(provider).toBeInstanceOf(CachingProvider);
expect((provider as CachingProvider).id).toBe('readest-tts');
});
test('without a cache store the provider is used directly', () => {
vi.mocked(createBookTTSCacheStore).mockReturnValueOnce(null);
h.bufferedArgs = [];
new TTSController(appService, view, true);
expect(h.bufferedArgs[0]![0]).not.toBeInstanceOf(CachingProvider);
});
});
describe('init', () => {
test('Readest Voice is available but Edge stays the default engine', async () => {
await controller.init();
expect(readest().init).toHaveBeenCalled();
expect(controller.ttsClient.name).toBe('edge-tts');
expect(controller.ttsReadestVoices).toEqual(READEST_VOICES);
});
test('a remembered Readest preference selects it', async () => {
vi.mocked(TTSUtils.getPreferredClient).mockReturnValue('readest-tts');
await controller.init();
expect(controller.ttsClient).toBe(readest());
});
});
describe('voices', () => {
test('lists the Readest group after native and before Edge, and warms the worker', async () => {
await controller.init();
vi.mocked(readest().getVoices).mockResolvedValue([
{ id: 'readest-tts', name: 'Readest Voice', voices: READEST_VOICES },
]);
vi.mocked(controller.ttsEdgeClient.getVoices).mockResolvedValue([
{ id: 'edge-tts', name: 'Edge TTS', voices: [] },
]);
const groups = await controller.getVoices('en');
expect(groups.map((g) => g.id)).toEqual(['readest-tts', 'edge-tts']);
expect(h.warmup).toHaveBeenCalledTimes(1);
});
test('hides the Readest group entirely when unavailable (free plan, kill switch)', async () => {
h.readestInit = false;
await controller.init();
vi.mocked(readest().getVoices).mockResolvedValue([
{ id: 'readest-tts', name: 'Readest Voice', voices: READEST_VOICES, disabled: true },
]);
const groups = await controller.getVoices('en');
expect(groups.map((g) => g.id)).not.toContain('readest-tts');
expect(h.warmup).not.toHaveBeenCalled();
});
});
describe('book language', () => {
test('a remembered Readest choice yields to Edge for a language it has no voice for', async () => {
vi.mocked(TTSUtils.getPreferredClient).mockReturnValue('readest-tts');
await controller.init();
expect(controller.ttsClient).toBe(readest());
await controller.setLang('de');
expect(controller.ttsClient.name).toBe('edge-tts');
// The choice itself is kept for books Readest Voice can read.
expect(TTSUtils.setPreferredClient).not.toHaveBeenCalled();
});
test('keeps Readest Voice for a language it can voice', async () => {
vi.mocked(TTSUtils.getPreferredClient).mockReturnValue('readest-tts');
await controller.init();
await controller.setLang('en-GB');
expect(controller.ttsClient).toBe(readest());
});
test('the picker hides an empty Readest group', async () => {
await controller.init();
vi.mocked(readest().getVoices).mockResolvedValue([
{ id: 'readest-tts', name: 'Readest Voice', voices: [], disabled: true },
]);
const groups = await controller.getVoices('de');
expect(groups.map((g) => g.id)).not.toContain('readest-tts');
expect(h.warmup).not.toHaveBeenCalled();
});
});
describe('setVoice', () => {
test("the engine-default voice ('') never selects Readest Voice", async () => {
await controller.init();
await controller.setVoice('', 'en');
expect(controller.ttsClient.name).toBe('edge-tts');
});
test('a Readest voice selects the Readest client', async () => {
await controller.init();
await controller.setVoice('kokoro:af_heart', 'en');
expect(controller.ttsClient).toBe(readest());
expect(TTSUtils.setPreferredClient).toHaveBeenCalledWith('readest-tts');
expect(readest().setVoice).toHaveBeenCalledWith('kokoro:af_heart');
});
});
describe('settings fan out to the Readest client', () => {
test('primary language, gaps and shutdown', async () => {
await controller.init();
await controller.setPrimaryLang('en');
controller.setSentenceGap(0.2);
controller.setParagraphGap(0.5);
await controller.shutdown();
expect(readest().setPrimaryLang).toHaveBeenCalledWith('en');
expect(readest().setSentenceGap).toHaveBeenCalledWith(0.2);
expect(readest().setParagraphGap).toHaveBeenCalledWith(0.5);
expect(readest().shutdown).toHaveBeenCalled();
});
});
describe('downloads follow the active synthetic engine', () => {
test('Edge by default, Readest Voice when it is the active client', async () => {
await controller.init();
await controller.clearDownloads();
expect(edge().clearDownloads).toHaveBeenCalledTimes(1);
await controller.setVoice('kokoro:af_heart', 'en');
await controller.clearDownloads();
await controller.beginDownloadSections([1]);
expect(readest().clearDownloads).toHaveBeenCalledTimes(1);
expect(readest().beginDownloadSections).toHaveBeenCalledWith([1]);
expect(controller.canDownload()).toBe(true);
expect(readest().canDownload).toHaveBeenCalled();
});
});

View file

@ -53,6 +53,9 @@ vi.mock('@/services/tts/WebSpeechClient', () => ({
}));
vi.mock('@/services/tts/EdgeTTSClient', () => ({
// constants.ts imports this named const from the same module; the mock
// factory replaces the whole module, so it must re-export it too.
DEFAULT_SENTENCE_GAP_SEC: 0.15,
EdgeTTSClient: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, makeMockClient('edge-tts'));
}),
@ -193,6 +196,17 @@ describe('TTSController section timeline', () => {
expect(info!.measuredFraction).toBeGreaterThan(0);
});
test('getPlaybackInfo follows a voice the client resolved after the timeline was built', async () => {
// A client whose voices load asynchronously reports no voice until its
// first sentence plays; durations are recorded under the resolved one.
vi.mocked(controller.ttsClient.getVoiceId).mockReturnValue('');
await controller.ensureTimeline();
recordMeasuredDuration('late-voice', S0, 4);
recordMeasuredDuration('late-voice', S1, 6);
vi.mocked(controller.ttsClient.getVoiceId).mockReturnValue('late-voice');
expect(controller.getPlaybackInfo()!.measuredFraction).toBeGreaterThan(0);
});
test('getPlaybackInfo is null before the timeline is built (reserved-slot state)', () => {
expect(controller.getPlaybackInfo()).toBeNull();
});

View file

@ -15,6 +15,9 @@ vi.mock('@/services/tts/WebSpeechClient', () => ({
}));
vi.mock('@/services/tts/EdgeTTSClient', () => ({
// constants.ts imports this named const from the same module; the mock
// factory replaces the whole module, so it must re-export it too.
DEFAULT_SENTENCE_GAP_SEC: 0.15,
EdgeTTSClient: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, createMockTTSClient('edge'), {
setSentenceGap: vi.fn(),
@ -69,6 +72,7 @@ vi.mock('@/utils/node', () => ({
vi.mock('@/utils/lang', () => ({
isValidLang: vi.fn(() => true),
isCJKLang: vi.fn(() => false),
}));
vi.mock('foliate-js/tts.js', () => ({
@ -294,6 +298,21 @@ describe('TTSController', () => {
expect(controller.ttsWebClient.init).toHaveBeenCalled();
});
test('initialises the engines concurrently, not one after another', async () => {
// Each init can take seconds (Edge synthesizes a probe sentence, system
// TTS waits for its voice list); in sequence they add up before play.
let edgeDone!: (ok: boolean) => void;
vi.mocked(controller.ttsEdgeClient.init).mockImplementation(
() => new Promise<boolean>((resolve) => (edgeDone = resolve)),
);
const ready = controller.init();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(controller.ttsWebClient.init).toHaveBeenCalled();
edgeDone(true);
await ready;
expect(controller.ttsClient.name).toBe('edge');
});
test('sets ttsClient to first available client (edge)', async () => {
await controller.init();
// edge inits first and succeeds, so it becomes the active client
@ -640,6 +659,13 @@ describe('TTSController', () => {
const armWithSentence = async (range: Range, markName = '0') => {
await controller.initViewTTS(0);
// A client that reports word boundaries, as word mode needs.
controller.ttsClient.getCapabilities = vi.fn().mockReturnValue({
wordBoundaries: true,
mediaClock: true,
gapControl: false,
liveRateChange: false,
}) as unknown as typeof controller.ttsClient.getCapabilities;
mockView.tts = {
setMark: vi.fn().mockReturnValue(range),
getLastRange: vi.fn().mockImplementation(() => range.cloneRange()),
@ -652,15 +678,32 @@ describe('TTSController', () => {
});
};
test('prepareSpeakWords immediately highlights the first word (no sentence flash)', async () => {
await armWithSentence(makeSentenceRange());
vi.mocked(mockView.getCFI).mockClear();
controller.prepareSpeakWords(['Hello', 'brave', 'world']);
const addedKeys = () => getOverlayer().add.mock.calls.map((call) => call[0]);
const getCFICalls = vi.mocked(mockView.getCFI).mock.calls;
expect(getCFICalls.length).toBeGreaterThanOrEqual(1);
expect(String(getCFICalls[0]![1])).toBe('Hello');
expect(getOverlayer().add).toHaveBeenCalledTimes(1);
test('word mode tints the sentence at its mark; the first word waits for its audio', async () => {
await armWithSentence(makeSentenceRange());
// The tint shows where reading is even while the audio is pending.
expect(addedKeys()).toEqual(['tts-sentence']);
getOverlayer().add.mockClear();
controller.prepareSpeakWords(['Hello', 'brave', 'world']);
expect(addedKeys()).toEqual([]);
vi.mocked(mockView.getCFI).mockClear();
controller.dispatchSpeakWord(0);
expect(addedKeys()).toEqual(['tts-highlight']);
expect(String(vi.mocked(mockView.getCFI).mock.calls[0]![1])).toBe('Hello');
});
test('the next sentence replaces the tint and clears the last word', async () => {
await armWithSentence(makeSentenceRange());
controller.prepareSpeakWords(['Hello', 'brave', 'world']);
controller.dispatchSpeakWord(2);
getOverlayer().remove.mockClear();
getOverlayer().add.mockClear();
await armWithSentence(makeSentenceRange(), '1');
expect(getOverlayer().remove).toHaveBeenCalledWith('tts-highlight');
expect(getOverlayer().remove).toHaveBeenCalledWith('tts-sentence');
expect(addedKeys()).toEqual(['tts-sentence']);
});
test('prepareSpeakWords with no words falls back to the full-sentence highlight', async () => {
@ -671,7 +714,8 @@ describe('TTSController', () => {
const getCFICalls = vi.mocked(mockView.getCFI).mock.calls;
expect(getCFICalls.length).toBeGreaterThanOrEqual(1);
expect(String(getCFICalls[0]![1])).toBe('Hello brave world');
expect(getOverlayer().add).toHaveBeenCalledTimes(1);
// The sentence tint from the mark, then the full-sentence highlight.
expect(addedKeys()).toEqual(['tts-sentence', 'tts-highlight']);
});
test('dispatchSpeakWord highlights the word sub-range of the current sentence', async () => {
@ -713,7 +757,8 @@ describe('TTSController', () => {
test('a new speak mark clears previously prepared words', async () => {
await armWithSentence(makeSentenceRange());
controller.prepareSpeakWords(['Hello', 'brave', 'world']);
expect(getOverlayer().add).toHaveBeenCalledTimes(1);
controller.dispatchSpeakWord(0);
expect(addedKeys()).toEqual(['tts-sentence', 'tts-highlight']);
controller.dispatchSpeakMark({
offset: 0,
@ -730,7 +775,9 @@ describe('TTSController', () => {
await armWithSentence(makeSentenceRange());
controller.prepareSpeakWords(['BOGUS', 'brave']);
// First word unmatched → no eager highlight.
// First word unmatched: nothing to draw for it.
getOverlayer().add.mockClear();
controller.dispatchSpeakWord(0);
expect(getOverlayer().add).not.toHaveBeenCalled();
vi.mocked(mockView.getCFI).mockClear();
@ -750,7 +797,7 @@ describe('TTSController', () => {
const getCFICalls = vi.mocked(mockView.getCFI).mock.calls;
expect(getCFICalls.length).toBeGreaterThanOrEqual(1);
expect(String(getCFICalls[0]![1])).toBe('brave');
expect(getCFICalls.map((call) => String(call[1]))).toContain('brave');
});
test('reapplyCurrentHighlight re-draws the whole sentence when not in word mode', async () => {
@ -823,8 +870,8 @@ describe('TTSController', () => {
await armWithSentence(makeSentenceRange());
getOverlayer().add.mockClear();
controller.prepareSpeakWords(['Hello', 'brave', 'world']);
// First word highlighted immediately and word mode engaged.
expect(getOverlayer().add).toHaveBeenCalledTimes(1);
controller.dispatchSpeakWord(0);
expect(addedKeys()).toEqual(['tts-highlight']);
expect(controller.getCurrentHighlightCfi()).not.toBeNull();
});
});
@ -1289,6 +1336,62 @@ describe('TTSController', () => {
expect(forwardSpy).toHaveBeenCalledWith(false, true);
});
test('next paragraphs are preloaded once this paragraph is audible, not before', async () => {
// Stepping the live cursor through upcoming paragraphs is synchronous
// DOM work: done before this paragraph's audio is scheduled, it lands in
// the pause between paragraphs.
await controller.init();
await controller.initViewTTS(0);
controller.setParagraphGap(0);
vi.spyOn(controller, 'forward').mockResolvedValue();
const preloadSpy = vi.spyOn(controller, 'preloadNextSSML').mockResolvedValue();
speakingControllers.push(controller);
let audible!: () => void;
const gate = new Promise<void>((resolve) => (audible = resolve));
vi.mocked(controller.ttsClient.speak).mockImplementation(
(_ssml: string, _signal: AbortSignal, preload?: boolean) =>
(async function* () {
if (preload) return;
await gate;
yield { code: 'boundary', mark: '0' } as TTSMessageEvent;
yield { code: 'end' } as TTSMessageEvent;
})(),
);
await controller.speak('<speak>hello</speak>');
await new Promise((resolve) => setTimeout(resolve, 0));
expect(preloadSpy).not.toHaveBeenCalled();
audible();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(preloadSpy).toHaveBeenCalledTimes(1);
});
test('next paragraphs are preloaded anyway if this paragraph is slow to become audible', async () => {
// Uncached audio waits on the network: the next paragraphs must not.
vi.useFakeTimers();
await controller.init();
await controller.initViewTTS(0);
controller.setParagraphGap(0);
vi.spyOn(controller, 'forward').mockResolvedValue();
const preloadSpy = vi.spyOn(controller, 'preloadNextSSML').mockResolvedValue();
speakingControllers.push(controller);
vi.mocked(controller.ttsClient.speak).mockImplementation(
(_ssml: string, _signal: AbortSignal, preload?: boolean) =>
(async function* () {
if (preload) return;
await new Promise(() => {}); // never audible in this test
})(),
);
await controller.speak('<speak>hello</speak>');
await vi.advanceTimersByTimeAsync(400);
expect(preloadSpy).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(200);
expect(preloadSpy).toHaveBeenCalledTimes(1);
vi.useRealTimers();
});
test('the paragraph gap is waited out as given, not re-scaled by the rate', async () => {
// The gap arrives already scaled for the rate (see scaleGapForRate);
// dividing it again here cut every paragraph pause in half at 2x (#5750).
@ -2006,6 +2109,155 @@ describe('TTSController', () => {
);
});
test('a windowed client gets about three minutes of upcoming paragraphs, not four', async () => {
// 450 Latin chars is about 30 s at the default estimate: six reach 180 s.
const paragraph = `<speak>${'a'.repeat(450)}</speak>`;
mockView.tts = {
next: vi.fn().mockReturnValue(paragraph),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
controller.ttsClient.getCapabilities = vi.fn().mockReturnValue({
wordBoundaries: true,
mediaClock: true,
gapControl: true,
liveRateChange: false,
windowedPrefetch: true,
}) as unknown as typeof controller.ttsClient.getCapabilities;
await controller.preloadNextSSML();
expect(controller.ttsClient.speak).toHaveBeenCalledTimes(6);
});
test('a windowed client preloads into the next chapter when this one ends', async () => {
// The section ends after one more paragraph: the next section's opening
// (the throwaway foliate TTS starts at "hello") follows it.
mockView.tts = {
next: vi.fn().mockReturnValueOnce('<speak>last</speak>').mockReturnValue(undefined),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
controller.ttsClient.getCapabilities = vi.fn().mockReturnValue({
wordBoundaries: true,
mediaClock: true,
gapControl: true,
liveRateChange: false,
windowedPrefetch: true,
}) as unknown as typeof controller.ttsClient.getCapabilities;
await controller.preloadNextSSML();
const preloaded = vi.mocked(controller.ttsClient.speak).mock.calls.map(([ssml]) => ssml);
expect(preloaded[0]).toContain('last');
expect(preloaded[1]).toContain('hello');
});
test('other clients never preload past the chapter', async () => {
mockView.tts = {
next: vi.fn().mockReturnValueOnce('<speak>last</speak>').mockReturnValue(undefined),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
const sections = (
mockView.book as unknown as { sections: { createDocument: ReturnType<typeof vi.fn> }[] }
).sections;
for (const s of sections) s.createDocument.mockClear();
await controller.preloadNextSSML();
expect(controller.ttsClient.speak).toHaveBeenCalledTimes(1);
expect(sections.some((s) => s.createDocument.mock.calls.length > 0)).toBe(false);
});
test('other clients keep preloading four paragraphs', async () => {
mockView.tts = {
next: vi.fn().mockReturnValue(`<speak>${'a'.repeat(450)}</speak>`),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
await controller.preloadNextSSML();
expect(controller.ttsClient.speak).toHaveBeenCalledTimes(4);
});
test('a voice change withdraws the preloads queued under the old voice', async () => {
// A windowed provider keeps queued preloads until their signal aborts:
// left alive, old-voice sentences keep reaching the worker after the
// switch, preempting the new voice's buffer and charging the quota.
mockView.tts = {
next: vi.fn().mockReturnValueOnce('<speak>one</speak>').mockReturnValue(undefined),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
await controller.preloadNextSSML(1);
const [, signal] = vi.mocked(controller.ttsClient.speak).mock.calls[0]!;
expect((signal as AbortSignal).aborted).toBe(false);
controller.ttsEdgeVoices = [{ id: 'edge-voice-1', name: 'Edge Voice', lang: 'en-US' }];
await controller.setVoice('edge-voice-1', 'en');
expect((signal as AbortSignal).aborted).toBe(true);
});
test('stopping withdraws queued preloads', async () => {
mockView.tts = {
next: vi.fn().mockReturnValueOnce('<speak>one</speak>').mockReturnValue(undefined),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
await controller.preloadNextSSML(1);
const [, signal] = vi.mocked(controller.ttsClient.speak).mock.calls[0]!;
await controller.stop();
expect((signal as AbortSignal).aborted).toBe(true);
});
test('a paragraph handover keeps queued preloads', async () => {
// Each paragraph's speak starts with stop(true): withdrawing there would
// drop the next paragraphs' audio at every paragraph boundary.
mockView.tts = {
next: vi.fn().mockReturnValueOnce('<speak>one</speak>').mockReturnValue(undefined),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
await controller.preloadNextSSML(1);
const [, signal] = vi.mocked(controller.ttsClient.speak).mock.calls[0]!;
await controller.stop(true);
expect((signal as AbortSignal).aborted).toBe(false);
});
test('preloads the next paragraphs one after another, in reading order', async () => {
// A windowed provider queues preloads in the order they reach it: the
// paragraph read next must not land behind a later one.
mockView.tts = {
next: vi
.fn()
.mockReturnValueOnce('<speak>one</speak>')
.mockReturnValueOnce('<speak>two</speak>')
.mockReturnValue(undefined),
prev: vi.fn(),
doc: {},
} as unknown as FoliateView['tts'];
const order: string[] = [];
vi.mocked(controller.ttsClient.speak).mockImplementation((ssml: string) => {
const name = ssml.includes('one') ? 'one' : 'two';
order.push(`start ${name}`);
return (async function* () {
await new Promise((r) => setTimeout(r, name === 'one' ? 20 : 0));
order.push(`end ${name}`);
})();
});
await controller.preloadNextSSML(2);
expect(order).toEqual(['start one', 'end one', 'start two', 'end two']);
});
test('calls tts.next() and tts.prev() synchronously without async gaps between them', async () => {
// This test verifies the fix for a race condition where async gaps between
// tts.next() calls in preloadNextSSML allowed #speak() to interleave and
@ -2122,7 +2374,9 @@ describe('TTSController', () => {
// Between a sentence's mark and its first word boundary a page relocate
// triggers a re-apply; the whole sentence must not flash in.
controller.reapplyCurrentHighlight();
expect(content.overlayer.add).not.toHaveBeenCalled();
expect(content.overlayer.add.mock.calls.map((call) => call[0])).not.toContain(
'tts-highlight',
);
// Paused keeps the sentence re-draw (deliberate navigation UX).
controller.state = 'paused';

View file

@ -122,4 +122,43 @@ describe('TTSDownloader', () => {
expect(result.completed).not.toContain(1);
expect(enumerator.enumerateSection).not.toHaveBeenCalledWith(1);
});
test('hands each section to a windowed warmer before warming it', async () => {
enumerated[0] = [sentence(0, 'A.'), sentence(1, 'B.')];
enumerated[1] = [sentence(0, 'C.')];
const order: string[] = [];
const prefetchSentences = vi.fn(async (sentences: { lang: string; text: string }[]) => {
order.push(`prefetch:${sentences.map((s) => s.text).join(',')}`);
});
vi.mocked(warmer.warmSentence).mockImplementation(async (_s, _o, _l, text) => {
order.push(`warm:${text}`);
return true;
});
const signal = new AbortController().signal;
await new TTSDownloader(enumerator, { ...warmer, prefetchSentences }).download(
[0, 1],
undefined,
signal,
);
expect(order).toEqual(['prefetch:A.,B.', 'warm:A.', 'warm:B.', 'prefetch:C.', 'warm:C.']);
expect(prefetchSentences).toHaveBeenCalledWith(
[
{ lang: 'en', text: 'A.' },
{ lang: 'en', text: 'B.' },
],
signal,
);
});
test('a fatal synthesis failure (quota) ends the whole download', async () => {
const { SpeechSynthesisFatalError } = await import('@/services/tts/providers/types');
enumerated[0] = [sentence(0, 'A.'), sentence(1, 'B.')];
enumerated[1] = [sentence(0, 'C.')];
vi.mocked(warmer.warmSentence).mockRejectedValueOnce(
new SpeechSynthesisFatalError('DAILY_QUOTA_EXCEEDED'),
);
await expect(new TTSDownloader(enumerator, warmer).download([0, 1])).rejects.toThrow(
'DAILY_QUOTA_EXCEEDED',
);
expect(warmer.warmSentence).toHaveBeenCalledTimes(1);
});
});

View file

@ -37,11 +37,9 @@ const noopStore = {
};
vi.mock('@/services/tts/providers/bookCacheStore', () => ({
getTTSCacheConfig: vi.fn(() => ({ enabled: cacheEnabled, budgetMB: 200, syncEnabled: false })),
BookTTSCacheStore: class {
get = noopStore.get;
put = noopStore.put;
close = noopStore.close;
},
createBookTTSCacheStore: vi.fn((appService: unknown) =>
appService && cacheEnabled ? { ...noopStore } : null,
),
}));
import { EdgeTTSClient } from '@/services/tts/EdgeTTSClient';

View file

@ -45,6 +45,9 @@ vi.mock('@/services/tts/WebSpeechClient', () => ({
}),
}));
vi.mock('@/services/tts/EdgeTTSClient', () => ({
// constants.ts imports this named const from the same module; the mock
// factory replaces the whole module, so it must re-export it too.
DEFAULT_SENTENCE_GAP_SEC: 0.15,
EdgeTTSClient: vi.fn().mockImplementation(function (this: Record<string, unknown>) {
Object.assign(this, makeMockClient('edge-tts'));
}),

View file

@ -0,0 +1,612 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const m = vi.hoisted(() => ({
fetchWithAuth: vi.fn(),
getAccessToken: vi.fn(),
getSubscriptionPlan: vi.fn(),
}));
vi.mock('@/utils/fetch', () => ({ fetchWithAuth: m.fetchWithAuth }));
vi.mock('@/services/environment', async (orig) => ({
...(await orig<typeof import('@/services/environment')>()),
getAPIBaseUrl: () => 'https://web.test/api',
}));
vi.mock('@/utils/access', async (orig) => ({
...(await orig<typeof import('@/utils/access')>()),
getAccessToken: m.getAccessToken,
getSubscriptionPlan: m.getSubscriptionPlan,
}));
import { ReadestVoiceProvider } from '@/services/tts/providers/readest';
import {
SpeechSynthesisFatalError,
SpeechSynthesisPermanentError,
type SpeechSynthesisRequest,
} from '@/services/tts/providers/types';
const VOICES = [{ id: 'kokoro:af_heart', name: 'Heart', lang: 'en-US', tier: 'plus' }];
const B = [{ offset: 0, duration: 5_000_000, text: 'Hello' }];
const AUDIO_B64 = btoa('mp3!');
const req = (text: string, lang = 'en-US'): SpeechSynthesisRequest => ({
lang,
text,
voice: 'kokoro:af_heart',
pitch: 1,
});
const reqs = (n: number, prefix = 'S') =>
Array.from({ length: n }, (_, i) => req(`${prefix}${i}.`));
const flush = async (times = 3) => {
for (let i = 0; i < times; i++) await new Promise((r) => setTimeout(r, 0));
};
interface WindowCall {
body: {
client: string;
lane: string;
lang: string;
segments: { id: string; text: string; voice: string }[];
};
signal: AbortSignal;
// Push NDJSON lines into the response body; end closes it.
send: (line: unknown) => void;
end: () => void;
// Answer every segment with audio, then done.
completeAll: () => void;
}
interface JobCall {
body: WindowCall['body'];
id: string;
polls: number;
deleted: boolean;
// Answers the poll in flight: still running, the result, or an error code.
running: () => void;
complete: () => void;
fail: (code: string) => void;
}
// Download jobs (null: the server has none, as off Workers).
let jobs: JobCall[] | null;
const jobResult = (body: WindowCall['body']) =>
new Response(
[
...body.segments.map((s) => ({ id: s.id, audio: AUDIO_B64, boundaries: B })),
{ done: true, charged: 1 },
]
.map((line) => `${JSON.stringify(line)}\n`)
.join(''),
);
const handleJobs = (url: string, init: RequestInit): Promise<Response> => {
if (!jobs) return Promise.reject(new Error('JOBS_UNAVAILABLE'));
const all = jobs;
if (init.method === 'POST') {
const body = JSON.parse(init.body as string);
let poll: { resolve: (res: Response) => void; reject: (error: unknown) => void } | null = null;
const job: JobCall = {
body,
id: `job${all.length}`,
polls: 0,
deleted: false,
running: () => poll?.resolve(Response.json({ state: 'leased' }, { status: 202 })),
complete: () => poll?.resolve(jobResult(body)),
fail: (code) => poll?.reject(new Error(code)),
};
(job as JobCall & { setPoll: (p: typeof poll) => void }).setPoll = (p) => (poll = p);
all.push(job);
return Promise.resolve(Response.json({ jobId: job.id, state: 'queued' }));
}
const job = all.find((j) => url.endsWith(`/jobs/${j.id}`))!;
if (init.method === 'DELETE') {
job.deleted = true;
return Promise.resolve(new Response(null, { status: 204 }));
}
job.polls += 1;
return new Promise((resolve, reject) => {
(job as JobCall & { setPoll: (p: unknown) => void }).setPoll({ resolve, reject });
init.signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
});
};
// fetchWithAuth stand-in: GET voices answers at once; each window POST returns
// a streamed NDJSON body the test drives through the recorded WindowCall;
// download jobs go through handleJobs.
const installFetch = () => {
const windows: WindowCall[] = [];
m.fetchWithAuth.mockImplementation(async (url: string, init: RequestInit) => {
if (url.includes('/tts/readest/jobs')) return handleJobs(url, init);
if (!init.method || init.method === 'GET') return Response.json({ voices: VOICES });
const body = JSON.parse(init.body as string);
if (body.warmup) return Response.json({ ok: true });
let controller!: ReadableStreamDefaultController<Uint8Array>;
const stream = new ReadableStream<Uint8Array>({ start: (c) => void (controller = c) });
const encoder = new TextEncoder();
const call: WindowCall = {
body,
signal: init.signal as AbortSignal,
send: (line) => controller.enqueue(encoder.encode(`${JSON.stringify(line)}\n`)),
end: () => controller.close(),
completeAll: () => {
for (const s of body.segments) call.send({ id: s.id, audio: AUDIO_B64, boundaries: B });
call.send({ done: true, charged: 1 });
call.end();
},
};
call.signal?.addEventListener('abort', () =>
controller.error(new DOMException('Aborted', 'AbortError')),
);
expect(url).toBe('https://web.test/api/tts/readest/stream');
windows.push(call);
return new Response(stream);
});
return windows;
};
const texts = (call: WindowCall) => call.body.segments.map((s) => s.text);
let windows: WindowCall[];
let events: EventTarget;
let provider: ReadestVoiceProvider;
beforeEach(() => {
for (const fn of Object.values(m)) fn.mockReset();
m.getAccessToken.mockResolvedValue('tok');
m.getSubscriptionPlan.mockReturnValue('plus');
windows = installFetch();
jobs = null;
events = new EventTarget();
provider = new ReadestVoiceProvider(events);
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
describe('voices and init', () => {
it('makes no request without a token or without a TTS plan', async () => {
m.getAccessToken.mockResolvedValue(null);
expect(await provider.getAllVoices()).toEqual([]);
expect(await provider.init()).toBe(false);
m.getAccessToken.mockResolvedValue('tok');
m.getSubscriptionPlan.mockReturnValue('purchase');
const other = new ReadestVoiceProvider(events);
expect(await other.getAllVoices()).toEqual([]);
expect(await other.init()).toBe(false);
expect(m.fetchWithAuth).not.toHaveBeenCalled();
});
it('fetches the plan voices once for getAllVoices + init', async () => {
expect(await provider.getAllVoices()).toEqual(VOICES);
expect(await provider.init()).toBe(true);
expect(m.fetchWithAuth).toHaveBeenCalledTimes(1);
expect(m.fetchWithAuth).toHaveBeenCalledWith('https://web.test/api/tts/readest', {
method: 'GET',
});
});
it('treats a failing voices request (kill switch, lapsed plan) as unavailable', async () => {
m.fetchWithAuth.mockRejectedValueOnce(new Error('NOT_CONFIGURED'));
expect(await provider.getAllVoices()).toEqual([]);
expect(await provider.init()).toBe(false);
});
it('fires the warmup at most once', async () => {
provider.warmup();
provider.warmup();
await flush();
const posts = m.fetchWithAuth.mock.calls.filter(([, init]) => init.method === 'POST');
expect(posts).toHaveLength(1);
expect(JSON.parse(posts[0]![1].body)).toEqual({ warmup: true });
});
});
describe('listen windows', () => {
it('grows windows 1 -> 4 -> 8 and keeps one listen window in flight', async () => {
const signal = new AbortController().signal;
provider.prefetch(reqs(21), 'listen', signal);
await flush();
expect(windows).toHaveLength(1);
expect(texts(windows[0]!)).toEqual(['S0.']);
provider.prefetch(reqs(21), 'listen', signal); // duplicates are ignored
await flush();
expect(windows).toHaveLength(1);
for (const expected of [4, 8, 8]) {
windows.at(-1)!.completeAll();
await flush();
expect(texts(windows.at(-1)!)).toHaveLength(expected);
}
expect(windows.map((w) => w.body.lane)).toEqual(['listen', 'listen', 'listen', 'listen']);
});
it('caps a listen window at about 20 s of estimated audio', async () => {
// 150 Latin chars is about 10 s at the default estimate: two fit, three do
// not. A due sentence waits behind the window in flight, so it stays short.
const signal = new AbortController().signal;
const long = Array.from({ length: 8 }, (_, i) => req(`${i}`.padEnd(150, 'a')));
provider.prefetch(long, 'listen', signal);
await flush();
expect(texts(windows[0]!)).toHaveLength(1);
for (const expected of [2, 2]) {
windows.at(-1)!.completeAll();
await flush();
expect(texts(windows.at(-1)!)).toHaveLength(expected);
}
});
it('lets a window of background preloads hold about a minute of audio', async () => {
// Nobody is waiting on these sentences: a bigger window amortizes the
// per-request overhead and lets the GPU batch them.
const signal = new AbortController().signal;
const long = Array.from({ length: 8 }, (_, i) => req(`${i}`.padEnd(150, 'a')));
provider.prefetch(long, 'listen', signal, { background: true });
await flush();
expect(texts(windows[0]!)).toHaveLength(1);
for (const expected of [4, 3]) {
windows.at(-1)!.completeAll();
await flush();
expect(texts(windows.at(-1)!)).toHaveLength(expected);
}
});
it('frees the lane once every sentence of the window has arrived', async () => {
// The stream's terminal line waits on the job's final status, seconds
// after the last audio: the next window must not wait for it.
const signal = new AbortController().signal;
provider.prefetch(reqs(3), 'listen', signal);
await flush();
windows[0]!.send({ id: windows[0]!.body.segments[0]!.id, audio: AUDIO_B64, boundaries: B });
await flush();
expect(windows).toHaveLength(2);
expect(texts(windows[1]!)).toEqual(['S1.', 'S2.']);
});
it('resolves each sentence as its line arrives, before the stream ends', async () => {
const signal = new AbortController().signal;
provider.prefetch(reqs(1), 'listen', signal);
const result = provider.synthesize(req('S0.'), signal);
await flush();
windows[0]!.send({ id: windows[0]!.body.segments[0]!.id, audio: AUDIO_B64, boundaries: B });
const { audio, boundaries } = await result;
expect(new TextDecoder().decode(audio)).toBe('mp3!');
expect(boundaries).toEqual(B);
});
it('synthesize without a prefetch issues a one-sentence window', async () => {
const result = provider.synthesize(req('Alone.'), new AbortController().signal);
await flush();
expect(texts(windows[0]!)).toEqual(['Alone.']);
windows[0]!.completeAll();
await expect(result).resolves.toBeTruthy();
});
it('maps an error line to a permanent failure for that sentence only', async () => {
const signal = new AbortController().signal;
const a = provider.synthesize(req('A.'), signal);
await flush();
windows[0]!.completeAll();
await a;
provider.prefetch([req('B.'), req('C.')], 'listen', signal);
const b = provider.synthesize(req('B.'), signal);
const c = provider.synthesize(req('C.'), signal);
await flush();
const [sb, sc] = windows[1]!.body.segments;
windows[1]!.send({ id: sb!.id, error: 'synthesis failed' });
windows[1]!.send({ id: sc!.id, audio: AUDIO_B64, boundaries: B });
windows[1]!.send({ done: true, charged: 2 });
windows[1]!.end();
await expect(b).rejects.toBeInstanceOf(SpeechSynthesisPermanentError);
await expect(c).resolves.toBeTruthy();
});
it('fails unanswered sentences transiently when the window ends early', async () => {
const result = provider.synthesize(req('A.'), new AbortController().signal);
await flush();
windows[0]!.send({ done: true, charged: 0, error: 'UPSTREAM_FAILED' });
windows[0]!.end();
const error = await result.catch((e: unknown) => e);
expect(error).toBeInstanceOf(Error);
expect(error).not.toBeInstanceOf(SpeechSynthesisPermanentError);
expect(error).not.toBeInstanceOf(SpeechSynthesisFatalError);
});
it('never mixes languages in one window', async () => {
const signal = new AbortController().signal;
provider.synthesize(req('First.'), signal).catch(() => {});
await flush();
provider.prefetch([req('A.'), req('Bonjour.', 'fr-FR'), req('C.')], 'listen', signal);
windows[0]!.completeAll();
await flush();
expect(texts(windows[1]!)).toEqual(['A.']);
expect(windows[1]!.body.lang).toBe('en-US');
});
it('a background synthesize (cache fill) leaves a preload in the background', async () => {
const signal = new AbortController().signal;
provider.synthesize(req('First.'), signal).catch(() => {});
await flush();
const preload = new AbortController().signal;
provider.prefetch([req('P0.'), req('P1.')], 'listen', preload, { background: true });
provider.synthesize(req('P0.'), preload, { background: true }).catch(() => {});
provider.prefetch([req('F0.')], 'listen', signal);
windows[0]!.completeAll();
await flush();
expect(texts(windows[1]!)).toEqual(['F0.', 'P0.', 'P1.']);
});
it('reports each prefetched sentence to onDelivered as it arrives', async () => {
const onDelivered = vi.fn();
provider.prefetch([req('A.'), req('B.')], 'listen', new AbortController().signal, {
onDelivered,
});
await flush();
windows[0]!.completeAll();
await flush();
expect(onDelivered).toHaveBeenCalledWith(req('A.'), expect.objectContaining({ boundaries: B }));
expect(onDelivered).toHaveBeenCalledTimes(1);
});
it('fills windows with foreground requests before background preloads', async () => {
const signal = new AbortController().signal;
provider.synthesize(req('First.'), signal).catch(() => {});
await flush();
provider.prefetch([req('P0.'), req('P1.')], 'listen', new AbortController().signal, {
background: true,
});
provider.prefetch([req('F0.'), req('F1.')], 'listen', signal);
windows[0]!.completeAll();
await flush();
expect(texts(windows[1]!)).toEqual(['F0.', 'F1.', 'P0.', 'P1.']);
});
});
describe('prefetched sentences', () => {
it('keeps a delivered sentence for playback after its window ends', async () => {
provider.prefetch([req('S0.')], 'listen', new AbortController().signal);
await flush();
windows[0]!.completeAll();
await flush();
// Playback reaches the sentence later: no second synthesis (or charge).
const result = await provider.synthesize(req('S0.'), new AbortController().signal);
expect(result.audio.byteLength).toBeGreaterThan(0);
expect(windows).toHaveLength(1);
});
});
describe('cancellation', () => {
it('a stop/seek withdraws queued sentences, aborts the window, and restarts at size 1', async () => {
const first = new AbortController();
provider.prefetch(reqs(10), 'listen', first.signal);
const s0 = provider.synthesize(req('S0.'), first.signal);
await flush();
windows[0]!.completeAll();
await s0;
await flush();
expect(texts(windows[1]!)).toHaveLength(4);
const queued = provider.synthesize(req('S9.'), first.signal);
first.abort();
await expect(queued).rejects.toMatchObject({ name: 'AbortError' });
expect(windows[1]!.signal.aborted).toBe(true);
const second = new AbortController();
provider.prefetch(reqs(3, 'T'), 'listen', second.signal);
await flush();
expect(texts(windows[2]!)).toEqual(['T0.']);
});
it('a paragraph handover keeps the window size', async () => {
// Each paragraph's speak signal aborts when the next paragraph starts. Its
// sentences stay wanted by the background preload, so nothing is withdrawn
// and the window must not shrink back to one sentence at every paragraph.
const preload = new AbortController();
provider.prefetch(reqs(20, 'P'), 'listen', preload.signal, { background: true });
await flush();
windows[0]!.completeAll();
await flush();
expect(texts(windows[1]!)).toHaveLength(4);
const paragraph = new AbortController();
provider.prefetch(reqs(5, 'P').slice(1), 'listen', paragraph.signal);
windows[1]!.completeAll();
await flush();
expect(texts(windows[2]!)).toHaveLength(8);
paragraph.abort();
windows[2]!.completeAll();
await flush();
expect(texts(windows[3]!)).toHaveLength(7);
});
it('keeps a window running while another caller still wants its sentences', async () => {
const a = new AbortController();
const b = new AbortController();
provider.prefetch([req('X.')], 'listen', a.signal);
const wanted = provider.synthesize(req('X.'), b.signal);
await flush();
a.abort();
expect(windows[0]!.signal.aborted).toBe(false);
windows[0]!.completeAll();
await expect(wanted).resolves.toBeTruthy();
});
it('a foreground request preempts a window of background preloads', async () => {
provider.prefetch(reqs(2, 'P'), 'listen', new AbortController().signal, { background: true });
await flush();
expect(texts(windows[0]!)).toEqual(['P0.']);
const now = provider.synthesize(req('Now.'), new AbortController().signal);
await flush();
expect(windows[0]!.signal.aborted).toBe(true);
expect(texts(windows[1]!)).toEqual(['Now.']);
windows[1]!.completeAll();
await now;
await flush();
// The preempted preload is queued again.
expect(texts(windows[2]!)).toEqual(['P0.', 'P1.']);
});
});
describe('errors', () => {
it('a quota rejection is fatal for everything, fires one event, and stops requesting', async () => {
const quota = vi.fn();
events.addEventListener('tts-quota-exceeded', quota);
m.fetchWithAuth.mockImplementation(async (_url: string, init: RequestInit) => {
if (init.method === 'POST') throw new Error('DAILY_QUOTA_EXCEEDED');
return Response.json({ voices: VOICES });
});
const signal = new AbortController().signal;
provider.prefetch(reqs(3), 'listen', signal);
const results = [0, 1, 2].map((i) => provider.synthesize(req(`S${i}.`), signal));
for (const r of results) await expect(r).rejects.toBeInstanceOf(SpeechSynthesisFatalError);
await expect(provider.synthesize(req('Later.'), signal)).rejects.toBeInstanceOf(
SpeechSynthesisFatalError,
);
expect(quota).toHaveBeenCalledTimes(1);
expect(m.fetchWithAuth).toHaveBeenCalledTimes(1);
expect(await provider.init()).toBe(true); // a new session may have fresh quota
await flush();
provider.synthesize(req('Tomorrow.'), signal).catch(() => {});
await flush();
expect(m.fetchWithAuth.mock.calls.filter(([, i]) => i.method === 'POST')).toHaveLength(2);
});
it.each([
'UNKNOWN_VOICE',
'VOICE_TIER_REQUIRED',
'INVALID_INPUT',
])('maps %s to a permanent failure for the window', async (code) => {
m.fetchWithAuth.mockRejectedValueOnce(new Error(code));
const result = provider.synthesize(req('A.'), new AbortController().signal);
await expect(result).rejects.toBeInstanceOf(SpeechSynthesisPermanentError);
});
it('rejects an empty voice permanently without a request', async () => {
const result = provider.synthesize({ ...req('A.'), voice: '' }, new AbortController().signal);
await expect(result).rejects.toBeInstanceOf(SpeechSynthesisPermanentError);
expect(m.fetchWithAuth).not.toHaveBeenCalled();
});
});
describe('download lane, streamed (no jobs on the server)', () => {
it('uses windows of up to 64 sentences', async () => {
provider.prefetch(reqs(70), 'download', new AbortController().signal);
await flush();
expect(windows[0]!.body.lane).toBe('download');
expect(texts(windows[0]!)).toHaveLength(64);
windows[0]!.completeAll();
await flush();
expect(texts(windows[1]!)).toHaveLength(6);
});
it('names its app instance on every window, so the server queues devices apart', async () => {
const other = new ReadestVoiceProvider(events);
provider.prefetch(reqs(1, 'D'), 'download', new AbortController().signal);
provider.prefetch(reqs(1, 'L'), 'listen', new AbortController().signal);
other.prefetch(reqs(1, 'O'), 'listen', new AbortController().signal);
await flush();
const client = (prefix: string) =>
windows.find((w) => w.body.segments[0]!.text.startsWith(prefix))!.body.client;
expect(client('D')).toEqual(expect.any(String));
expect(client('L')).toBe(client('D'));
expect(client('O')).not.toBe(client('D'));
});
it('runs alongside a listen window', async () => {
provider.prefetch(reqs(2, 'D'), 'download', new AbortController().signal);
provider.prefetch(reqs(1, 'L'), 'listen', new AbortController().signal);
await flush();
expect(windows.map((w) => w.body.lane).sort()).toEqual(['download', 'listen']);
});
it('waits and retries the same window after BUSY', async () => {
vi.useFakeTimers();
m.fetchWithAuth.mockRejectedValueOnce(new Error('BUSY'));
provider.prefetch(reqs(2, 'D'), 'download', new AbortController().signal);
await vi.advanceTimersByTimeAsync(0);
expect(m.fetchWithAuth).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(5000);
expect(texts(windows[0]!)).toEqual(['D0.', 'D1.']);
});
});
describe('download jobs', () => {
beforeEach(() => {
jobs = [];
});
const all = () => jobs!;
it('submits windows of up to 64 sentences as jobs, four at a time', async () => {
provider.prefetch(reqs(300), 'download', new AbortController().signal);
await flush();
expect(all().map((j) => j.body.segments.length)).toEqual([64, 64, 64, 64]);
expect(all()[0]!.body).toMatchObject({ lane: 'download', lang: 'en-US' });
expect(windows).toHaveLength(0);
all()[1]!.complete();
await flush();
expect(all().map((j) => j.body.segments.length)).toEqual([64, 64, 64, 64, 44]);
});
it('resolves sentences from the result once the job is done, polling meanwhile', async () => {
const delivered: string[] = [];
provider.prefetch(reqs(2, 'D'), 'download', new AbortController().signal, {
onDelivered: (r) => delivered.push(r.text),
});
await flush();
const [job] = all();
expect(job!.polls).toBe(1);
job!.running();
await flush();
expect(job!.polls).toBe(2);
expect(delivered).toEqual([]);
job!.complete();
await flush();
expect(delivered).toEqual(['D0.', 'D1.']);
});
it('cancels the job when nobody wants it any more', async () => {
const controller = new AbortController();
provider.prefetch(reqs(2, 'D'), 'download', controller.signal);
await flush();
controller.abort();
await flush();
expect(all()[0]!.deleted).toBe(true);
});
it('submits a window again when its job was cancelled elsewhere or is gone', async () => {
provider.prefetch(reqs(2, 'D'), 'download', new AbortController().signal);
await flush();
all()[0]!.fail('CANCELLED');
await flush();
expect(all()).toHaveLength(2);
all()[1]!.fail('NOT_FOUND');
await flush();
expect(all()).toHaveLength(3);
expect(all()[2]!.body.segments).toEqual(all()[0]!.body.segments);
});
it('fails the sentences of a failed job', async () => {
provider.prefetch([req('D0.')], 'download', new AbortController().signal);
// Playback reaches the sentence while its job runs: it shares the job.
const result = provider.synthesize(req('D0.'), new AbortController().signal);
await flush();
all()[0]!.fail('UPSTREAM_FAILED');
await expect(result).rejects.toThrow('UPSTREAM_FAILED');
expect(windows).toHaveLength(0);
});
it('streams downloads instead when the server has no jobs', async () => {
jobs = null;
provider.prefetch(reqs(300), 'download', new AbortController().signal);
await flush();
expect(windows).toHaveLength(1);
expect(windows[0]!.body.lane).toBe('download');
windows[0]!.completeAll();
await flush();
// Remembered: the next window streams without asking for a job again.
expect(windows).toHaveLength(2);
const asked = m.fetchWithAuth.mock.calls.filter(([url]) => String(url).includes('/jobs'));
expect(asked).toHaveLength(1);
});
});

View file

@ -43,6 +43,31 @@ describe('SectionTimeline', () => {
expect(sentences[3]!.text.trim()).toBe(SENTENCE_B1);
});
test('buffered extent runs from a sentence through its measured successors', () => {
const voice = 'timeline-voice-buffered';
const sentences = enumerate(makeDoc());
recordMeasuredDuration(voice, sentences[1]!.text, 10);
recordMeasuredDuration(voice, sentences[2]!.text, 10);
const timeline = new SectionTimeline(sentences, 'en', voice);
const total = timeline.getDuration();
// Playing sentence 1: it and sentence 2 are synthesized, sentence 3 is not.
expect(timeline.getBufferedFraction(1)).toBeCloseTo((timeline.positionAt(1) + 20) / total, 6);
// Playing an unsynthesized sentence: nothing is buffered past its start.
expect(timeline.getBufferedFraction(0)).toBe(0);
});
test('a sentence with nothing to speak does not stop the buffered extent', () => {
// Segmentation can leave a punctuation-only fragment (" ? "): it is never
// synthesized, so it is never measured, yet audio after it is buffered.
const voice = 'timeline-voice-unspeakable';
const sentences = enumerate(makeDoc());
sentences[1] = { ...sentences[1]!, text: ' ? ' };
recordMeasuredDuration(voice, sentences[0]!.text, 10);
recordMeasuredDuration(voice, sentences[2]!.text, 10);
const timeline = new SectionTimeline(sentences, 'en', voice);
expect(timeline.getBufferedFraction(0)).toBeCloseTo(20 / timeline.getDuration(), 6);
});
test('mixes measured and estimated durations after refresh', () => {
const voice = 'timeline-voice-mixed';
const sentences = enumerate(makeDoc());

View file

@ -49,6 +49,23 @@ describe('WebAudioPlayer scheduling', () => {
]);
});
test('a chunk scheduled after its predecessor ended fires its chunk-start then', async () => {
// Its audio arrived late (synthesis still pending when the previous
// sentence finished): nothing announces it at the prior onended, so the
// schedule must, or the sentence plays with no mark and no word highlight.
const { ctx, player, events, onEvent } = setup();
await player.ensureContext();
const gen = player.startSession(onEvent);
player.scheduleChunk(gen, makeBuffer(2), { trimStartSec: 0, mediaScale: 1, gapSec: 0.2 });
await ctx.advanceTo(SAFETY + 3);
expect(events).toEqual([{ type: 'chunk-start', chunkIndex: 0 }]);
player.scheduleChunk(gen, makeBuffer(1), { trimStartSec: 0, mediaScale: 1, gapSec: 0.2 });
expect(events).toEqual([
{ type: 'chunk-start', chunkIndex: 0 },
{ type: 'chunk-start', chunkIndex: 1 },
]);
});
test('stale-generation scheduleChunk is a no-op', async () => {
const { ctx, player, events, onEvent } = setup();
await player.ensureContext();
@ -341,14 +358,15 @@ describe('WebAudioPlayer playback position', () => {
expect(pos?.mediaTimeSec).toBeCloseTo(0.3 + 1 * 1.5, 3);
});
test('clamps before the first chunk and in the inter-chunk gap', async () => {
test('runs before the first chunk starts and clamps in the inter-chunk gap', async () => {
const { ctx, player, onEvent } = setup();
await player.ensureContext();
const gen = player.startSession(onEvent);
player.scheduleChunk(gen, makeBuffer(1), { trimStartSec: 0.2, mediaScale: 1, gapSec: 1 });
player.scheduleChunk(gen, makeBuffer(1), { trimStartSec: 0.1, mediaScale: 1, gapSec: 1 });
// Before the first chunk starts.
expect(player.getPlaybackPosition(gen)?.mediaTimeSec).toBeCloseTo(0.2, 5);
// Before the first chunk starts: still short of its first word, which
// must not light during the pause before the audio.
expect(player.getPlaybackPosition(gen)?.mediaTimeSec).toBeCloseTo(0.2 - SAFETY, 5);
// Inside the gap after chunk 0 (ends at SAFETY+1; next starts SAFETY+2).
ctx.currentTime = SAFETY + 1.5;
const pos = player.getPlaybackPosition(gen);
@ -356,6 +374,17 @@ describe('WebAudioPlayer playback position', () => {
expect(pos?.mediaTimeSec).toBeCloseTo(0.2 + 1, 5);
});
test('trails the context clock by the output latency', async () => {
const { ctx, player, onEvent } = setup();
await player.ensureContext();
const gen = player.startSession(onEvent);
player.scheduleChunk(gen, makeBuffer(2), { trimStartSec: 0, mediaScale: 1, gapSec: 0 });
// The speakers play what the clock rendered 50 ms ago.
Object.assign(ctx, { outputLatency: 0.05 });
await ctx.advanceTo(SAFETY + 1);
expect(player.getPlaybackPosition(gen)?.mediaTimeSec).toBeCloseTo(0.95, 5);
});
test('returns null for a stale generation or empty session', async () => {
const { player, onEvent } = setup();
await player.ensureContext();

View file

@ -1,5 +1,6 @@
import { describe, test, it, expect } from 'vitest';
import {
alignBoundariesToSpeech,
computeWordOffsets,
findBoundaryIndexAtTime,
getTextSubRange,
@ -85,6 +86,31 @@ describe('findBoundaryIndexAtTime', () => {
});
});
describe('alignBoundariesToSpeech', () => {
// A forced aligner can put the first word inside the leading silence. The
// player trims that silence, so the second word lit up almost as soon as the
// first one became audible.
const boundaries = [
{ offset: 2_210_000, duration: 200_000, text: '从' },
{ offset: 4_010_000, duration: 200_000, text: '一' },
{ offset: 5_610_000, duration: 2_610_000, text: '开始' },
];
test('shifts every word so the first starts with the speech', () => {
expect(alignBoundariesToSpeech(boundaries, 0.3).map((b) => b.offset)).toEqual([
3_000_000, 4_800_000, 6_400_000,
]);
});
test('keeps boundaries whose first word starts after the speech', () => {
expect(alignBoundariesToSpeech(boundaries, 0.2)).toBe(boundaries);
});
test('keeps an empty list', () => {
expect(alignBoundariesToSpeech([], 0.3)).toEqual([]);
});
});
describe('getTextSubRange', () => {
const makeBaseRange = (html: string) => {
document.body.innerHTML = html;

View file

@ -0,0 +1,29 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getTTSQuota, isTTSInPlan, TTS_PLANS } from '@/utils/access';
describe('TTS plan gating', () => {
it('includes exactly plus and pro', () => {
expect(TTS_PLANS).toEqual(['plus', 'pro']);
expect(isTTSInPlan('plus')).toBe(true);
expect(isTTSInPlan('pro')).toBe(true);
expect(isTTSInPlan('free')).toBe(false);
expect(isTTSInPlan('purchase')).toBe(false);
});
});
describe('getTTSQuota', () => {
afterEach(() => vi.unstubAllEnvs());
it('returns per-plan daily character quotas', () => {
expect(getTTSQuota('plus')).toBe(100 * 1024);
expect(getTTSQuota('pro')).toBe(300 * 1024);
expect(getTTSQuota('free')).toBe(0);
expect(getTTSQuota('purchase')).toBe(0);
});
it('honors the TTS_FIXED_QUOTA env override', () => {
vi.stubEnv('TTS_FIXED_QUOTA', '12345');
expect(getTTSQuota('plus')).toBe(12345);
expect(getTTSQuota('free')).toBe(12345);
});
});

View file

@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import { readNDJSON } from '@/utils/ndjson';
const streamOf = (chunks: (string | Uint8Array)[]) => {
const encoder = new TextEncoder();
return new ReadableStream<Uint8Array>({
start(controller) {
for (const c of chunks) controller.enqueue(typeof c === 'string' ? encoder.encode(c) : c);
controller.close();
},
});
};
const collect = async (body: ReadableStream<Uint8Array>) => {
const out: unknown[] = [];
for await (const v of readNDJSON(body)) out.push(v);
return out;
};
describe('readNDJSON', () => {
it('parses lines split across chunks', async () => {
expect(await collect(streamOf(['{"a":', '1}\n{"b"', ':2}\n']))).toEqual([{ a: 1 }, { b: 2 }]);
});
it('handles a multi-byte character split across chunks', async () => {
const bytes = new TextEncoder().encode('{"text":"你好"}\n');
// Split inside the 3-byte encoding of 你.
const cut = bytes.indexOf(0xe4) + 1;
expect(await collect(streamOf([bytes.slice(0, cut), bytes.slice(cut)]))).toEqual([
{ text: '你好' },
]);
});
it('parses a final line without a trailing newline and skips blank lines', async () => {
expect(await collect(streamOf(['{"a":1}\n\n \n{"done":true}']))).toEqual([
{ a: 1 },
{ done: true },
]);
});
it('throws on invalid JSON', async () => {
await expect(collect(streamOf(['{"a":1}\nnot json\n']))).rejects.toThrow();
});
it('releases the reader when the consumer stops early', async () => {
const body = streamOf(['{"a":1}\n{"b":2}\n']);
for await (const _ of readNDJSON(body)) break;
expect(body.locked).toBe(false);
});
});

View file

@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from 'next/server';
import {
getDispatcher,
getResultBucket,
resultKey,
runAfterResponse,
} from '@/libs/readestVoice/bindings';
import { errorResponse, gateReadestVoice } from '@/libs/readestVoice/gate';
// One download job of the app's (see ../route.ts). GET long-polls until the
// job ends: 202 {state} while it runs, then its NDJSON result once (the same
// lines the stream route sends, ending in {done}), after which the job and
// its result are gone. DELETE cancels it.
interface RouteParams {
params: Promise<{ id: string }>;
}
const JOB_ID = /^[0-9a-f]{32}$/;
// Under the time proxies wait for a reply.
const WAIT_MS = 25_000;
const ENDED_ERRORS: Record<string, [string, number]> = {
failed: ['UPSTREAM_FAILED', 502],
cancelled: ['CANCELLED', 409],
};
export async function GET(request: NextRequest, { params }: RouteParams) {
const gate = await gateReadestVoice(request);
if (!gate.ok) return gate.response;
const userId = gate.ctx.user.id;
const { id } = await params;
if (!JOB_ID.test(id)) return errorResponse('INVALID_INPUT', 400);
const dispatcher = getDispatcher();
const bucket = getResultBucket();
if (!dispatcher || !bucket) return errorResponse('JOBS_UNAVAILABLE', 503);
const state = await dispatcher.waitJob(id, userId, WAIT_MS);
if (state === 'queued' || state === 'leased') {
return NextResponse.json({ state }, { status: 202 });
}
if (state && ENDED_ERRORS[state]) return errorResponse(...ENDED_ERRORS[state]);
const result = state === 'done' ? await bucket.get(resultKey(id)) : null;
if (!result) {
if (state) await dispatcher.forgetJob(id, userId);
return errorResponse('NOT_FOUND', 404);
}
// Read whole before dropping it; a result is a few MB at most.
const body = await result.text();
runAfterResponse(Promise.all([bucket.delete(resultKey(id)), dispatcher.forgetJob(id, userId)]));
return new Response(body, {
headers: { 'Content-Type': 'application/x-ndjson', 'Cache-Control': 'no-store' },
});
}
export async function DELETE(request: NextRequest, { params }: RouteParams) {
const gate = await gateReadestVoice(request);
if (!gate.ok) return gate.response;
const userId = gate.ctx.user.id;
const { id } = await params;
if (!JOB_ID.test(id)) return errorResponse('INVALID_INPUT', 400);
const dispatcher = getDispatcher();
const bucket = getResultBucket();
if (!dispatcher || !bucket) return errorResponse('JOBS_UNAVAILABLE', 503);
await dispatcher.cancelJob(id, userId);
await Promise.all([dispatcher.forgetJob(id, userId), bucket.delete(resultKey(id))]);
return new NextResponse(null, { status: 204 });
}

View file

@ -0,0 +1,66 @@
import { NextRequest, NextResponse } from 'next/server';
import { getTTSQuota } from '@/utils/access';
import { USAGE_TYPES, UsageStatsManager } from '@/utils/usage';
import { getDispatcher, getResultBucket } from '@/libs/readestVoice/bindings';
import { errorResponse, gateReadestVoice } from '@/libs/readestVoice/gate';
import { checkVoices, parseWindow, type Segment } from '@/libs/readestVoice/window';
// Readest Voice download jobs: the app submits a window of a chapter download
// and collects it later (jobs/[id]); any worker may synthesize it (workers
// route). Jobs live in the TTSDispatcher Durable Object, results in the
// TTS_JOBS_R2 bucket. Without either (Node dev, self-hosting) the route says
// JOBS_UNAVAILABLE and the app downloads through the stream route instead.
// Quota counts the user's unfinished jobs; delivered sentences are charged
// when a worker completes the job.
const BUSY_RETRY_AFTER_SEC = 5;
// Stable per user and window, so a resubmitted window finds its job.
const jobId = async (userId: string, lang: string, segments: Segment[]) => {
const data = new TextEncoder().encode(JSON.stringify([userId, lang, segments]));
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', data));
return [...digest.slice(0, 16)].map((b) => b.toString(16).padStart(2, '0')).join('');
};
export async function POST(request: NextRequest) {
const gate = await gateReadestVoice(request);
if (!gate.ok) return gate.response;
const { user, plan, catalog } = gate.ctx;
let window = null;
try {
window = parseWindow(await request.json());
} catch {
// Unparseable body: same flat code as an invalid window.
}
if (!window || window.lane !== 'download') return errorResponse('INVALID_INPUT', 400);
const { lang, segments } = window;
const voices = checkVoices(catalog, plan, segments);
if ('error' in voices) return errorResponse(voices.error, voices.status);
const dispatcher = getDispatcher();
if (!dispatcher || !getResultBucket()) return errorResponse('JOBS_UNAVAILABLE', 503);
const used = await UsageStatsManager.getCurrentUsage(user.id, USAGE_TYPES.TTS_CHARS, 'daily');
const id = await jobId(user.id, lang, segments);
let result;
try {
result = await dispatcher.submitJob({
id,
userId: user.id,
plan,
lang,
segments,
engines: voices.engines,
quotaLeft: getTTSQuota(plan) - used,
});
} catch (error) {
console.error('Readest Voice job submit failed:', error);
return errorResponse('JOBS_UNAVAILABLE', 503);
}
if (!result.ok) {
const headers =
result.error === 'BUSY' ? { 'Retry-After': String(BUSY_RETRY_AFTER_SEC) } : undefined;
return errorResponse(result.error, 429, headers);
}
return NextResponse.json({ jobId: id, state: result.state });
}

View file

@ -0,0 +1,23 @@
import { NextRequest, NextResponse } from 'next/server';
import { voicesForPlan } from '@/libs/readestVoice/catalog';
import { errorResponse, gateReadestVoice } from '@/libs/readestVoice/gate';
import { warmup } from '@/libs/readestVoice/runpod';
// Readest Voice voices for the caller's plan. Doubles as the capability
// probe: 403/503 hide the engine in the app (kill switch, lapsed plan).
export async function GET(request: NextRequest) {
const gate = await gateReadestVoice(request);
if (!gate.ok) return gate.response;
const { plan, catalog } = gate.ctx;
return NextResponse.json({ voices: voicesForPlan(catalog, plan) });
}
// Voice-picker-open warmup: boots a worker so the first window is warm.
export async function POST(request: NextRequest) {
const gate = await gateReadestVoice(request);
if (!gate.ok) return gate.response;
const body = (await request.json().catch(() => null)) as { warmup?: unknown } | null;
if (body?.warmup !== true) return errorResponse('INVALID_INPUT', 400);
await warmup(gate.ctx.config);
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,195 @@
import { NextRequest } from 'next/server';
import type { TTSWordBoundary } from '@/libs/edgeTTS';
import { getTTSQuota } from '@/utils/access';
import { USAGE_TYPES, UsageStatsManager } from '@/utils/usage';
import {
acquireSlot,
releaseSlot,
setSlotJob,
SLOT_TTL_SECONDS,
} from '@/libs/readestVoice/admission';
import { runAfterResponse } from '@/libs/readestVoice/bindings';
import { errorResponse, gateReadestVoice } from '@/libs/readestVoice/gate';
import { cancelJob, startJob, streamJob } from '@/libs/readestVoice/runpod';
import { checkVoices, parseWindow, type WindowRequest } from '@/libs/readestVoice/window';
// Readest Voice window route: one RunPod job per window of sentences, streamed
// back as NDJSON, one line per sentence as soon as it is ready, then a
// terminal {done, charged} line. Quota is checked before the window starts
// and charged once, for delivered sentences only, when the stream ends or the
// client goes away (stop, seek, voice change); the RunPod job is cancelled
// then too.
const WINDOW_DEADLINE_MS = SLOT_TTL_SECONDS * 1000;
const BUSY_RETRY_AFTER_SEC = 5;
interface WorkerFrame {
id?: unknown;
audio?: unknown;
boundaries?: unknown;
failed?: unknown;
}
const encoder = new TextEncoder();
const ndjsonLine = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`);
export async function POST(request: NextRequest) {
const gate = await gateReadestVoice(request);
if (!gate.ok) return gate.response;
const { user, plan, config, catalog } = gate.ctx;
let window: WindowRequest | null = null;
try {
window = parseWindow(await request.json());
} catch {
// Unparseable body: same flat code as an invalid window.
}
if (!window) return errorResponse('INVALID_INPUT', 400);
const { clientId, lane, lang, segments } = window;
const voices = checkVoices(catalog, plan, segments);
if ('error' in voices) return errorResponse(voices.error, voices.status);
// Every round trip before the job starts is heard as delay, so the quota
// check and the slot run together. Check before starting; charge only what
// is delivered (below). The slot may wait for this user's turn; a client
// that goes away meanwhile withdraws the window.
const windowChars = segments.reduce((sum, s) => sum + s.text.length, 0);
const token = crypto.randomUUID();
const withdraw = () => runAfterResponse(releaseSlot(token));
request.signal.addEventListener('abort', withdraw, { once: true });
const [used, slot] = await Promise.all([
UsageStatsManager.getCurrentUsage(user.id, USAGE_TYPES.TTS_CHARS, 'daily'),
acquireSlot(user.id, clientId, lane, token),
]);
request.signal.removeEventListener('abort', withdraw);
if (request.signal.aborted) {
if (slot.acquired) runAfterResponse(releaseSlot(token));
return errorResponse('CANCELLED', 499);
}
if (used + windowChars > getTTSQuota(plan)) {
if (slot.acquired) runAfterResponse(releaseSlot(token));
return errorResponse('DAILY_QUOTA_EXCEEDED', 429);
}
if (!slot.acquired) {
return errorResponse('BUSY', 429, { 'Retry-After': String(BUSY_RETRY_AFTER_SEC) });
}
// A new listen window replaced this client's previous one (seek, voice
// change). Best effort, so the new job does not wait on it.
if (slot.previousJobId) runAfterResponse(cancelJob(config, slot.previousJobId));
let jobId: string;
try {
jobId = await startJob(config, { lang, segments });
} catch (error) {
console.error('Readest Voice job start failed:', error);
await releaseSlot(token);
return errorResponse('UPSTREAM_FAILED', 502);
}
const headers = { 'Content-Type': 'application/x-ndjson', 'Cache-Control': 'no-store' };
// Recorded while the job already streams; resolves false when another
// window from this user took the slot meanwhile (handled in the stream).
const slotRecorded = setSlotJob(token, jobId);
const textLength = new Map(segments.map((s) => [s.id, s.text.length]));
const upstream = new AbortController();
let delivered = 0;
let settled = false;
let clientGone = false;
let lostSlot = false;
// Charge once, free the slot once, whatever ends the window.
const settle = async (cancel: boolean) => {
if (settled) return;
settled = true;
if (cancel) await cancelJob(config, jobId);
if (delivered > 0) {
try {
await UsageStatsManager.trackUsage(user.id, USAGE_TYPES.TTS_CHARS, delivered, {
plan,
lane,
segments: segments.length,
});
} catch (error) {
console.error(`Readest Voice usage charge failed (job: ${jobId}):`, error);
}
}
await releaseSlot(token);
};
const onClientGone = () => {
if (clientGone) return;
clientGone = true;
upstream.abort();
runAfterResponse(settle(true));
};
request.signal.addEventListener('abort', onClientGone, { once: true });
const body = new ReadableStream<Uint8Array>({
async start(controller) {
const send = (value: unknown) => {
if (!clientGone) controller.enqueue(ndjsonLine(value));
};
const finish = async (error?: string, cancel = false) => {
await settle(cancel);
if (clientGone) return;
send(
error ? { done: true, charged: delivered, error } : { done: true, charged: delivered },
);
controller.close();
};
const deadline = setTimeout(() => upstream.abort(), WINDOW_DEADLINE_MS);
void slotRecorded.then((recorded) => {
if (recorded) return;
lostSlot = true;
upstream.abort();
});
try {
for await (const event of streamJob(config, jobId, upstream.signal)) {
if ('status' in event) {
const error =
event.status === 'COMPLETED'
? undefined
: event.status === 'CANCELLED'
? 'CANCELLED'
: 'UPSTREAM_FAILED';
await finish(error);
return;
}
const frame = (event.output ?? {}) as WorkerFrame;
const length = typeof frame.id === 'string' ? textLength.get(frame.id) : undefined;
if (length === undefined) continue;
if (typeof frame.audio === 'string') {
delivered += length;
const boundaries = Array.isArray(frame.boundaries)
? (frame.boundaries as TTSWordBoundary[])
: [];
send({ id: frame.id, audio: frame.audio, boundaries });
} else {
// Worker frames say {id, failed}: a top-level `error` would end the
// RunPod job. The app-facing line uses `error`.
send({ id: frame.id, error: 'synthesis failed' });
}
}
await finish('UPSTREAM_FAILED', true);
} catch (error) {
if (clientGone) return;
if (lostSlot) {
// Superseded by another window of this user: end quietly.
await finish(undefined, true);
return;
}
console.error(`Readest Voice stream failed (job: ${jobId}):`, error);
await finish('UPSTREAM_FAILED', true);
} finally {
clearTimeout(deadline);
request.signal.removeEventListener('abort', onClientGone);
}
},
cancel() {
onClientGone();
},
});
return new Response(body, { headers });
}

View file

@ -0,0 +1,120 @@
import { NextRequest, NextResponse } from 'next/server';
import { USAGE_TYPES, UsageStatsManager } from '@/utils/usage';
import { getDispatcher, getResultBucket, resultKey } from '@/libs/readestVoice/bindings';
import { errorResponse } from '@/libs/readestVoice/gate';
// Readest Voice workers pull download jobs here (see ../jobs/route.ts), one
// JSON body per call, by `action`:
// - lease {engines, version}: long-polls for a job the worker can run. Needs
// a worker token (READEST_VOICE_WORKER_TOKENS: "name:token,...") and the
// deployed worker version (READEST_VOICE_WORKER_VERSION, when set), so a
// download sounds like listening.
// - job {lease}: the leased window (a RunPod job started by the dispatcher's
// bridge holds only the lease).
// - heartbeat {lease}: renews the lease; live false means stop.
// - complete {lease, frames}: the worker's frames ({id, audio, boundaries} or
// {id, failed}), stored as the NDJSON lines the app reads, then charged.
// A lease is the credential for its own job and nothing else.
const LEASE_WAIT_MS = 25_000;
interface WorkerFrame {
id?: unknown;
audio?: unknown;
boundaries?: unknown;
}
const sameSecret = (a: string, b: string) => {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
};
const workerName = (request: NextRequest): string | null => {
const token = request.headers.get('authorization')?.replace(/^Bearer\s+/i, '');
if (!token) return null;
for (const entry of (process.env['READEST_VOICE_WORKER_TOKENS'] ?? '').split(',')) {
const separator = entry.indexOf(':');
const name = entry.slice(0, separator).trim();
const secret = entry.slice(separator + 1).trim();
if (separator > 0 && secret && sameSecret(secret, token)) return name;
}
return null;
};
export async function POST(request: NextRequest) {
let body: Record<string, unknown> = {};
try {
body = ((await request.json()) ?? {}) as Record<string, unknown>;
} catch {
// Falls through to INVALID_INPUT.
}
const { action, lease } = body;
if (action !== 'lease' && typeof lease !== 'string') return errorResponse('INVALID_INPUT', 400);
const dispatcher = getDispatcher();
const bucket = getResultBucket();
if (!dispatcher || !bucket) return errorResponse('JOBS_UNAVAILABLE', 503);
switch (action) {
case 'lease': {
const worker = workerName(request);
if (!worker) return errorResponse('NOT_AUTHENTICATED', 401);
const version = process.env['READEST_VOICE_WORKER_VERSION'];
if (version && body['version'] !== version) return errorResponse('VERSION_MISMATCH', 409);
const engines = body['engines'];
if (!Array.isArray(engines) || !engines.every((e) => typeof e === 'string')) {
return errorResponse('INVALID_INPUT', 400);
}
const job = await dispatcher.leaseJob(worker, engines, LEASE_WAIT_MS);
return job ? NextResponse.json(job) : new NextResponse(null, { status: 204 });
}
case 'job': {
const job = await dispatcher.leasedJob(lease as string);
return job ? NextResponse.json(job) : errorResponse('GONE', 410);
}
case 'heartbeat':
return NextResponse.json({ live: await dispatcher.heartbeat(lease as string) });
case 'complete': {
const job = await dispatcher.leasedJob(lease as string);
if (!job) return errorResponse('GONE', 410);
const frames = new Map<unknown, WorkerFrame>(
(Array.isArray(body['frames']) ? (body['frames'] as WorkerFrame[]) : []).map((f) => [
f?.id,
f,
]),
);
let charged = 0;
const lines: unknown[] = job.segments.map(({ id, text }) => {
const frame = frames.get(id);
if (typeof frame?.audio !== 'string') return { id, error: 'synthesis failed' };
charged += text.length;
const boundaries = Array.isArray(frame.boundaries) ? frame.boundaries : [];
return { id, audio: frame.audio, boundaries };
});
lines.push({ done: true, charged });
const key = resultKey(job.jobId);
await bucket.put(key, lines.map((line) => `${JSON.stringify(line)}\n`).join(''));
const owner = await dispatcher.completeJob(lease as string);
if (!owner) {
// Cancelled or re-leased while the result uploaded.
await bucket.delete(key);
return errorResponse('GONE', 410);
}
if (charged > 0) {
try {
await UsageStatsManager.trackUsage(owner.userId, USAGE_TYPES.TTS_CHARS, charged, {
plan: owner.plan,
lane: 'download',
segments: job.segments.length,
});
} catch (error) {
console.error(`Readest Voice usage charge failed (job: ${job.jobId}):`, error);
}
}
return NextResponse.json({ charged });
}
default:
return errorResponse('INVALID_INPUT', 400);
}
}

View file

@ -40,7 +40,13 @@ const TTSControl: React.FC<TTSControlProps> = ({ bookKey, gridInsets }) => {
const hasTimeline = tts.ttsClientsInited && tts.handleSupportsPlaybackInfo();
const audioTransport = tts.ttsClientsInited && tts.audioTransport;
const miniPlayerMounted = tts.showIndicator && !showPlayerSheet;
const miniPlayerVisible = useMiniPlayerAutoHide(bookKey, playerStyle, miniPlayerMounted);
const buffering = !tts.ttsClientsInited || tts.buffering;
const miniPlayerVisible = useMiniPlayerAutoHide(
bookKey,
playerStyle,
miniPlayerMounted,
buffering,
);
useEffect(() => {
if (tts.showBackToCurrentTTSLocation) {
@ -105,7 +111,7 @@ const TTSControl: React.FC<TTSControlProps> = ({ bookKey, gridInsets }) => {
<TTSMiniPlayer
bookKey={bookKey}
isPlaying={tts.isPlaying}
buffering={!tts.ttsClientsInited || tts.buffering}
buffering={buffering}
isEink={isEink}
visible={miniPlayerVisible}
hasTimeline={hasTimeline}

View file

@ -694,6 +694,11 @@ const TTSPlayerSheet = ({
>
{_(voice.name)}
</span>
{voice.tier && (
<span className='badge badge-sm badge-ghost shrink-0'>
{voice.tier === 'pro' ? _('Pro') : _('Plus')}
</span>
)}
</button>
))}
</div>

View file

@ -25,24 +25,29 @@ const LINGER_MS = 5000;
* dismissal: no toolbar up means show the card and arm a fresh countdown.
* Re-running on hoveredBookKey also cancels a countdown in flight when the
* toolbar returns, so a stale remainder can never hide a card just summoned.
*
* While `buffering` (nothing audible yet: a cold GPU worker can take far longer
* than the linger) the card stays up with its spinning play button, and the
* countdown starts once audio does.
*/
export const useMiniPlayerAutoHide = (
bookKey: string,
playerStyle: TTSPlayerStyle,
mounted: boolean,
buffering = false,
) => {
const { hoveredBookKey } = useReaderStore();
const [visible, setVisible] = useState(true);
useEffect(() => {
if (!mounted || playerStyle === 'minimal' || hoveredBookKey === bookKey) {
if (!mounted || playerStyle === 'minimal' || hoveredBookKey === bookKey || buffering) {
setVisible(true);
return;
}
setVisible(true);
const timeout = setTimeout(() => setVisible(false), LINGER_MS);
return () => clearTimeout(timeout);
}, [mounted, playerStyle, hoveredBookKey, bookKey]);
}, [mounted, playerStyle, hoveredBookKey, bookKey, buffering]);
return visible;
};

View file

@ -381,6 +381,13 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
timeout: 5000,
});
};
const handleQuotaExceeded = () => {
eventDispatcher.dispatch('toast', {
message: _('Daily TTS limit reached. Upgrade your plan or try again tomorrow.'),
type: 'error',
timeout: 5000,
});
};
const stopPageFollow = () => {
if (pageFollowTimerRef.current === null) return;
@ -631,6 +638,7 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
};
ttsController.addEventListener('tts-need-auth', handleNeedAuth);
ttsController.addEventListener('tts-quota-exceeded', handleQuotaExceeded);
ttsController.addEventListener('tts-highlight-mark', handleHighlightMark);
ttsController.addEventListener('tts-highlight-word', handleHighlightWord);
ttsController.addEventListener('tts-position', handlePosition);
@ -642,6 +650,7 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
return () => {
stopPageFollow();
ttsController.removeEventListener('tts-need-auth', handleNeedAuth);
ttsController.removeEventListener('tts-quota-exceeded', handleQuotaExceeded);
ttsController.removeEventListener('tts-highlight-mark', handleHighlightMark);
ttsController.removeEventListener('tts-highlight-word', handleHighlightWord);
ttsController.removeEventListener('tts-position', handlePosition);
@ -1053,7 +1062,7 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
setShowIndicator(false);
setIsPlaying(false);
eventDispatcher.dispatch('toast', {
message: _('TTS not supported for this document'),
message: _('TTS not available for this page'),
type: 'error',
});
console.error(error);

View file

@ -0,0 +1,61 @@
import type { TTSLane } from '@/services/tts/providers/types';
import { getDispatcher } from './bindings';
import type { SlotResult } from './dispatchQueue';
// Admission of Readest Voice windows through the TTSDispatcher Durable Object
// (worker.ts, scheduling in dispatchQueue.ts): one global queue that runs at
// most READEST_VOICE_MAX_JOBS windows, one per user and lane, and serves
// waiting users in turn. Every call fails open: an unbound dispatcher (Node
// dev, self-hosting) or a failed call admits the window, and the RunPod
// max-workers cap plus the account spend limit stay the hard ceiling.
export type { SlotResult, TTSLane };
// Matches the route's window deadline: a slot never outlives its request.
export const SLOT_TTL_SECONDS = 180;
// Longer than a window usually runs, shorter than proxies wait for a reply.
export const SLOT_WAIT_SECONDS = 60;
const ADMITTED: SlotResult = { acquired: true, previousJobId: null };
// Resolves once the window may start (possibly after waiting its turn), or
// with acquired false when it was refused, timed out or withdrawn.
export const acquireSlot = async (
userId: string,
clientId: string,
lane: TTSLane,
token: string,
): Promise<SlotResult> => {
const dispatcher = getDispatcher();
if (!dispatcher) return ADMITTED;
try {
return await dispatcher.acquire({ userId, clientId, lane, token });
} catch (error) {
console.warn('TTS slot acquire failed, admitting:', error);
return ADMITTED;
}
};
// False when another window of this client took the slot meanwhile.
export const setSlotJob = async (token: string, jobId: string): Promise<boolean> => {
const dispatcher = getDispatcher();
if (!dispatcher) return true;
try {
return await dispatcher.setJob(token, jobId);
} catch (error) {
console.warn('TTS slot update failed, keeping the job:', error);
return true;
}
};
// Ends a running window, or withdraws a waiting one.
export const releaseSlot = async (token: string): Promise<void> => {
const dispatcher = getDispatcher();
if (!dispatcher) return;
try {
await dispatcher.release(token);
} catch (error) {
// The lease expires on its own (SLOT_TTL_SECONDS).
console.warn('TTS slot release failed:', error);
}
};

View file

@ -0,0 +1,67 @@
import { getCloudflareContext } from '@opennextjs/cloudflare';
import type { SlotRequest, SlotResult } from './dispatchQueue';
import type { JobState, JobSubmission, LeasedJob, SubmitResult } from './jobQueue';
// Cloudflare bindings of the Readest Voice routes (wrangler.toml): the
// TTSDispatcher Durable Object (tts-dispatcher.ts) and the download result
// bucket. Both are null off Workers (Node dev, self-hosting).
export interface DispatcherStub {
acquire(request: SlotRequest): Promise<SlotResult>;
setJob(token: string, jobId: string): Promise<boolean>;
release(token: string): Promise<void>;
submitJob(submission: JobSubmission): Promise<SubmitResult>;
waitJob(jobId: string, userId: string, waitMs: number): Promise<JobState | null>;
cancelJob(jobId: string, userId: string): Promise<boolean>;
forgetJob(jobId: string, userId: string): Promise<void>;
leaseJob(worker: string, engines: string[], waitMs: number): Promise<LeasedJob | null>;
leasedJob(lease: string): Promise<LeasedJob | null>;
heartbeat(lease: string): Promise<boolean>;
completeJob(lease: string): Promise<{ userId: string; plan: string } | null>;
}
export interface ResultBucket {
put(key: string, value: string): Promise<unknown>;
get(key: string): Promise<{ text(): Promise<string> } | null>;
delete(key: string): Promise<void>;
}
interface DispatcherNamespace {
idFromName(name: string): unknown;
get(id: unknown): DispatcherStub;
}
interface Bindings {
TTS_DISPATCHER?: DispatcherNamespace;
TTS_JOBS_R2?: ResultBucket;
}
const getBindings = (): Bindings => {
try {
return getCloudflareContext().env as Bindings;
} catch {
// Not on Workers.
return {};
}
};
export const getDispatcher = (): DispatcherStub | null => {
const namespace = getBindings().TTS_DISPATCHER;
return namespace ? namespace.get(namespace.idFromName('global')) : null;
};
export const getResultBucket = (): ResultBucket | null => getBindings().TTS_JOBS_R2 ?? null;
// Where a finished download job's NDJSON lines wait for the app.
export const resultKey = (jobId: string) => `tts-jobs/${jobId}`;
// Work that must finish after the response is gone (charging, cancelling,
// cleanup): on Workers it has to be registered with waitUntil or it may be
// dropped.
export const runAfterResponse = (task: Promise<unknown>) => {
try {
getCloudflareContext().ctx.waitUntil(task);
} catch {
// Not on Workers (tests, Node dev): the promise just runs.
}
};

View file

@ -0,0 +1,88 @@
import type { UserPlan } from '@/types/quota';
import { isTTSInPlan } from '@/utils/access';
// Readest Voice catalog: server-owned data exported by the TTS worker
// (scripts/export_catalog.py) and uploaded with each worker release, so adding
// a preset voice never needs an app release. Fetched instead of asked from the
// worker because a catalog job would cold-start a GPU on every reader open.
export interface CatalogVoice {
id: string;
engine: string;
name: string;
langs: string[];
}
export interface PlanVoice {
id: string;
name: string;
lang: string;
// The plan that unlocks the voice, shown as its badge.
tier: 'plus' | 'pro';
}
const CATALOG_TTL_MS = 10 * 60 * 1000;
// Which plan unlocks each engine. An engine missing here is hidden (fail
// closed), so a new worker engine never reaches users before this is decided.
// Qwen3 is left out on purpose: its voices stay blocked for every plan.
export const ENGINE_MIN_PLAN: Record<string, 'plus' | 'pro'> = {
kokoro: 'plus',
omnivoice: 'pro',
};
const PLAN_TIER: Record<UserPlan, number> = { free: 0, purchase: 0, plus: 1, pro: 2 };
const MIN_PLAN_TIER: Record<'plus' | 'pro', number> = { plus: 1, pro: 2 };
let cached: { voices: CatalogVoice[]; fetchedAt: number } | null = null;
const isCatalogVoice = (v: unknown): v is CatalogVoice => {
const r = v as Partial<CatalogVoice> | null;
return (
!!r &&
typeof r.id === 'string' &&
typeof r.engine === 'string' &&
typeof r.name === 'string' &&
Array.isArray(r.langs) &&
r.langs.every((l) => typeof l === 'string')
);
};
export const getCatalog = async (): Promise<CatalogVoice[] | null> => {
const url = process.env['READEST_TTS_CATALOG_URL'];
if (!url) return null;
if (cached && Date.now() - cached.fetchedAt < CATALOG_TTL_MS) return cached.voices;
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`catalog fetch failed: ${res.status}`);
const data = (await res.json()) as { voices?: unknown };
const voices = Array.isArray(data.voices) ? data.voices.filter(isCatalogVoice) : [];
cached = { voices, fetchedAt: Date.now() };
return voices;
} catch (error) {
console.warn('Readest Voice catalog unavailable:', error);
// A failed refresh keeps serving the last good catalog.
return cached?.voices ?? null;
}
};
export const isVoiceInPlan = (voice: CatalogVoice, plan: UserPlan): boolean => {
const minPlan = ENGINE_MIN_PLAN[voice.engine];
return !!minPlan && isTTSInPlan(plan) && PLAN_TIER[plan] >= MIN_PLAN_TIER[minPlan];
};
// One row per (voice, language): multilingual voices appear under each
// language they are listed for, as the per-language voice picker expects.
export const voicesForPlan = (catalog: CatalogVoice[], plan: UserPlan): PlanVoice[] =>
catalog
.filter((voice) => isVoiceInPlan(voice, plan))
.flatMap((voice) =>
voice.langs.map((lang) => ({
id: voice.id,
name: voice.name,
lang,
tier: ENGINE_MIN_PLAN[voice.engine]!,
})),
);
export const findVoice = (catalog: CatalogVoice[], id: string): CatalogVoice | undefined =>
catalog.find((voice) => voice.id === id);

View file

@ -0,0 +1,220 @@
// Fair admission of Readest Voice windows to the shared RunPod endpoint, run
// inside the TTSDispatcher Durable Object (worker.ts). Pure and clock-injected
// so it can be tested; no path aliases, since wrangler bundles it from
// worker.ts.
//
// - At most `capacity` windows run at once across all users.
// - Each user runs at most one window per lane; more wait in that user's
// queue (up to `maxWaiting` per lane, then refused).
// - A free slot goes to listening before downloads, except that downloads
// always get a quarter of the capacity (at least one slot) when they wait.
// Within a lane, the waiting user served least recently goes first, which
// stays fair across the gap between a reader's back-to-back windows.
// - A client asking for listening again replaces its own waiting or running
// listen window (a seek or voice change made it stale), without queueing.
// - Waits end after `waitMs`, leases after `leaseMs` (the route's window
// deadline), so a crashed request never holds a slot for long.
export type DispatchLane = 'listen' | 'download';
export interface SlotRequest {
userId: string;
// One per app instance (device or window), so a user's own windows can
// replace each other while other devices of the user queue.
clientId: string;
lane: DispatchLane;
token: string;
}
export interface SlotResult {
acquired: boolean;
// A replaced running listen window's job, for the caller to cancel.
previousJobId: string | null;
}
export interface Lease extends SlotRequest {
jobId: string | null;
expiresAt: number;
}
interface Waiter extends SlotRequest {
deadline: number;
resolve: (result: SlotResult) => void;
}
export interface DispatchOptions {
capacity: number;
leaseMs: number;
waitMs: number;
maxWaiting: number;
}
const MAX_REMEMBERED_USERS = 1000;
const REFUSED: SlotResult = { acquired: false, previousJobId: null };
export class DispatchQueue {
#leases = new Map<string, Lease>();
#waiting: Waiter[] = [];
// Order in which users were last granted a slot.
#served = new Map<string, number>();
#grants = 0;
constructor(
private readonly options: DispatchOptions,
private readonly now: () => number = Date.now,
) {}
acquire(request: SlotRequest): Promise<SlotResult> {
if (request.lane === 'listen') {
const same = (s: SlotRequest) =>
s.lane === 'listen' && s.userId === request.userId && s.clientId === request.clientId;
const stale = this.#waiting.find(same);
if (stale) this.#drop(stale, REFUSED);
const running = [...this.#leases.values()].find(same);
if (running) {
this.#leases.delete(running.token);
this.#grant(request);
return Promise.resolve({ acquired: true, previousJobId: running.jobId });
}
}
const waiting = this.#waiting.filter(
(w) => w.userId === request.userId && w.lane === request.lane,
).length;
if (waiting >= this.options.maxWaiting) return Promise.resolve(REFUSED);
const result = new Promise<SlotResult>((resolve) => {
this.#waiting.push({ ...request, deadline: this.now() + this.options.waitMs, resolve });
});
this.#pump();
return result;
}
// Admits a download now or never (the download job bridge, whose jobs wait
// in the job queue instead): a free slot, and no waiting listen window due
// it first.
tryAcquire(request: SlotRequest): boolean {
if (this.#leases.size >= this.options.capacity) return false;
const downloads = [...this.#leases.values()].filter((l) => l.lane === 'download').length;
if (downloads >= this.#downloadReserve() && this.#waiting.some((w) => w.lane === 'listen')) {
return false;
}
this.#grant(request);
return true;
}
// Keeps a lease that legitimately runs longer than `leaseMs` (a bridged
// download job whose worker still reports in).
renew(token: string): boolean {
const lease = this.#leases.get(token);
if (!lease) return false;
lease.expiresAt = this.now() + this.options.leaseMs;
return true;
}
// False when the lease is gone (replaced or expired): the caller cancels
// its job.
setJob(token: string, jobId: string): boolean {
const lease = this.#leases.get(token);
if (!lease) return false;
lease.jobId = jobId;
return true;
}
// Ends a running window, or withdraws a waiting one.
release(token: string): void {
const waiter = this.#waiting.find((w) => w.token === token);
if (waiter) this.#drop(waiter, REFUSED);
if (this.#leases.delete(token)) this.#pump();
}
sweep(): void {
const now = this.now();
for (const lease of [...this.#leases.values()]) {
if (lease.expiresAt <= now) this.#leases.delete(lease.token);
}
this.#pump();
for (const waiter of this.#waiting.filter((w) => w.deadline <= now)) {
this.#drop(waiter, REFUSED);
}
// Turn order only matters while a user competes; forget idle users once
// the map grows, so it stays bounded.
if (this.#served.size > MAX_REMEMBERED_USERS) {
const active = new Set([
...this.#waiting.map((w) => w.userId),
...[...this.#leases.values()].map((l) => l.userId),
]);
for (const user of this.#served.keys()) {
if (!active.has(user)) this.#served.delete(user);
}
}
}
nextDeadline(): number | null {
const times = [
...[...this.#leases.values()].map((l) => l.expiresAt),
...this.#waiting.map((w) => w.deadline),
];
return times.length ? Math.min(...times) : null;
}
snapshot(): Lease[] {
return [...this.#leases.values()].map((lease) => ({ ...lease }));
}
restore(leases: Lease[]): void {
for (const lease of leases) this.#leases.set(lease.token, { ...lease });
}
#drop(waiter: Waiter, result: SlotResult) {
this.#waiting = this.#waiting.filter((w) => w !== waiter);
waiter.resolve(result);
}
#grant(request: SlotRequest) {
const { userId, clientId, lane, token } = request;
this.#leases.set(token, {
userId,
clientId,
lane,
token,
jobId: null,
expiresAt: this.now() + this.options.leaseMs,
});
this.#served.set(userId, ++this.#grants);
}
#pump() {
while (this.#leases.size < this.options.capacity) {
const next = this.#next();
if (!next) return;
this.#waiting = this.#waiting.filter((w) => w !== next);
this.#grant(next);
next.resolve({ acquired: true, previousJobId: null });
}
}
#next(): Waiter | undefined {
const running = [...this.#leases.values()];
const downloads = running.filter((l) => l.lane === 'download').length;
const lanes: DispatchLane[] =
downloads < this.#downloadReserve() ? ['download', 'listen'] : ['listen', 'download'];
for (const lane of lanes) {
let best: Waiter | undefined;
for (const waiter of this.#waiting) {
if (waiter.lane !== lane) continue;
if (running.some((l) => l.userId === waiter.userId && l.lane === lane)) continue;
// Waiters are in arrival order, so the first per user is its oldest.
if (!best || this.#turn(waiter.userId) < this.#turn(best.userId)) best = waiter;
}
if (best) return best;
}
return undefined;
}
#downloadReserve(): number {
return Math.max(1, Math.floor(this.options.capacity / 4));
}
#turn(userId: string): number {
return this.#served.get(userId) ?? 0;
}
}

View file

@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import type { User } from '@supabase/supabase-js';
import type { UserPlan } from '@/types/quota';
import { getSubscriptionPlan, isTTSInPlan, validateUserAndToken } from '@/utils/access';
import { type CatalogVoice, getCatalog } from './catalog';
import { getRunPodConfig, type RunPodConfig } from './runpod';
// Checks shared by the Readest Voice routes, in order: auth, kill switch,
// plan, catalog. Error bodies are flat string codes: fetchWithAuth throws
// body.error as the Error message, so an object would reach the client as
// "[object Object]".
export interface ReadestVoiceContext {
user: User;
plan: UserPlan;
config: RunPodConfig;
catalog: CatalogVoice[];
}
export const errorResponse = (error: string, status: number, headers?: HeadersInit) =>
NextResponse.json({ error }, { status, headers });
export const gateReadestVoice = async (
request: Request,
): Promise<{ ok: true; ctx: ReadestVoiceContext } | { ok: false; response: NextResponse }> => {
const { user, token } = await validateUserAndToken(request.headers.get('authorization'));
if (!user || !token) return { ok: false, response: errorResponse('NOT_AUTHENTICATED', 403) };
const config = getRunPodConfig();
if (!config) return { ok: false, response: errorResponse('NOT_CONFIGURED', 503) };
const plan = getSubscriptionPlan(token);
if (!isTTSInPlan(plan)) return { ok: false, response: errorResponse('PLAN_REQUIRED', 403) };
const catalog = await getCatalog();
if (!catalog) return { ok: false, response: errorResponse('NOT_CONFIGURED', 503) };
return { ok: true, ctx: { user, plan, config, catalog } };
};

View file

@ -0,0 +1,350 @@
// Durable download jobs for Readest Voice, run inside the TTSDispatcher
// Durable Object (tts-dispatcher.ts) beside the listen admission queue. Pure
// and clock-injected so it can be tested; no path aliases, since wrangler
// bundles it from worker.ts.
//
// - An app submits a window of sentences as a job; any worker that runs every
// engine the job needs leases it, renews the lease while it works, and
// completes it with the audio (stored by the route, not here).
// - The same window submitted again (same id) returns the existing job, so a
// download resumed later picks up what finished meanwhile.
// - Fair order: the waiting user served least recently goes first. A user may
// run several jobs at once only when nobody else waits.
// - A lease that runs out puts the job back in the queue; after `maxAttempts`
// leases it fails.
// - Book text lives only until a job ends; ended jobs are forgotten after
// `retainMs`, as is any job nobody touched for that long.
export type JobState = 'queued' | 'leased' | 'done' | 'failed' | 'cancelled';
export interface JobSegment {
id: string;
text: string;
voice: string;
}
export interface JobSubmission {
// Derived from the user and the window, so a resubmit finds its job.
id: string;
userId: string;
plan: string;
lang: string;
segments: JobSegment[];
// Engines a worker must run to synthesize every segment.
engines: string[];
// Characters the user may still use today; unfinished jobs count against it.
quotaLeft: number;
}
export type SubmitResult =
| { ok: true; state: JobState }
| { ok: false; error: 'BUSY' | 'DAILY_QUOTA_EXCEEDED' };
export interface Job {
id: string;
userId: string;
plan: string;
lang: string;
segments: JobSegment[];
engines: string[];
chars: number;
state: JobState;
attempts: number;
lease: string | null;
worker: string | null;
leaseExpiresAt: number;
updatedAt: number;
}
export interface LeasedJob {
jobId: string;
lease: string;
lang: string;
segments: JobSegment[];
}
export interface JobOptions {
leaseMs: number;
maxAttempts: number;
maxQueuedPerUser: number;
retainMs: number;
}
interface WorkerWaiter {
worker: string;
engines: string[];
deadline: number;
resolve: (job: LeasedJob | null) => void;
}
interface AppWaiter {
jobId: string;
deadline: number;
resolve: (state: JobState | null) => void;
}
const MAX_REMEMBERED_USERS = 1000;
const ENDED: readonly JobState[] = ['done', 'failed', 'cancelled'];
export class JobQueue {
#jobs = new Map<string, Job>();
#workers: WorkerWaiter[] = [];
#apps: AppWaiter[] = [];
// Order in which users were last served a job.
#served = new Map<string, number>();
#leases = 0;
#dirty = new Set<string>();
constructor(
private readonly options: JobOptions,
private readonly now: () => number = Date.now,
) {}
submit(submission: JobSubmission): SubmitResult {
const { quotaLeft, ...fields } = submission;
const existing = this.#jobs.get(fields.id);
if (existing?.userId === fields.userId && !['failed', 'cancelled'].includes(existing.state)) {
return { ok: true, state: existing.state };
}
const unfinished = [...this.#jobs.values()].filter(
(job) => job.userId === fields.userId && (job.state === 'queued' || job.state === 'leased'),
);
if (
unfinished.filter((job) => job.state === 'queued').length >= this.options.maxQueuedPerUser
) {
return { ok: false, error: 'BUSY' };
}
const chars = fields.segments.reduce((sum, s) => sum + s.text.length, 0);
const pending = unfinished.reduce((sum, job) => sum + job.chars, 0);
if (pending + chars > quotaLeft) return { ok: false, error: 'DAILY_QUOTA_EXCEEDED' };
// Re-inserted, so a resubmitted job queues behind the others.
this.#jobs.delete(fields.id);
this.#jobs.set(fields.id, {
...fields,
chars,
state: 'queued',
attempts: 0,
lease: null,
worker: null,
leaseExpiresAt: 0,
updatedAt: this.now(),
});
this.#dirty.add(fields.id);
this.#pump();
return { ok: true, state: 'queued' };
}
hasQueued(): boolean {
return [...this.#jobs.values()].some((job) => job.state === 'queued');
}
// A job for this worker now, or null. `engines` null runs every engine;
// `lease` lets the caller name the lease up front.
leaseNow(
worker: string,
engines: string[] | null,
lease: string = crypto.randomUUID(),
): LeasedJob | null {
const job = this.#pick(engines);
return job ? this.#grant(job, worker, lease) : null;
}
// Waits up to `waitMs` for a job (a worker's long poll).
lease(worker: string, engines: string[], waitMs: number): Promise<LeasedJob | null> {
const job = this.leaseNow(worker, engines);
if (job) return Promise.resolve(job);
return new Promise((resolve) => {
this.#workers.push({ worker, engines, deadline: this.now() + waitMs, resolve });
});
}
// The window a lease holder works on, while the lease is live.
job(lease: string): LeasedJob | null {
const job = this.#byLease(lease);
return job ? this.#leased(job) : null;
}
isLeaseLive(lease: string): boolean {
return !!this.#byLease(lease);
}
// Renews a live lease; false tells the worker to stop (cancelled, or the
// lease ran out and the job went to someone else).
heartbeat(lease: string): boolean {
const job = this.#byLease(lease);
if (!job) return false;
job.leaseExpiresAt = this.now() + this.options.leaseMs;
this.#dirty.add(job.id);
return true;
}
// Null when the lease is no longer live: the result must be discarded.
complete(lease: string): { userId: string; plan: string } | null {
const job = this.#byLease(lease);
if (!job) return null;
this.#end(job, 'done');
return { userId: job.userId, plan: job.plan };
}
cancel(jobId: string, userId: string): boolean {
const job = this.#owned(jobId, userId);
if (!job || ENDED.includes(job.state)) return false;
this.#end(job, 'cancelled');
return true;
}
status(jobId: string, userId: string): JobState | null {
return this.#owned(jobId, userId)?.state ?? null;
}
// The job's state once it ends, or after `waitMs` (an app's long poll).
wait(jobId: string, userId: string, waitMs: number): Promise<JobState | null> {
const job = this.#owned(jobId, userId);
if (!job || ENDED.includes(job.state)) return Promise.resolve(job?.state ?? null);
return new Promise((resolve) => {
this.#apps.push({ jobId, deadline: this.now() + waitMs, resolve });
});
}
// The app has the result: nothing left to keep.
forget(jobId: string, userId: string): void {
if (!this.#owned(jobId, userId)) return;
this.#jobs.delete(jobId);
this.#dirty.add(jobId);
this.#wake(jobId, null);
}
sweep(): void {
const now = this.now();
for (const job of [...this.#jobs.values()]) {
if (job.state === 'leased' && job.leaseExpiresAt <= now) {
if (job.attempts >= this.options.maxAttempts) {
this.#end(job, 'failed');
} else {
job.state = 'queued';
job.lease = null;
job.worker = null;
job.updatedAt = now;
this.#dirty.add(job.id);
}
} else if (job.state !== 'leased' && job.updatedAt + this.options.retainMs <= now) {
this.#jobs.delete(job.id);
this.#dirty.add(job.id);
this.#wake(job.id, null);
}
}
this.#pump();
for (const waiter of this.#workers.filter((w) => w.deadline <= now)) {
this.#workers = this.#workers.filter((w) => w !== waiter);
waiter.resolve(null);
}
for (const waiter of this.#apps.filter((w) => w.deadline <= now)) {
this.#apps = this.#apps.filter((w) => w !== waiter);
waiter.resolve(this.#jobs.get(waiter.jobId)?.state ?? null);
}
// Turn order only matters while a user waits; forget idle users once the
// map grows, so it stays bounded.
if (this.#served.size > MAX_REMEMBERED_USERS) {
const active = new Set([...this.#jobs.values()].map((job) => job.userId));
for (const user of this.#served.keys()) {
if (!active.has(user)) this.#served.delete(user);
}
}
}
nextDeadline(): number | null {
const times = [
...[...this.#jobs.values()].map((job) =>
job.state === 'leased' ? job.leaseExpiresAt : job.updatedAt + this.options.retainMs,
),
...this.#workers.map((w) => w.deadline),
...this.#apps.map((w) => w.deadline),
];
return times.length ? Math.min(...times) : null;
}
// Jobs changed (to store) and removed (to delete) since the last call.
takeChanges(): { put: Job[]; deleted: string[] } {
const put: Job[] = [];
const deleted: string[] = [];
for (const id of this.#dirty) {
const job = this.#jobs.get(id);
if (job) put.push({ ...job });
else deleted.push(id);
}
this.#dirty.clear();
return { put, deleted };
}
restore(jobs: Job[]): void {
for (const job of jobs) this.#jobs.set(job.id, { ...job });
}
#owned(jobId: string, userId: string): Job | undefined {
const job = this.#jobs.get(jobId);
return job?.userId === userId ? job : undefined;
}
#byLease(lease: string): Job | undefined {
for (const job of this.#jobs.values()) {
if (job.state === 'leased' && job.lease === lease) return job;
}
return undefined;
}
#leased(job: Job): LeasedJob {
return { jobId: job.id, lease: job.lease!, lang: job.lang, segments: job.segments };
}
#pick(engines: string[] | null): Job | undefined {
let best: Job | undefined;
for (const job of this.#jobs.values()) {
if (job.state !== 'queued') continue;
if (engines && !job.engines.every((engine) => engines.includes(engine))) continue;
// Jobs are in arrival order, so the first per user is its oldest.
if (!best || this.#turn(job.userId) < this.#turn(best.userId)) best = job;
}
return best;
}
#grant(job: Job, worker: string, lease: string = crypto.randomUUID()): LeasedJob {
job.state = 'leased';
job.lease = lease;
job.worker = worker;
job.attempts += 1;
job.leaseExpiresAt = this.now() + this.options.leaseMs;
job.updatedAt = this.now();
this.#dirty.add(job.id);
this.#served.set(job.userId, ++this.#leases);
return this.#leased(job);
}
#pump() {
for (const waiter of [...this.#workers]) {
const job = this.#pick(waiter.engines);
if (!job) continue;
this.#workers = this.#workers.filter((w) => w !== waiter);
waiter.resolve(this.#grant(job, waiter.worker));
}
}
#end(job: Job, state: JobState) {
job.state = state;
job.segments = [];
job.lease = null;
job.updatedAt = this.now();
this.#dirty.add(job.id);
this.#wake(job.id, state);
}
#wake(jobId: string, state: JobState | null) {
for (const waiter of this.#apps.filter((w) => w.jobId === jobId)) {
this.#apps = this.#apps.filter((w) => w !== waiter);
waiter.resolve(state);
}
}
#turn(userId: string): number {
return this.#served.get(userId) ?? 0;
}
}

View file

@ -0,0 +1,93 @@
// RunPod Serverless client for the Readest Voice worker: one job per window
// of sentences, read back incrementally from /stream. Every detail of the
// /stream envelope lives in streamJob so a correction is one edit (the local
// emulator in the readest-voice worker repo mirrors it; verify against real RunPod
// before deploy).
export interface RunPodConfig {
apiKey: string;
endpointId: string;
base: string;
}
export type TerminalStatus = 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMED_OUT';
export type StreamEvent = { output: unknown } | { status: TerminalStatus; error?: string };
const DEFAULT_RUNPOD_API_BASE = 'https://api.runpod.ai/v2';
const TERMINAL: readonly string[] = ['COMPLETED', 'FAILED', 'CANCELLED', 'TIMED_OUT'];
// /stream long-polls; after an empty reply, wait briefly before asking again.
const EMPTY_POLL_DELAY_MS = 100;
// Unset key or endpoint is the kill switch: the routes answer 503.
// RUNPOD_API_BASE points the routes at the local emulator in development.
export const getRunPodConfig = (): RunPodConfig | null => {
const apiKey = process.env['RUNPOD_API_KEY'];
const endpointId = process.env['RUNPOD_TTS_ENDPOINT_ID'];
if (!apiKey || !endpointId) return null;
return { apiKey, endpointId, base: process.env['RUNPOD_API_BASE'] || DEFAULT_RUNPOD_API_BASE };
};
const headers = (cfg: RunPodConfig) => ({
'Content-Type': 'application/json',
Authorization: `Bearer ${cfg.apiKey}`,
});
const url = (cfg: RunPodConfig, path: string) => `${cfg.base}/${cfg.endpointId}/${path}`;
export const startJob = async (cfg: RunPodConfig, input: unknown): Promise<string> => {
const res = await fetch(url(cfg, 'run'), {
method: 'POST',
headers: headers(cfg),
body: JSON.stringify({ input }),
});
if (!res.ok) throw new Error(`RunPod run failed: ${res.status}`);
const { id } = (await res.json()) as { id?: unknown };
if (typeof id !== 'string' || !id) throw new Error('RunPod run returned no job id');
return id;
};
export async function* streamJob(
cfg: RunPodConfig,
jobId: string,
signal: AbortSignal,
): AsyncGenerator<StreamEvent> {
for (;;) {
const res = await fetch(url(cfg, `stream/${jobId}`), { headers: headers(cfg), signal });
if (!res.ok) throw new Error(`RunPod stream failed: ${res.status} (job: ${jobId})`);
const body = (await res.json()) as {
status?: string;
stream?: { output?: unknown }[];
error?: string;
};
const items = body.stream ?? [];
for (const item of items) yield { output: item.output };
if (body.status && TERMINAL.includes(body.status)) {
yield { status: body.status as TerminalStatus, error: body.error };
return;
}
if (!items.length) await new Promise((resolve) => setTimeout(resolve, EMPTY_POLL_DELAY_MS));
}
}
// Best effort: a failed cancel only means the worker finishes the window.
export const cancelJob = async (cfg: RunPodConfig, jobId: string): Promise<void> => {
try {
await fetch(url(cfg, `cancel/${jobId}`), { method: 'POST', headers: headers(cfg) });
} catch (error) {
console.warn(`RunPod cancel failed (job: ${jobId}):`, error);
}
};
// Voice-picker-open warmup: boots a worker and loads Kokoro so the first
// window hits a warm engine. Fire-and-forget via the async /run endpoint.
export const warmup = async (cfg: RunPodConfig): Promise<void> => {
try {
await fetch(url(cfg, 'run'), {
method: 'POST',
headers: headers(cfg),
body: JSON.stringify({ input: { warmup: true } }),
});
} catch (error) {
console.warn('RunPod warmup failed:', error);
}
};

View file

@ -0,0 +1,74 @@
import type { UserPlan } from '@/types/quota';
import type { TTSLane } from '@/services/tts/providers/types';
import { type CatalogVoice, findVoice, isVoiceInPlan } from './catalog';
// A window of sentences as the app sends it, shared by the stream route
// (listening) and the jobs route (downloads).
export interface Segment {
id: string;
text: string;
voice: string;
}
export interface WindowRequest {
clientId: string;
lane: TTSLane;
lang: string;
segments: Segment[];
}
const LANE_LIMITS: Record<TTSLane, { segments: number; chars: number }> = {
listen: { segments: 8, chars: 2000 },
download: { segments: 64, chars: 12000 },
};
const MAX_SEGMENT_CHARS = 2000;
const MAX_CLIENT_ID_CHARS = 64;
// Apps that send no client id share one: their listen windows replace each
// other, as before per-client queueing.
const DEFAULT_CLIENT_ID = 'default';
export const parseWindow = (body: unknown): WindowRequest | null => {
const {
client = DEFAULT_CLIENT_ID,
lane,
lang,
segments,
} = (body ?? {}) as Record<string, unknown>;
if (typeof client !== 'string' || !client || client.length > MAX_CLIENT_ID_CHARS) return null;
if (lane !== 'listen' && lane !== 'download') return null;
if (typeof lang !== 'string' || !Array.isArray(segments)) return null;
const limits = LANE_LIMITS[lane];
if (segments.length === 0 || segments.length > limits.segments) return null;
const ids = new Set<string>();
let chars = 0;
// Only the validated fields go on, to the worker and into stored jobs.
const clean: Segment[] = [];
for (const raw of segments) {
const { id, text, voice } = (raw ?? {}) as Record<string, unknown>;
if (typeof id !== 'string' || !id || ids.has(id)) return null;
if (typeof text !== 'string' || !text.trim() || text.length > MAX_SEGMENT_CHARS) return null;
if (typeof voice !== 'string') return null;
ids.add(id);
chars += text.length;
clean.push({ id, text, voice });
}
if (chars > limits.chars) return null;
return { clientId: client, lane, lang: lang.slice(0, 35), segments: clean };
};
// The engines the window needs, or the flat error code that refuses it.
export const checkVoices = (
catalog: CatalogVoice[],
plan: UserPlan,
segments: Segment[],
): { engines: string[] } | { error: 'UNKNOWN_VOICE' | 'VOICE_TIER_REQUIRED'; status: number } => {
const engines = new Set<string>();
for (const segment of segments) {
const voice = findVoice(catalog, segment.voice);
if (!voice) return { error: 'UNKNOWN_VOICE', status: 400 };
if (!isVoiceInPlan(voice, plan)) return { error: 'VOICE_TIER_REQUIRED', status: 403 };
engines.add(voice.engine);
}
return { engines: [...engines] };
};

View file

@ -34,7 +34,7 @@ import {
OneDriveSettings,
ICloudSettings,
} from '@/types/settings';
import { UserStorageQuota, UserDailyTranslationQuota } from '@/types/quota';
import { UserStorageQuota, UserDailyTranslationQuota, UserDailyTTSQuota } from '@/types/quota';
import { getDefaultMaxBlockSize, getDefaultMaxInlineSize } from '@/utils/config';
import { stubTranslation as _ } from '@/utils/misc';
import { DEFAULT_AI_SETTINGS } from './ai/constants';
@ -1028,6 +1028,13 @@ export const DEFAULT_DAILY_TRANSLATION_QUOTA: UserDailyTranslationQuota = {
purchase: 0,
};
export const DEFAULT_DAILY_TTS_QUOTA: UserDailyTTSQuota = {
free: 0,
plus: 100 * 1024,
pro: 300 * 1024,
purchase: 0,
};
export const DOUBLE_CLICK_INTERVAL_THRESHOLD_MS = 250;
export const DISABLE_DOUBLE_CLICK_ON_MOBILE = true;
export const LONG_HOLD_THRESHOLD = 500;

View file

@ -9,20 +9,23 @@ import { AppService } from '@/types/system';
import { parseSSMLMarks } from '@/utils/ssml';
import { DEFAULT_PARAGRAPH_GAP_SEC, TTSController } from './TTSController';
import { TTSUtils } from './TTSUtils';
import { findBoundaryIndexAtTime } from './wordHighlight';
import { alignBoundariesToSpeech, findBoundaryIndexAtTime } from './wordHighlight';
import { applyEdgeFade, findSpeechBounds } from './pcm';
import { timeStretch } from './timeStretch';
import { gapAfterSentence } from './gap';
import {
calibrateVoiceRate,
estimateSentenceSeconds,
recordMeasuredDuration,
recordProvisionalDuration,
} from './ttsDuration';
import { CachingProvider } from './providers/cache';
import {
SpeechProvider,
SpeechSynthesisFatalError,
SpeechSynthesisPermanentError,
SpeechSynthesisRequest,
SpeechSynthesisResult,
} from './providers/types';
import { TTSAudioBuffer, WebAudioPlayer, WebAudioPlayerEvent } from './WebAudioPlayer';
@ -55,6 +58,15 @@ const TICKS_PER_SECOND = 10_000_000;
// resets the count. A wholly-uncached run stops instead of racing to the end.
const MAX_CONSECUTIVE_SKIPS = 3;
// Windowed providers (SpeechProvider.prefetch) are told about upcoming marks so
// they can synthesize several per request, minutes ahead: a GPU worker is
// slower than playback for a long sentence, and unheard audio after a stop or
// seek costs little next to an audible stall. The lookahead covers the current
// paragraph; preloads give each upcoming paragraph its first minute.
const PREFETCH_AHEAD_MARKS = 32;
const PREFETCH_AHEAD_SEC = 180;
const PRELOAD_AHEAD_SEC = 60;
interface ChunkMeta {
mark: TTSMark;
boundaries: TTSWordBoundary[];
@ -165,6 +177,9 @@ export class BufferedTTSClient implements TTSClient {
return { data: audio, boundaries };
} catch (err) {
if (err instanceof SpeechSynthesisPermanentError) throw err;
if (err instanceof SpeechSynthesisFatalError) throw err;
// Stopped on purpose (stop, seek, voice change): not a failure.
if (signal.aborted) return undefined;
lastError = err;
console.warn(`TTS synthesis attempt ${attempt}/${maxAttempts} failed`, err);
if (attempt < maxAttempts && !signal.aborted) {
@ -201,6 +216,7 @@ export class BufferedTTSClient implements TTSClient {
const availableVoices = (await this.getVoices(lang))[0]?.voices || [];
const picked = this.provider.pickDefaultVoice?.(availableVoices);
if (this.provider.sameLanguageVoicesOnly) return picked || availableVoices[0]?.id || '';
return (
picked ||
availableVoices[0]?.id ||
@ -302,7 +318,62 @@ export class BufferedTTSClient implements TTSClient {
}
}
// Requests for marks, voices resolved exactly as playback does.
async #requestsFor(marks: TTSMark[]): Promise<SpeechSynthesisRequest[]> {
const reqs: SpeechSynthesisRequest[] = [];
for (const mark of marks) {
const voice = await this.getVoiceIdFromLang(mark.language);
reqs.push({ lang: mark.language, text: mark.text, voice, pitch: this.#pitch });
}
return reqs;
}
// The marks from `from` within `horizonSec` of estimated audio (at least the
// first, at most PREFETCH_AHEAD_MARKS).
async #marksAhead(marks: TTSMark[], from: number, horizonSec: number): Promise<TTSMark[]> {
const ahead: TTSMark[] = [];
let seconds = 0;
for (let i = from; i < marks.length && ahead.length < PREFETCH_AHEAD_MARKS; i++) {
const mark = marks[i]!;
const voice = await this.getVoiceIdFromLang(mark.language);
seconds += estimateSentenceSeconds(mark.text, mark.language, voice);
if (ahead.length > 0 && seconds > horizonSec) break;
ahead.push(mark);
}
return ahead;
}
// A prefetched sentence counts as buffered once its audio exists, as an Edge
// preload does once synthesized.
#onPrefetchDelivered = (req: SpeechSynthesisRequest, result: SpeechSynthesisResult) => {
if (req.voice) this.#recordDurations(req.voice, req.text, result.boundaries);
};
// Tell a windowed provider which marks come next.
async #prefetchAhead(marks: TTSMark[], from: number, signal: AbortSignal) {
if (!this.provider.prefetch) return;
const ahead = await this.#marksAhead(marks, from, PREFETCH_AHEAD_SEC);
if (signal.aborted) return;
this.provider.prefetch(await this.#requestsFor(ahead), 'listen', signal, {
onDelivered: this.#onPrefetchDelivered,
});
}
async *#preload(marks: TTSMark[], signal: AbortSignal) {
// The lookahead cannot see past the current paragraph: hint each upcoming
// paragraph's first minute at background priority, and let the scheduler's
// lookahead do the rest once the paragraph starts.
if (this.provider.prefetch) {
const reqs = await this.#requestsFor(await this.#marksAhead(marks, 0, PRELOAD_AHEAD_SEC));
if (reqs.length && !signal.aborted) {
this.provider.prefetch(reqs, 'listen', signal, {
background: true,
onDelivered: this.#onPrefetchDelivered,
});
}
yield { code: 'end', message: 'Preload finished' } as TTSMessageEvent;
return;
}
// Fetch the first couple of marks immediately and the rest in the
// background; the provider's in-flight dedup keeps this from racing
// duplicate requests against the playback scheduler.
@ -358,8 +429,9 @@ export class BufferedTTSClient implements TTSClient {
): Promise<void> {
const rate = this.#rate;
try {
for (const mark of marks) {
for (const [index, mark] of marks.entries()) {
if (signal.aborted || this.#activeGeneration !== generation) return;
await this.#prefetchAhead(marks, index, signal);
// Voices resolve per mark: mixed-language sections speak (and record
// durations under) the voice actually used for each sentence.
const voiceId = await this.getVoiceIdFromLang(mark.language);
@ -376,6 +448,11 @@ export class BufferedTTSClient implements TTSClient {
try {
audio = await this.#synthesizeWithRetry(mark.language, mark.text, voiceId, signal);
} catch (error) {
if (error instanceof SpeechSynthesisFatalError) {
// Nothing later can succeed either (e.g. the daily quota is used up).
queue.push({ kind: 'error', message: error.message });
return;
}
if (error instanceof SpeechSynthesisPermanentError) {
// Genuinely unsynthesizable sentence (server returned no audio):
// skip it and keep going — a few bad sentences must not stop a
@ -458,7 +535,7 @@ export class BufferedTTSClient implements TTSClient {
if (!ready || signal.aborted) return;
chunkMeta.push({
mark,
boundaries: audio.boundaries,
boundaries: alignBoundariesToSpeech(audio.boundaries, prepared.trimStartSec),
trimStartSec: prepared.trimStartSec,
trimmedDurationSec: prepared.trimmedDurationSec,
req,
@ -638,6 +715,21 @@ export class BufferedTTSClient implements TTSClient {
return this.provider instanceof CachingProvider;
}
// Chapter downloads: hand a windowed provider the whole section on the
// download lane (cached sentences are filtered out by CachingProvider).
async prefetchSentences(
sentences: { lang: string; text: string }[],
signal?: AbortSignal,
): Promise<void> {
if (!this.provider.prefetch) return;
const reqs: SpeechSynthesisRequest[] = [];
for (const { lang, text } of sentences) {
const voice = await this.getVoiceIdFromLang(lang);
reqs.push({ lang, text, voice, pitch: this.#pitch });
}
this.provider.prefetch(reqs, 'download', signal ?? new AbortController().signal);
}
// Synthesize one sentence into the cache (a hit is a no-op) and record its
// key against the section manifest. Resolves the voice exactly as live
// playback does, so the computed key matches. Returns whether audio is now
@ -666,6 +758,9 @@ export class BufferedTTSClient implements TTSClient {
);
if (!result) return false;
} catch (err) {
// A fatal failure (quota) ends the whole download, not just this
// sentence: let it reach the downloader.
if (err instanceof SpeechSynthesisFatalError) throw err;
// Offline / permanent failure: leave the ordinal unrecorded so the
// section stays incomplete and can be retried later.
console.warn(
@ -762,6 +857,7 @@ export class BufferedTTSClient implements TTSClient {
// queue starts each session fresh, so its paragraph pause stays with the
// controller.
scheduledGaps: !(this.#player instanceof NativeAudioPlayer),
windowedPrefetch: !!this.provider.prefetch,
};
}

View file

@ -2,8 +2,8 @@ import { EDGE_TTS_PROTOCOL } from '@/libs/edgeTTS';
import { isTauriAppPlatform } from '@/services/environment';
import { AppService } from '@/types/system';
import { BufferedTTSClient } from './BufferedTTSClient';
import { BookTTSCacheStore, getTTSCacheConfig } from './providers/bookCacheStore';
import { CachingProvider } from './providers/cache';
import { createBookTTSCacheStore } from './providers/bookCacheStore';
import { CachingProvider, type TTSCacheStore } from './providers/cache';
import { EdgeSpeechProvider } from './providers/edge';
import { SpeechProvider } from './providers/types';
import { TTSController } from './TTSController';
@ -18,23 +18,27 @@ export { DEFAULT_SENTENCE_GAP_SEC } from './BufferedTTSClient';
export class EdgeTTSClient extends BufferedTTSClient {
#edgeProvider: EdgeSpeechProvider;
constructor(controller?: TTSController, appService?: AppService | null) {
// `store` is the controller's shared per-book cache store (null: caching
// off). Omitted, the client builds its own (standalone use and tests).
constructor(
controller?: TTSController,
appService?: AppService | null,
store?: TTSCacheStore | null,
) {
const edgeProvider = new EdgeSpeechProvider();
let provider: SpeechProvider = edgeProvider;
const cacheConfig = getTTSCacheConfig();
if (appService && cacheConfig.enabled) {
// Per-book persistent cache on every platform: appService.openDatabase
// rides tauri-plugin-turso natively and turso WASM over OPFS on the
// web. The book key lands on the controller in init(), after this
// constructor, hence the lazy resolver — the hash is the part of the
// key before the first dash (see TTSSessionManager.getBookHashFromKey;
// inlined to avoid a module cycle through the session manager).
const store = new BookTTSCacheStore(
appService,
() => controller?.bookKey?.split('-')[0] || null,
cacheConfig.budgetMB * 1024 * 1024,
);
provider = new CachingProvider(edgeProvider, store);
// Per-book persistent cache on every platform: appService.openDatabase
// rides tauri-plugin-turso natively and turso WASM over OPFS on the
// web. The book key lands on the controller in init(), after this
// constructor, hence the lazy resolver — the hash is the part of the
// key before the first dash (see TTSSessionManager.getBookHashFromKey;
// inlined to avoid a module cycle through the session manager).
const cacheStore =
store === undefined
? createBookTTSCacheStore(appService, () => controller?.bookKey?.split('-')[0] || null)
: store;
if (cacheStore) {
provider = new CachingProvider(edgeProvider, cacheStore);
}
super(provider, controller, appService);
this.#edgeProvider = edgeProvider;

View file

@ -78,7 +78,9 @@ export class SectionTimeline {
const duration =
measured ?? estimateSentenceSeconds(sentence.text, this.#lang, this.#voiceId);
this.#durations[i] = duration;
this.#measured[i] = measured !== undefined;
// A sentence with nothing to speak (estimated at 0 s) is never
// synthesized: it is as known as a measured one.
this.#measured[i] = measured !== undefined || duration === 0;
this.#prefix[i] = sum;
sum += duration;
}
@ -90,6 +92,19 @@ export class SectionTimeline {
return this.#total / this.#rate;
}
// Where buffered audio ends, as a fraction of the timeline, while sentence
// `index` plays: through the run of measured (synthesized) sentences that
// starts there. Prefetched audio is measured as it arrives, so this is the
// player's buffer bar; it stays correct when playback resumes mid-section.
getBufferedFraction(index: number): number {
if (this.#total <= 0 || index < 0 || index >= this.#durations.length) return 0;
let end = this.#prefix[index]!;
for (let i = index; i < this.#durations.length && this.#measured[i]; i++) {
end += this.#durations[i]!;
}
return end / this.#total;
}
// Duration-weighted fraction of the timeline backed by measured (exact)
// values — the scrubber shows "~" while this is low.
getMeasuredFraction(): number {

View file

@ -33,6 +33,10 @@ export interface TTSCapabilities {
// clock. The controller must not also sleep for it: doing both plays the gap
// twice and puts synthesis latency on top of it instead of inside it (#5750).
scheduledGaps?: boolean;
// Preloads are cheap hints the engine batches into synthesis windows, not
// immediate syntheses: the controller keeps minutes of upcoming paragraphs
// requested instead of a fixed handful.
windowedPrefetch?: boolean;
}
export interface TTSClient {

View file

@ -20,13 +20,17 @@ import { expandRangeOverRuby } from '@/utils/ruby';
import { WebSpeechClient } from './WebSpeechClient';
import { NativeTTSClient } from './NativeTTSClient';
import { EdgeTTSClient } from './EdgeTTSClient';
import { BufferedTTSClient } from './BufferedTTSClient';
import { createBookTTSCacheStore } from './providers/bookCacheStore';
import { CachingProvider } from './providers/cache';
import { ReadestVoiceProvider } from './providers/readest';
import { SectionTimeline, TimelineSentence } from './SectionTimeline';
import { hydrateProvisionalDurations } from './ttsDuration';
import { estimateSentenceSeconds, hydrateProvisionalDurations } from './ttsDuration';
import { DownloadableSentence, SectionEnumerator, TTSDownloader } from './TTSDownloader';
import { TTSUtils } from './TTSUtils';
import { TTSClient } from './TTSClient';
import { startAudioKeepAlive, stopAudioKeepAlive } from './WebAudioPlayer';
import { isValidLang } from '@/utils/lang';
import { isSameLang, isValidLang } from '@/utils/lang';
import { normalizeLyricText } from '@/utils/ttsLyrics';
import {
computeWordOffsets,
@ -75,6 +79,12 @@ let ttsPositionSequence = 0;
// consecutive failures so a wholly-unusable engine still stops gracefully
// instead of silently racing to the end of the book. See #4613, #4408.
const TTS_NATIVE_SPEAK_MAX_CONSECUTIVE_ERRORS = 5;
// Windowed engines (TTSCapabilities.windowedPrefetch): preload upcoming
// paragraphs until about this much estimated audio, at most this many.
const PRELOAD_AHEAD_SEC = 180;
const PRELOAD_MAX_PARAGRAPHS = 40;
// Preload the next paragraphs this long after a paragraph starts at the latest.
const PRELOAD_NEXT_AFTER_MS = 500;
type TTSState =
| 'stopped'
@ -100,6 +110,9 @@ const SEEK_PREVIEW_KEY = 'tts-seek-preview';
// The A-B repeat span, tinted under the spoken highlight.
const LOOP_KEY = 'tts-loop';
const LOOP_TINT_OPACITY = '0.12';
// In word mode, the sounding sentence tinted under the spoken word.
const SENTENCE_KEY = 'tts-sentence';
const SENTENCE_TINT_OPACITY = '0.2';
// Hook-supplied callbacks rebound on view attach: the constructor-captured
// closures belong to whichever reader hook created the controller and die
@ -118,11 +131,13 @@ export interface TTSViewBindings {
// stop/init overhead allows, which reads as no pause at all.
export const DEFAULT_PARAGRAPH_GAP_SEC = 0.3;
const drawLoopTint = (rects: DOMRectList, options: Record<string, unknown>) => {
const drawTint = (opacity: string) => (rects: DOMRectList, options: Record<string, unknown>) => {
const g = Overlayer.highlight(rects, options);
g.style.opacity = LOOP_TINT_OPACITY;
g.style.opacity = opacity;
return g;
};
const drawLoopTint = drawTint(LOOP_TINT_OPACITY);
const drawSentenceTint = drawTint(SENTENCE_TINT_OPACITY);
export class TTSController extends EventTarget {
// PlaybackSource tag: the media bridge and the session manager consume this
@ -171,6 +186,12 @@ export class TTSController extends EventTarget {
// chunk (see BufferedTTSClient/MediaOverlayClient), so it is the only signal
// needed here. Surfaced as isBuffering() for the player's spinner.
#awaitingAudio = false;
// Opening paragraphs (raw SSML) of the section after the current one, for
// windowed engines' preloads across a chapter end; built once per section.
#nextSectionOpening: { index: number; ssmls: Promise<string[]> } | null = null;
// Signal for queued background preloads: a windowed provider keeps them
// until it aborts, so a voice change or stop must withdraw them.
#preloadAbort = new AbortController();
#ttsDoc: Document | null = null;
#ttsGranularity: TTSGranularity = 'sentence';
#skipInlineAnnotations = false;
@ -216,10 +237,15 @@ export class TTSController extends EventTarget {
ttsClient: TTSClient;
ttsWebClient: TTSClient;
ttsEdgeClient: EdgeTTSClient;
// Readest Voice (premium, Plus/Pro): never the default engine, only chosen
// by picking one of its voices.
ttsReadestClient: BufferedTTSClient;
#readestProvider: ReadestVoiceProvider;
ttsNativeClient: TTSClient | null = null;
ttsMediaOverlayClient: MediaOverlayClient;
ttsWebVoices: TTSVoice[] = [];
ttsEdgeVoices: TTSVoice[] = [];
ttsReadestVoices: TTSVoice[] = [];
ttsNativeVoices: TTSVoice[] = [];
ttsTargetLang: string = '';
@ -234,7 +260,20 @@ export class TTSController extends EventTarget {
) {
super();
this.ttsWebClient = new WebSpeechClient(this);
this.ttsEdgeClient = new EdgeTTSClient(this, appService);
// One per-book cache store for every synthetic engine: they share the
// book's cache.db (see createBookTTSCacheStore). The book key lands in
// init(), after this constructor, hence the lazy resolver.
const cacheStore = createBookTTSCacheStore(
appService,
() => this.bookKey?.split('-')[0] || null,
);
this.ttsEdgeClient = new EdgeTTSClient(this, appService, cacheStore);
this.#readestProvider = new ReadestVoiceProvider(this);
this.ttsReadestClient = new BufferedTTSClient(
cacheStore ? new CachingProvider(this.#readestProvider, cacheStore) : this.#readestProvider,
this,
appService,
);
// Native TTS is backed by Android TextToSpeech and iOS AVSpeechSynthesizer.
// TODO: implement native TTS client for desktop platforms.
if (appService?.isAndroidApp || appService?.isIOSApp) {
@ -419,16 +458,27 @@ export class TTSController extends EventTarget {
async init() {
const availableClients = [];
if (await this.ttsEdgeClient.init()) {
// Started together: each can take seconds (Edge synthesizes a probe
// sentence, system TTS waits for its voices), and play waits on them all.
// Results are still taken in priority order.
const readestReady = this.ttsReadestClient.init();
const edgeReady = this.ttsEdgeClient.init();
const nativeReady = this.ttsNativeClient?.init();
const webReady = this.ttsWebClient.init();
if (await edgeReady) {
availableClients.push(this.ttsEdgeClient);
}
if (this.ttsNativeClient && (await this.ttsNativeClient.init())) {
if (this.ttsNativeClient && (await nativeReady)) {
availableClients.push(this.ttsNativeClient);
this.ttsNativeVoices = await this.ttsNativeClient.getAllVoices();
}
if (await this.ttsWebClient.init()) {
if (await webReady) {
availableClients.push(this.ttsWebClient);
}
// Last: Readest Voice is never the default, only a remembered choice.
if (await readestReady) {
availableClients.push(this.ttsReadestClient);
}
this.ttsClient = availableClients[0] || this.ttsWebClient;
const preferredClientName = TTSUtils.getPreferredClient();
if (preferredClientName) {
@ -441,6 +491,7 @@ export class TTSController extends EventTarget {
}
this.ttsWebVoices = await this.ttsWebClient.getAllVoices();
this.ttsEdgeVoices = await this.ttsEdgeClient.getAllVoices();
this.ttsReadestVoices = await this.ttsReadestClient.getAllVoices();
// A book that ships its own narration should be read by its narrator, not
// synthesized — that is the whole point of having the recording. The
@ -649,6 +700,7 @@ export class TTSController extends EventTarget {
const contents = this.view.renderer.getContents() as { overlayer?: Overlayer }[];
for (const { overlayer } of contents) {
overlayer?.remove(HIGHLIGHT_KEY);
overlayer?.remove(SENTENCE_KEY);
overlayer?.remove(SEEK_PREVIEW_KEY);
}
}
@ -925,13 +977,19 @@ export class TTSController extends EventTarget {
// document + TTS instance per section, so it never disturbs live playback,
// and labels sentences identically to ensureTimeline so packs written here
// and by playback share one manifest.
// Downloads synthesize with the engine the reader listens with: Readest
// Voice when it is active, Edge otherwise.
#downloadClient(): BufferedTTSClient {
return this.ttsClient === this.ttsReadestClient ? this.ttsReadestClient : this.ttsEdgeClient;
}
canDownload(): boolean {
return this.ttsEdgeClient.canDownload();
return this.#downloadClient().canDownload();
}
getTTSDownloader(): TTSDownloader | null {
const edge = this.ttsEdgeClient;
if (!edge.canDownload()) return null;
const client = this.#downloadClient();
if (!client.canDownload()) return null;
const enumerator: SectionEnumerator = {
enumerateSection: async (sectionIndex: number) => {
const sections = this.view.book.sections;
@ -945,7 +1003,7 @@ export class TTSController extends EventTarget {
const { textWalker } = await import('foliate-js/text-walker.js');
const nodeFilter = createTTSNodeFilter();
let granularity: TTSGranularity = this.view.language.isCJK ? 'sentence' : 'word';
const supported = edge.getGranularities();
const supported = client.getGranularities();
if (!supported.includes(granularity)) granularity = supported[0]!;
// getSentences enumerates EVERY segment; parseSSMLMarks drops the
@ -995,32 +1053,32 @@ export class TTSController extends EventTarget {
}
},
};
return new TTSDownloader(enumerator, edge);
return new TTSDownloader(enumerator, client);
}
// Per-section download status keyed by section index, for the podcast UI.
async getSectionCacheStatuses() {
return this.ttsEdgeClient.getSectionCacheStatuses();
return this.#downloadClient().getSectionCacheStatuses();
}
async getCacheBytes() {
return this.ttsEdgeClient.getCacheBytes();
return this.#downloadClient().getCacheBytes();
}
async beginDownloadSections(sections: number[]) {
await this.ttsEdgeClient.beginDownloadSections(sections);
await this.#downloadClient().beginDownloadSections(sections);
}
async completeDownloadSections(sections: number[]) {
await this.ttsEdgeClient.completeDownloadSections(sections);
await this.#downloadClient().completeDownloadSections(sections);
}
async cancelDownloadSections(sections: number[]) {
await this.ttsEdgeClient.cancelDownloadSections(sections);
await this.#downloadClient().cancelDownloadSections(sections);
}
async clearDownloads() {
await this.ttsEdgeClient.clearDownloads();
await this.#downloadClient().clearDownloads();
}
// Whether the active client can ever produce a timeline — it needs a real
@ -1126,6 +1184,7 @@ export class TTSController extends EventTarget {
// client (same as supportsPlaybackInfo/supportsGapControl's comparison).
setSentenceGap(sec: number): void {
this.ttsEdgeClient.setSentenceGap(sec);
this.ttsReadestClient.setSentenceGap(sec);
}
// Universal (not Edge-only) paragraph-to-paragraph gap, in wall-clock
@ -1136,6 +1195,7 @@ export class TTSController extends EventTarget {
// The buffered client needs it too: it schedules this pause as silence on
// its own audio clock rather than letting #delayParagraphGap sleep for it.
this.ttsEdgeClient.setParagraphGap(sec);
this.ttsReadestClient.setParagraphGap(sec);
}
// Abortable delay inserted before auto-advancing to the next paragraph.
@ -1176,6 +1236,10 @@ export class TTSController extends EventTarget {
if (!this.ttsClient.getCapabilities().mediaClock) return null;
const timeline = this.#sectionTimeline;
if (!timeline || this.#timelineSectionIndex !== this.#ttsSectionIndex) return null;
// A client whose voices load asynchronously resolves its voice only when
// the first sentence plays, after the timeline was built: measured
// durations are keyed by that voice. A no-op once they match.
timeline.setVoice(this.ttsClient.getVoiceId());
const duration = timeline.getDuration();
if (!Number.isFinite(duration) || duration <= 0) return null;
let index = this.#currentSentenceIndex;
@ -1188,7 +1252,8 @@ export class TTSController extends EventTarget {
return {
position: timeline.positionAt(index, within),
duration,
measuredFraction: timeline.getMeasuredFraction(),
// The buffer bar: how far synthesized audio reaches past this sentence.
measuredFraction: timeline.getBufferedFraction(index),
};
}
@ -1487,29 +1552,91 @@ export class TTSController extends EventTarget {
async preloadNextSSML(count: number = 4) {
const tts = this.#getTts();
if (!tts) return;
// A windowed engine takes preloads as hints it batches on a GPU worker that
// is slower than an online voice: keep about three minutes of upcoming
// paragraphs requested, however short they are, so the buffer never drains.
const byDuration = !!this.ttsClient.getCapabilities().windowedPrefetch;
const maxCount = byDuration ? PRELOAD_MAX_PARAGRAPHS : count;
const voiceId = this.ttsClient.getVoiceId();
let seconds = 0;
// Gather all next SSMLs and rewind synchronously to avoid a race condition:
// tts.next() replaces TTS.#ranges (used by setMark() during playback).
// If async gaps exist between next()/prev() calls, a concurrent #speak()
// can dispatch marks against the wrong #ranges, causing incorrect highlights
// and accidental page turns.
const estimate = (ssml: string) =>
estimateSentenceSeconds(ssml.replace(/<[^>]*>/g, ' '), this.ttsLang || 'en', voiceId);
const rawSsmls: string[] = [];
for (let i = 0; i < count; i++) {
let sectionEnded = false;
for (let i = 0; i < maxCount; i++) {
const ssml = tts.next();
if (!ssml) break;
if (!ssml) {
sectionEnded = true;
break;
}
rawSsmls.push(ssml);
if (!byDuration) continue;
seconds += estimate(ssml);
if (seconds >= PRELOAD_AHEAD_SEC) break;
}
for (let i = 0; i < rawSsmls.length; i++) {
tts.prev();
}
// The chapter ends inside the budget: carry on into the next one, so a
// chapter change finds its opening already synthesized.
if (byDuration && sectionEnded && seconds < PRELOAD_AHEAD_SEC) {
const nextIndex = this.#ttsSectionIndex + 1;
if (this.#nextSectionOpening?.index !== nextIndex) {
this.#nextSectionOpening = { index: nextIndex, ssmls: this.#sectionOpening(nextIndex) };
}
for (const ssml of await this.#nextSectionOpening.ssmls) {
if (seconds >= PRELOAD_AHEAD_SEC || rawSsmls.length >= maxCount) break;
rawSsmls.push(ssml);
seconds += estimate(ssml);
}
}
const ssmls: string[] = [];
for (const raw of rawSsmls) {
const ssml = await this.#preprocessSSML(raw);
if (!ssml) break;
ssmls.push(ssml);
}
await Promise.all(ssmls.map((ssml) => this.preloadSSML(ssml, new AbortController().signal)));
// In reading order, one after another: a windowed provider queues preloads
// as they arrive, so the paragraph read next must reach it first.
const { signal } = this.#preloadAbort;
for (const ssml of ssmls) {
await this.preloadSSML(ssml, signal);
}
}
// Up to about PRELOAD_AHEAD_SEC of a section's opening paragraphs as raw
// SSML, from a throwaway TTS over a fresh document (never the live one), the
// same way the live session will produce them so preloads match playback.
async #sectionOpening(sectionIndex: number): Promise<string[]> {
const section = this.view.book.sections?.[sectionIndex];
if (!section?.createDocument) return [];
try {
const doc = await this.#createSectionDoc(section);
const { TTS } = await import('foliate-js/tts.js');
const { textWalker } = await import('foliate-js/text-walker.js');
const tts = new TTS(doc, textWalker, createTTSNodeFilter(), () => {}, this.#ttsGranularity);
const voiceId = this.ttsClient.getVoiceId();
const ssmls: string[] = [];
let seconds = 0;
for (let raw = tts.start(); raw && ssmls.length < PRELOAD_MAX_PARAGRAPHS; raw = tts.next()) {
ssmls.push(raw);
const text = raw.replace(/<[^>]*>/g, ' ');
seconds += estimateSentenceSeconds(text, this.ttsLang || 'en', voiceId);
if (seconds >= PRELOAD_AHEAD_SEC) break;
}
return ssmls;
} catch (err) {
console.warn('TTS preload of the next section failed', sectionIndex, err);
return [];
}
}
async #preprocessSSML(ssml?: string) {
@ -1614,6 +1741,16 @@ export class TTSController extends EventTarget {
let sentenceMark: string | undefined;
let sentenceRange: Range | undefined;
let stepAfter: { range?: Range; advance: boolean } | null = null;
let preloadedNext = false;
const preloadNext = () => {
if (preloadedNext || oneTime || signal.aborted) return;
preloadedNext = true;
void this.preloadNextSSML();
};
// Or once this paragraph is slow to become audible (uncached audio
// waits on the network; the next paragraphs should not).
const preloadTimer = setTimeout(preloadNext, PRELOAD_NEXT_AFTER_MS);
signal.addEventListener('abort', () => clearTimeout(preloadTimer), { once: true });
for await (const { code, mark } of iter) {
// Anything the iterator yields means the client is done waiting:
// 'boundary' is the first audible chunk, 'end'/'error' resolve the
@ -1625,6 +1762,10 @@ export class TTSController extends EventTarget {
}
lastCode = code;
if (oneTime || this.state !== 'playing') continue;
// Once this paragraph is audible: stepping through the next ones is
// synchronous DOM work that would otherwise sit in the pause before it.
clearTimeout(preloadTimer);
preloadNext();
if (code === 'end') {
const range = this.#getTts()?.getLastRange();
if (this.#stopsAfter(range)) {
@ -1848,10 +1989,7 @@ export class TTSController extends EventTarget {
}
})
.catch((e) => this.error(e));
if (!oneTime) {
this.preloadNextSSML();
this.dispatchSpeakMark();
}
if (!oneTime) this.dispatchSpeakMark();
}
play() {
@ -1874,7 +2012,6 @@ export class TTSController extends EventTarget {
this.resume();
}
this.#speak(ssml);
this.preloadNextSSML();
}
async pause() {
@ -1891,8 +2028,15 @@ export class TTSController extends EventTarget {
await this.ttsClient.resume().catch((e) => this.error(e));
}
#withdrawPreloads() {
this.#preloadAbort.abort();
this.#preloadAbort = new AbortController();
}
async stop(handover = false) {
this.#awaitingAudio = false;
// A handover (the next paragraph starting) keeps them: they are its audio.
if (!handover) this.#withdrawPreloads();
if (this.#currentSpeakAbortController) {
this.#currentSpeakAbortController.abort();
}
@ -1977,16 +2121,25 @@ export class TTSController extends EventTarget {
} else {
await this.#handleNavigationWithSSML(ssml, isPlaying);
}
if (isPlaying && !byMark) this.preloadNextSSML();
}
async setLang(lang: string) {
this.ttsLang = lang;
// Readest Voice is a remembered choice, never a default: for a book in a
// language it has no voice for, the default engine reads instead, and the
// choice stays remembered for books it can read.
if (
this.ttsClient === this.ttsReadestClient &&
!this.ttsReadestVoices.some((voice) => isSameLang(voice.lang, lang))
) {
this.ttsClient = this.ttsEdgeClient.initialized ? this.ttsEdgeClient : this.ttsWebClient;
}
this.setPrimaryLang(lang);
}
async setPrimaryLang(lang: string) {
if (this.ttsEdgeClient.initialized) this.ttsEdgeClient.setPrimaryLang(lang);
if (this.ttsReadestClient.initialized) this.ttsReadestClient.setPrimaryLang(lang);
if (this.ttsWebClient.initialized) this.ttsWebClient.setPrimaryLang(lang);
if (this.ttsNativeClient?.initialized) this.ttsNativeClient?.setPrimaryLang(lang);
if (this.ttsMediaOverlayClient.initialized) this.ttsMediaOverlayClient.setPrimaryLang(lang);
@ -2005,6 +2158,15 @@ export class TTSController extends EventTarget {
const ttsWebVoices = await this.ttsWebClient.getVoices(lang);
const ttsEdgeVoices = await this.ttsEdgeClient.getVoices(lang);
const ttsNativeVoices = (await this.ttsNativeClient?.getVoices(lang)) ?? [];
// Unavailable (free plan, kill switch) hides the group entirely: no dead
// premium entry in the picker.
const ttsReadestVoices = this.ttsReadestClient.initialized
? (await this.ttsReadestClient.getVoices(lang)).filter((group) => group.voices.length > 0)
: [];
// The picker is open: boot a GPU worker so the first window is warm.
if (ttsReadestVoices.some((group) => group.voices.length > 0)) {
this.#readestProvider.warmup();
}
// The book's own narrator leads the list when there is one: it is the best
// voice available for that book by a wide margin.
const narrationVoices = this.narrationAvailable
@ -2014,6 +2176,7 @@ export class TTSController extends EventTarget {
const voicesGroups = [
...narrationVoices,
...ttsNativeVoices,
...ttsReadestVoices,
...ttsEdgeVoices,
...ttsWebVoices,
];
@ -2022,6 +2185,7 @@ export class TTSController extends EventTarget {
async setVoice(voiceId: string, lang: string) {
this.state = 'setvoice-paused';
this.#withdrawPreloads();
// Switching into or out of narration changes the mark source, not just the
// engine: the current section's TTS instance has to be rebuilt.
@ -2043,13 +2207,23 @@ export class TTSController extends EventTarget {
return;
}
// Never for the engine-default voice (''): Edge and native treat it as
// "any enabled voice", and matching it here would move a paying reader who
// never chose Readest Voice onto it.
const useReadestTTS =
voiceId !== '' &&
this.ttsReadestClient.initialized &&
this.ttsReadestVoices.some((voice) => voice.id === voiceId);
const useEdgeTTS = !!this.ttsEdgeVoices.find(
(voice) => (voiceId === '' || voice.id === voiceId) && !voice.disabled,
);
const useNativeTTS = !!this.ttsNativeVoices.find(
(voice) => (voiceId === '' || voice.id === voiceId) && !voice.disabled,
);
if (useEdgeTTS) {
if (useReadestTTS) {
this.ttsClient = this.ttsReadestClient;
await this.ttsClient.setRate(this.ttsRate);
} else if (useEdgeTTS) {
this.ttsClient = this.ttsEdgeClient;
await this.ttsClient.setRate(this.ttsRate);
} else if (useNativeTTS) {
@ -2142,11 +2316,17 @@ export class TTSController extends EventTarget {
// (no boundaries) is drawn later in prepareSpeakWords. When the user
// forces sentence granularity we keep the sentence highlight, so don't
// suppress it.
this.#suppressMarkHighlight =
const wordMode =
this.ttsClient.getCapabilities().wordBoundaries && this.#highlightGranularity === 'word';
this.#suppressMarkHighlight = wordMode;
const range = this.#getTts()?.setMark(mark.name);
this.#suppressMarkHighlight = false;
this.#speakWordsArmed = !!range;
if (wordMode && range) {
// The previous sentence's last word is no longer sounding.
this.#getPrimaryContent()?.overlayer?.remove(HIGHLIGHT_KEY);
this.#drawSentenceTint(range);
}
if (this.#sectionTimeline && range) {
// Keep the timeline honest as measurements land, then locate the
// audible sentence for position reporting.
@ -2189,6 +2369,24 @@ export class TTSController extends EventTarget {
this.#lastSpeakWordRange = null;
}
// Word mode tints the sentence as soon as its mark is dispatched, before its
// audio may be ready, and keeps it until the next sentence: the tint is where
// the reader is, the word highlight is what is sounding now.
#drawSentenceTint(range: Range) {
const content = this.#getPrimaryContent();
const overlayer = content?.overlayer;
overlayer?.remove(SENTENCE_KEY);
if (!content?.doc || content.index !== this.#ttsSectionIndex) return;
try {
const cfi = this.view.getCFI(content.index, range);
const visibleRange = this.view.resolveCFI(cfi).anchor(content.doc);
if (!visibleRange) return;
overlayer?.add(SENTENCE_KEY, visibleRange, drawSentenceTint, { color: this.options.color });
} catch (e) {
console.error('Failed to tint sentence', e);
}
}
// Re-apply the active highlight after the view relocates (page turn,
// re-render). In word mode this re-draws the current word so the sentence
// never reappears over it; otherwise it re-draws the sentence.
@ -2196,19 +2394,21 @@ export class TTSController extends EventTarget {
if (!this.#attached) return;
if (this.ttsClient.getCapabilities().textHighlight === false) return;
if (this.#wordHighlightActive && this.#lastSpeakWordRange) {
if (this.#speakWordBaseRange) this.#drawSentenceTint(this.#speakWordBaseRange);
this.#getHighlighter()(this.#lastSpeakWordRange.cloneRange());
return;
}
// Word mode during playback: between a sentence's mark and its first word
// boundary there is nothing word-level to re-draw yet, and re-drawing the
// sentence here is exactly the whole-sentence flash word mode suppresses
// at setMark. Draw nothing; the next word boundary paints momentarily.
// Paused/stopped states keep the sentence re-draw (navigation UX).
// boundary only the sentence tint shows; re-drawing the full sentence here
// is exactly the flash word mode suppresses at setMark. Paused/stopped
// states keep the sentence re-draw (navigation UX).
if (
this.state === 'playing' &&
this.ttsClient.getCapabilities().wordBoundaries &&
this.#highlightGranularity === 'word'
) {
const range = this.#getTts()?.getLastRange();
if (range) this.#drawSentenceTint(range);
return;
}
const range = this.#getTts()?.getLastRange();
@ -2326,10 +2526,9 @@ export class TTSController extends EventTarget {
this.#wordHighlightActive = false;
this.#getHighlighter()(range.cloneRange());
} else {
// Highlight the first word immediately so the suppressed sentence
// highlight never appears before playback reaches the first boundary.
// The first word lights when its audio does; until then the sentence
// tint drawn at mark dispatch shows where reading is.
this.#wordHighlightActive = true;
this.dispatchSpeakWord(0);
}
}
@ -2392,6 +2591,9 @@ export class TTSController extends EventTarget {
if (this.ttsEdgeClient.initialized) {
await this.ttsEdgeClient.shutdown();
}
if (this.ttsReadestClient.initialized) {
await this.ttsReadestClient.shutdown();
}
if (this.ttsNativeClient?.initialized) {
await this.ttsNativeClient.shutdown();
}

View file

@ -44,6 +44,14 @@ export interface CacheWarmer {
// Force any newly-completed sections to compact into packs now (and push,
// if pack sync is on) rather than waiting for the debounced timer.
compactCache(): Promise<void>;
// Windowed engines: announce a whole section up front so it synthesizes in
// a few large requests; warmSentence then picks each sentence up as it
// arrives. A fatal failure (e.g. quota) thrown by warmSentence ends the
// download.
prefetchSentences?(
sentences: { lang: string; text: string }[],
signal?: AbortSignal,
): Promise<void>;
}
export interface SectionDownloadProgress {
@ -93,6 +101,11 @@ export class TTSDownloader {
sentences.map((s) => s.label),
);
await this.#warmer.prefetchSentences?.(
sentences.map(({ lang, text }) => ({ lang, text })),
signal,
);
let synthesized = 0;
let failed = false;
let aborted = false;

View file

@ -47,6 +47,7 @@ export interface TTSAudioBufferSourceNode {
export interface TTSAudioContext {
readonly currentTime: number;
readonly outputLatency?: number;
readonly state: string; // 'running' | 'suspended' | 'interrupted' | 'closed'
readonly destination: unknown;
onstatechange: (() => void) | null;
@ -287,8 +288,11 @@ export class WebAudioPlayer implements TTSAudioPlayer {
console.log(
`[TTS] schedule ${generation}:${chunk.index} at ${start.toFixed(2)} dur ${buffer.duration.toFixed(2)}`,
);
if (chunk.index === 0) {
session.onEvent({ type: 'chunk-start', chunkIndex: 0 });
// The first chunk, or one whose predecessor already ended while its audio
// was still being fetched: no onended is left to announce it.
const previous = session.chunks[chunk.index - 1];
if (!previous || previous.ended) {
session.onEvent({ type: 'chunk-start', chunkIndex: chunk.index });
}
}
@ -372,13 +376,17 @@ export class WebAudioPlayer implements TTSAudioPlayer {
if (!session || session.generation !== generation || !ctx) return null;
const first = session.chunks[0];
if (!first) return null;
const t = ctx.currentTime;
// What the speakers play now: the clock runs ahead of them by the output
// latency, which would light each word before it is heard.
const t = ctx.currentTime - (ctx.outputLatency ?? 0);
let active = first;
for (const chunk of session.chunks) {
if (chunk.startTime <= t) active = chunk;
else break;
}
const within = Math.min(Math.max(t - active.startTime, 0), active.duration);
// Negative only before the first chunk starts, so its first word waits
// for its audio instead of lighting during the pause before it.
const within = Math.min(t - active.startTime, active.duration);
return {
chunkIndex: active.index,
mediaTimeSec: active.timing.trimStartSec + within * active.timing.mediaScale,

View file

@ -109,6 +109,19 @@ const createNativePackFs = (dir: string): TTSPackFs => ({
},
});
// The per-book store every synthetic engine of one reader shares: each opens
// the same `cache.db`, and OPFS sync access handles are exclusive, so two
// stores on one book would fight. Entries are namespaced by provider id.
// Null when there is no app context or the user turned the cache off.
export const createBookTTSCacheStore = (
appService: AppService | null | undefined,
getBookHash: () => string | null,
): BookTTSCacheStore | null => {
const cacheConfig = getTTSCacheConfig();
if (!appService || !cacheConfig.enabled) return null;
return new BookTTSCacheStore(appService, getBookHash, cacheConfig.budgetMB * 1024 * 1024);
};
export class BookTTSCacheStore implements TTSCacheStore {
#appService: AppService;
// The book key lands on the controller after construction (init()), so the
@ -176,6 +189,10 @@ export class BookTTSCacheStore implements TTSCacheStore {
return this.#opening;
}
async open(): Promise<void> {
await this.#open();
}
async get(key: string): Promise<TTSCacheEntry | null> {
const opened = await this.#open();
return opened ? opened.store.get(key) : null;

View file

@ -10,7 +10,13 @@
import { md5 } from 'js-md5';
import type { TTSWordBoundary } from '@/libs/edgeTTS';
import type { TTSVoice } from '../types';
import type { SpeechProvider, SpeechSynthesisRequest, SpeechSynthesisResult } from './types';
import type {
PrefetchOptions,
SpeechProvider,
SpeechSynthesisRequest,
SpeechSynthesisResult,
TTSLane,
} from './types';
export interface TTSCacheEntry {
audio: ArrayBuffer;
@ -19,6 +25,8 @@ export interface TTSCacheEntry {
}
export interface TTSCacheStore {
// Open the backing store ahead of the first lookup (no-op if it cannot yet).
open?(): Promise<void>;
get(key: string): Promise<TTSCacheEntry | null>;
put(
key: string,
@ -57,16 +65,27 @@ export interface TTSCacheStore {
export const computeTTSCacheKey = (providerId: string, req: SpeechSynthesisRequest): string =>
md5(JSON.stringify(['tts-v1', providerId, req.lang, req.voice, req.pitch, req.text]));
// Recently read or synthesized sentences kept in memory: a store read costs
// hundreds of ms on device, and audio fetched ahead plays from here at the
// paragraph boundary. A few minutes of speech is a few MB.
const RECENT_BYTES = 16 * 1024 * 1024;
export class CachingProvider implements SpeechProvider {
readonly #inner: SpeechProvider;
readonly #store: TTSCacheStore;
// Dedups whole get-or-synthesize flows: the playback scheduler and the
// preloader routinely race the same sentence.
readonly #inflight = new Map<string, Promise<SpeechSynthesisResult>>();
readonly #recent = new Map<string, SpeechSynthesisResult>();
#recentBytes = 0;
// Present only for a windowed inner provider: callers feature-detect it to
// choose windowed prefetch over synthesizing preloads.
readonly prefetch?: SpeechProvider['prefetch'];
constructor(inner: SpeechProvider, store: TTSCacheStore) {
this.#inner = inner;
this.#store = store;
if (inner.prefetch) this.prefetch = this.#prefetch.bind(this);
}
get id(): string {
@ -81,10 +100,30 @@ export class CachingProvider implements SpeechProvider {
return this.#inner.fallbackVoiceId;
}
get sameLanguageVoicesOnly(): boolean | undefined {
return this.#inner.sameLanguageVoicesOnly;
}
init(): Promise<boolean> {
// Opening the per-book database takes about a second on device: overlap it
// with engine init instead of the first sentence's lookup.
void this.#store.open?.().catch(() => {});
return this.#inner.init();
}
#remember(key: string, result: SpeechSynthesisResult) {
const old = this.#recent.get(key);
if (old) this.#recentBytes -= old.audio.byteLength;
this.#recent.delete(key);
this.#recent.set(key, { audio: result.audio.slice(0), boundaries: result.boundaries });
this.#recentBytes += result.audio.byteLength;
for (const [oldest, entry] of this.#recent) {
if (this.#recentBytes <= RECENT_BYTES) break;
this.#recent.delete(oldest);
this.#recentBytes -= entry.audio.byteLength;
}
}
getAllVoices(): Promise<TTSVoice[]> {
return this.#inner.getAllVoices();
}
@ -93,12 +132,64 @@ export class CachingProvider implements SpeechProvider {
return this.#inner.pickDefaultVoice?.(voices);
}
#prefetch(
reqs: SpeechSynthesisRequest[],
lane: TTSLane,
signal: AbortSignal,
options?: PrefetchOptions,
): void {
if (this.#inner.cacheable === false) {
this.#inner.prefetch?.(reqs, lane, signal, options);
return;
}
void this.#prefetchUncached(reqs, lane, signal, options);
}
async #prefetchUncached(
reqs: SpeechSynthesisRequest[],
lane: TTSLane,
signal: AbortSignal,
options?: PrefetchOptions,
): Promise<void> {
const uncached: SpeechSynthesisRequest[] = [];
const toFill: SpeechSynthesisRequest[] = [];
for (const req of reqs) {
const key = computeTTSCacheKey(this.#inner.id, req);
// Already being filled: still forwarded, so the provider can raise a
// preload's priority once its paragraph starts.
if (this.#inflight.has(key)) {
uncached.push(req);
continue;
}
try {
const cached = this.#recent.get(key) ?? (await this.#store.get(key));
if (cached) {
this.#remember(key, cached);
options?.onDelivered?.(req, { audio: cached.audio, boundaries: cached.boundaries });
continue;
}
} catch {
// Unreadable store: treat as uncached.
}
uncached.push(req);
toFill.push(req);
}
if (signal.aborted || uncached.length === 0) return;
this.#inner.prefetch?.(uncached, lane, signal, options);
// Persist every sentence as it arrives, even one playback never asks for
// (stop, seek): it was synthesized and paid for, so keep it.
for (const req of toFill) {
this.synthesize(req, signal, options).catch(() => {});
}
}
async synthesize(
req: SpeechSynthesisRequest,
signal: AbortSignal,
options?: PrefetchOptions,
): Promise<SpeechSynthesisResult> {
if (this.#inner.cacheable === false) {
return this.#inner.synthesize(req, signal);
return this.#inner.synthesize(req, signal, options);
}
const key = computeTTSCacheKey(this.#inner.id, req);
const pending = this.#inflight.get(key);
@ -106,7 +197,7 @@ export class CachingProvider implements SpeechProvider {
// Joiners get their own buffer: decodeAudioData detaches its input.
return pending.then((result) => ({ ...result, audio: result.audio.slice(0) }));
}
const promise = this.#getOrSynthesize(key, req, signal);
const promise = this.#getOrSynthesize(key, req, signal, options);
this.#inflight.set(key, promise);
try {
return await promise;
@ -120,16 +211,21 @@ export class CachingProvider implements SpeechProvider {
key: string,
req: SpeechSynthesisRequest,
signal: AbortSignal,
options?: PrefetchOptions,
): Promise<SpeechSynthesisResult> {
const recent = this.#recent.get(key);
if (recent) return { audio: recent.audio.slice(0), boundaries: recent.boundaries };
try {
const cached = await this.#store.get(key);
if (cached) {
this.#remember(key, cached);
return { audio: cached.audio.slice(0), boundaries: cached.boundaries };
}
} catch (err) {
console.warn('TTS cache read failed; synthesizing instead', err);
}
const result = await this.#inner.synthesize(req, signal);
const result = await this.#inner.synthesize(req, signal, options);
this.#remember(key, result);
try {
await this.#store.put(
key,

View file

@ -0,0 +1,529 @@
import type { TTSWordBoundary } from '@/libs/edgeTTS';
import { getAPIBaseUrl } from '@/services/environment';
import { getAccessToken, getSubscriptionPlan, isTTSInPlan } from '@/utils/access';
import { fetchWithAuth } from '@/utils/fetch';
import { readNDJSON } from '@/utils/ndjson';
import { estimateSentenceSeconds } from '../ttsDuration';
import type { TTSVoice } from '../types';
import {
type PrefetchOptions,
type SpeechProvider,
SpeechSynthesisFatalError,
SpeechSynthesisPermanentError,
type SpeechSynthesisRequest,
type SpeechSynthesisResult,
type TTSLane,
} from './types';
// Readest Voice: premium voices synthesized on a GPU worker behind
// /api/tts/readest/stream. Sentences are requested in windows (one RunPod job
// per window, one NDJSON line back per sentence), one window in flight per
// lane:
// - listen: windows grow 1 -> 4 -> 8 sentences so the first audio after play,
// seek or a voice change waits for one sentence only, and hold at most about
// 20 s of estimated audio (60 s for a window of background preloads only):
// a sentence that falls due waits behind the window in flight. Requests the
// current paragraph is waiting on fill a window before background preloads
// of later paragraphs, never mixing languages. A window frees the lane as
// soon as its last sentence arrives.
// - download: chapter downloads, up to 64 sentences per window, submitted as
// durable jobs that any worker may run (/api/tts/readest/jobs), up to four
// at a time, and collected when done. A server without jobs (off Workers)
// gets streamed windows instead, one at a time, like listening.
// A sentence stays requested while any caller that asked for it is still
// interested; once every such signal is aborted it is withdrawn, and a window
// nobody wants any more is aborted, which cancels its GPU job server-side.
export const DAILY_QUOTA_EXCEEDED = 'DAILY_QUOTA_EXCEEDED';
const LISTEN_WINDOW_SIZES = [1, 4, 8];
const LISTEN_WINDOW_CHARS = 2000;
const LISTEN_WINDOW_SEC = 20;
// A window of background preloads only: nobody waits on it, so it may carry
// more audio, amortizing the per-request overhead and batching on the GPU.
const LISTEN_BACKGROUND_WINDOW_SEC = 60;
const DOWNLOAD_WINDOW_SENTENCES = 64;
const DOWNLOAD_WINDOW_CHARS = 12000;
const DOWNLOAD_JOBS = 4;
const BUSY_RETRY_MS = 5000;
// Route codes that will fail again for the same sentences.
const PERMANENT_CODES = new Set(['UNKNOWN_VOICE', 'VOICE_TIER_REQUIRED', 'INVALID_INPUT']);
// Job codes worth submitting the window again for: another device of the user
// cancelled the shared job, or its result is gone.
const RESUBMIT_CODES = new Set(['CANCELLED', 'NOT_FOUND']);
interface Entry {
key: string;
req: SpeechSynthesisRequest;
background: boolean;
// Signals of the callers still interested in this sentence.
wanted: Set<AbortSignal>;
settled: boolean;
promise: Promise<SpeechSynthesisResult>;
resolve: (result: SpeechSynthesisResult) => void;
reject: (error: unknown) => void;
}
interface Window {
entries: Entry[];
controller: AbortController;
}
interface Lane {
name: TTSLane;
queue: Entry[];
inflight: Window[];
// Listen lane: position in LISTEN_WINDOW_SIZES for the next window.
sizeIndex: number;
retryTimer: ReturnType<typeof setTimeout> | null;
}
interface WindowLine {
id?: unknown;
audio?: unknown;
boundaries?: unknown;
error?: unknown;
done?: unknown;
}
const abortError = () => new DOMException('Aborted', 'AbortError');
const entryKey = (req: SpeechSynthesisRequest) => `${req.voice}\u0000${req.lang}\u0000${req.text}`;
const decodeBase64 = (base64: string): ArrayBuffer => {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes.buffer;
};
const newLane = (name: TTSLane): Lane => ({
name,
queue: [],
inflight: [],
sizeIndex: 0,
retryTimer: null,
});
export class ReadestVoiceProvider implements SpeechProvider {
readonly id = 'readest-tts';
readonly label = 'Readest Voice';
readonly cacheable = true;
// A sentence in a language without a Readest voice is skipped, never read
// with a wrong-language voice.
readonly sameLanguageVoicesOnly = true;
readonly #events: EventTarget | undefined;
#voices: Promise<TTSVoice[]> | null = null;
#quotaExhausted = false;
#warmupFired = false;
// Whether the server runs download jobs (null: not known yet, so one
// download goes out at a time); without them downloads stream.
#jobsAvailable: boolean | null = null;
readonly #entries = new Map<string, Entry>();
// Names this app instance to the server, which queues the windows of a
// user's devices one after another but lets this instance replace its own.
readonly #clientId = crypto.randomUUID();
readonly #lanes: Record<TTSLane, Lane> = {
listen: newLane('listen'),
download: newLane('download'),
};
readonly #watched = new WeakSet<AbortSignal>();
// `events` receives tts-quota-exceeded.
constructor(events?: EventTarget) {
this.#events = events;
}
// BufferedTTSClient calls getAllVoices before init: both share one request.
getAllVoices(): Promise<TTSVoice[]> {
this.#voices ??= this.#fetchVoices();
return this.#voices;
}
async init(): Promise<boolean> {
// A new session (or day) may have fresh quota.
this.#quotaExhausted = false;
const voices = await this.getAllVoices();
this.#voices = null; // the next init asks again (plan or catalog may change)
return voices.length > 0;
}
// Boots a worker when the voice picker opens; once per provider.
warmup(): void {
if (this.#warmupFired) return;
this.#warmupFired = true;
fetchWithAuth(`${getAPIBaseUrl()}/tts/readest`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ warmup: true }),
}).catch(() => {});
}
synthesize(
req: SpeechSynthesisRequest,
signal: AbortSignal,
options?: PrefetchOptions,
): Promise<SpeechSynthesisResult> {
if (this.#quotaExhausted) {
return Promise.reject(new SpeechSynthesisFatalError(DAILY_QUOTA_EXCEEDED));
}
// No Readest voice for this sentence's language: skip it rather than read
// it with a wrong-language voice.
if (!req.voice) {
return Promise.reject(
new SpeechSynthesisPermanentError('no Readest Voice for this language'),
);
}
if (signal.aborted) return Promise.reject(abortError());
const background = !!options?.background;
let entry = this.#entries.get(entryKey(req));
if (entry) {
this.#want(entry, signal);
if (!background) entry.background = false;
} else {
entry = this.#enqueue(req, this.#lanes.listen, signal, background, !background);
}
this.#pumpAll();
const consumed = entry;
return new Promise((resolve, reject) => {
const onAbort = () => reject(abortError());
signal.addEventListener('abort', onAbort, { once: true });
consumed.promise
.then((result) => {
// Consumed: a later request for the same sentence synthesizes again.
if (this.#entries.get(consumed.key) === consumed) this.#entries.delete(consumed.key);
resolve({ audio: result.audio.slice(0), boundaries: result.boundaries });
}, reject)
.finally(() => signal.removeEventListener('abort', onAbort));
});
}
prefetch(
reqs: SpeechSynthesisRequest[],
lane: TTSLane,
signal: AbortSignal,
options?: PrefetchOptions,
): void {
if (this.#quotaExhausted || signal.aborted) return;
const background = lane === 'listen' && !!options?.background;
const onDelivered = options?.onDelivered;
for (const req of reqs) {
if (!req.voice) continue;
let entry = this.#entries.get(entryKey(req));
if (entry) {
this.#want(entry, signal);
if (!background) entry.background = false;
} else {
entry = this.#enqueue(req, this.#lanes[lane], signal, background, false);
}
if (onDelivered)
entry.promise.then(
(result) => onDelivered(req, result),
() => {},
);
}
this.#pumpAll();
}
async shutdown(): Promise<void> {
for (const lane of Object.values(this.#lanes)) {
if (lane.retryTimer) clearTimeout(lane.retryTimer);
lane.retryTimer = null;
lane.queue = [];
for (const window of lane.inflight) window.controller.abort();
}
for (const entry of this.#entries.values()) this.#settle(entry, abortError());
this.#entries.clear();
}
async #fetchVoices(): Promise<TTSVoice[]> {
try {
const token = await getAccessToken();
// Cheap local gate; the route re-checks the plan on every request.
if (!token || !isTTSInPlan(getSubscriptionPlan(token))) return [];
const res = await fetchWithAuth(`${getAPIBaseUrl()}/tts/readest`, { method: 'GET' });
const data = (await res.json()) as { voices?: TTSVoice[] };
return Array.isArray(data.voices)
? data.voices.map(({ id, name, lang, tier }) => ({ id, name, lang, tier }))
: [];
} catch {
// 503 kill switch, 403 lapsed plan, offline: the engine is unavailable.
return [];
}
}
#enqueue(
req: SpeechSynthesisRequest,
lane: Lane,
signal: AbortSignal,
background: boolean,
front: boolean,
): Entry {
let resolve!: Entry['resolve'];
let reject!: Entry['reject'];
const promise = new Promise<SpeechSynthesisResult>((res, rej) => {
resolve = res;
reject = rej;
});
promise.catch(() => {}); // a prefetch nobody consumes must not surface
const entry: Entry = {
key: entryKey(req),
req,
background,
wanted: new Set(),
settled: false,
promise,
resolve,
reject,
};
this.#entries.set(entry.key, entry);
if (front) lane.queue.unshift(entry);
else lane.queue.push(entry);
this.#want(entry, signal);
return entry;
}
#want(entry: Entry, signal: AbortSignal) {
entry.wanted.add(signal);
if (this.#watched.has(signal)) return;
this.#watched.add(signal);
signal.addEventListener('abort', () => this.#onAbort(signal), { once: true });
}
// A caller went away (stop, seek, voice change, cancelled download).
#onAbort(signal: AbortSignal) {
let hadForeground = false;
for (const entry of [...this.#entries.values()]) {
if (!entry.wanted.delete(signal)) continue;
// Withdrawn sentences the listener waited on; delivered ones do not count.
if (!entry.background && !entry.settled) hadForeground = true;
if (entry.wanted.size === 0) {
this.#settle(entry, abortError());
this.#entries.delete(entry.key);
}
}
// The next listen window starts small again: first audio waits for one.
if (hadForeground) this.#lanes.listen.sizeIndex = 0;
for (const lane of Object.values(this.#lanes)) {
for (const window of lane.inflight) {
if (window.entries.every((e) => e.settled || e.wanted.size === 0)) {
window.controller.abort();
}
}
}
this.#pumpAll();
}
#settle(entry: Entry, error: unknown) {
if (entry.settled) return;
entry.settled = true;
entry.reject(error);
}
#fail(entry: Entry, error: unknown) {
this.#settle(entry, error);
if (this.#entries.get(entry.key) === entry) this.#entries.delete(entry.key);
}
#pumpAll() {
this.#pump(this.#lanes.listen);
this.#pump(this.#lanes.download);
}
#pump(lane: Lane) {
if (lane.retryTimer) return;
lane.queue = lane.queue.filter((e) => !e.settled && e.wanted.size > 0);
const [current] = lane.inflight;
if (lane.name === 'listen' && current) {
// Something the listener is waiting on preempts a window of preloads.
// A window whose sentences have all arrived is just finishing; leave it.
const waiting = lane.queue.some((e) => !e.background);
const unanswered = current.entries.filter((e) => !e.settled);
const serving = unanswered.some((e) => !e.background);
if (waiting && unanswered.length > 0 && !serving) {
lane.sizeIndex = 0;
current.controller.abort();
}
return;
}
const jobs = lane.name === 'download' && this.#jobsAvailable !== false;
while (lane.inflight.length < (jobs && this.#jobsAvailable ? DOWNLOAD_JOBS : 1)) {
const entries = this.#takeWindow(lane);
if (!entries.length) return;
void this.#runWindow(lane, entries, jobs);
}
}
#takeWindow(lane: Lane): Entry[] {
const listen = lane.name === 'listen';
const ordered = listen
? [...lane.queue.filter((e) => !e.background), ...lane.queue.filter((e) => e.background)]
: lane.queue;
const maxSentences = listen ? LISTEN_WINDOW_SIZES[lane.sizeIndex]! : DOWNLOAD_WINDOW_SENTENCES;
const maxChars = listen ? LISTEN_WINDOW_CHARS : DOWNLOAD_WINDOW_CHARS;
const picked: Entry[] = [];
let chars = 0;
let seconds = 0;
for (const entry of ordered) {
if (picked.length >= maxSentences) break;
// One language per window (the route takes a single lang).
if (picked.length && entry.req.lang !== picked[0]!.req.lang) break;
if (picked.length && chars + entry.req.text.length > maxChars) break;
const { text, lang, voice } = entry.req;
const entrySeconds = listen ? estimateSentenceSeconds(text, lang, voice ?? '') : 0;
const backgroundOnly = entry.background && picked.every((e) => e.background);
const capSec = backgroundOnly ? LISTEN_BACKGROUND_WINDOW_SEC : LISTEN_WINDOW_SEC;
if (picked.length && seconds + entrySeconds > capSec) break;
picked.push(entry);
chars += text.length;
seconds += entrySeconds;
}
lane.queue = lane.queue.filter((e) => !picked.includes(e));
if (listen && picked.length) {
lane.sizeIndex = Math.min(lane.sizeIndex + 1, LISTEN_WINDOW_SIZES.length - 1);
}
return picked;
}
async #runWindow(lane: Lane, entries: Entry[], job: boolean) {
const controller = new AbortController();
const window = { entries, controller };
lane.inflight.push(window);
const byId = new Map(entries.map((entry, i) => [`s${i}`, entry]));
let busy = false;
try {
// fetchWithAuth throws on non-OK responses with the route's flat error
// code as the message (DAILY_QUOTA_EXCEEDED, BUSY, ...).
const request = JSON.stringify({
client: this.#clientId,
lane: lane.name,
lang: entries[0]!.req.lang,
segments: [...byId].map(([id, e]) => ({ id, text: e.req.text, voice: e.req.voice })),
});
const body = job
? await this.#collectJob(request, controller.signal)
: (
await fetchWithAuth(`${getAPIBaseUrl()}/tts/readest/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: request,
signal: controller.signal,
})
).body;
if (!body) throw new Error('UPSTREAM_FAILED');
let endError: string | undefined;
for await (const raw of readNDJSON(body)) {
const line = raw as WindowLine;
if (line.done) {
endError = typeof line.error === 'string' ? line.error : undefined;
break;
}
const entry = typeof line.id === 'string' ? byId.get(line.id) : undefined;
if (!entry || entry.settled) continue;
if (typeof line.audio === 'string') {
entry.settled = true;
entry.resolve({
audio: decodeBase64(line.audio),
boundaries: Array.isArray(line.boundaries)
? (line.boundaries as TTSWordBoundary[])
: [],
});
} else {
this.#fail(entry, new SpeechSynthesisPermanentError('synthesis failed'));
}
// Every sentence is in: the terminal line only waits on the job's
// final status, seconds later. Free the lane for the next window now.
if (entries.every((e) => e.settled)) {
controller.abort();
break;
}
}
// Sentences the window never answered are worth retrying. Answered ones
// stay for the caller that has not consumed them yet (#onAbort drops
// them if nobody does).
for (const entry of entries) {
if (!entry.settled) this.#fail(entry, new Error(endError ?? 'UPSTREAM_FAILED'));
}
} catch (error) {
const unanswered = entries.filter((e) => !e.settled);
if (controller.signal.aborted) {
// Preempted or withdrawn: put back whatever is still wanted.
lane.queue.unshift(...unanswered.filter((e) => e.wanted.size > 0));
} else {
const code = error instanceof Error ? error.message : String(error);
if (code === DAILY_QUOTA_EXCEEDED) {
this.#exhaustQuota();
} else if (code === 'JOBS_UNAVAILABLE' || (job && RESUBMIT_CODES.has(code))) {
if (code === 'JOBS_UNAVAILABLE') this.#jobsAvailable = false;
lane.queue.unshift(...unanswered);
} else if (code === 'BUSY') {
// The endpoint is saturated (no turn within the server's wait, or
// too many windows of this user waiting): wait, retry.
busy = true;
lane.queue.unshift(...unanswered);
} else {
const failure = PERMANENT_CODES.has(code)
? new SpeechSynthesisPermanentError(code)
: error;
for (const entry of unanswered) this.#fail(entry, failure);
}
}
} finally {
lane.inflight = lane.inflight.filter((w) => w !== window);
if (busy) {
lane.retryTimer = setTimeout(() => {
lane.retryTimer = null;
this.#pump(lane);
}, BUSY_RETRY_MS);
} else {
this.#pump(lane);
}
}
}
// A download job: submitted, then collected once a worker has finished it.
// The result is the NDJSON a stream window sends. Nobody wanting the window
// any more cancels the job, so its worker stops too.
async #collectJob(request: string, signal: AbortSignal) {
const jobs = `${getAPIBaseUrl()}/tts/readest/jobs`;
const submitted = await fetchWithAuth(jobs, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: request,
signal,
});
const { jobId } = (await submitted.json()) as { jobId: string };
if (!this.#jobsAvailable) {
this.#jobsAvailable = true;
this.#pumpAll();
}
const cancel = () => {
fetchWithAuth(`${jobs}/${jobId}`, { method: 'DELETE' }).catch(() => {});
};
signal.addEventListener('abort', cancel, { once: true });
try {
for (;;) {
// Long-polls; 202 while the job runs.
const res = await fetchWithAuth(`${jobs}/${jobId}`, { method: 'GET', signal });
if (res.status !== 202) return res.body;
}
} finally {
signal.removeEventListener('abort', cancel);
}
}
// Every further request would be refused too: fail everything and tell the
// user once. init() (a new session) clears it.
#exhaustQuota() {
if (!this.#quotaExhausted) {
this.#quotaExhausted = true;
this.#events?.dispatchEvent(new CustomEvent('tts-quota-exceeded'));
}
const fatal = new SpeechSynthesisFatalError(DAILY_QUOTA_EXCEEDED);
for (const lane of Object.values(this.#lanes)) {
lane.queue = [];
for (const window of lane.inflight) window.controller.abort();
}
for (const entry of [...this.#entries.values()]) this.#fail(entry, fatal);
}
}

View file

@ -41,6 +41,29 @@ export class SpeechSynthesisPermanentError extends Error {
}
}
// A failure that ends the whole session (or download): retrying or skipping
// cannot help, e.g. the daily synthesis quota is used up. The buffered client
// stops at once instead of retrying or skipping ahead.
export class SpeechSynthesisFatalError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SpeechSynthesisFatalError';
}
}
// Who a prefetch serves: live listening or a chapter download. Windowed
// providers admit and size the two differently.
export type TTSLane = 'listen' | 'download';
export interface PrefetchOptions {
// Listen lane only: preloads of upcoming paragraphs. They fill windows after
// the requests the current paragraph is waiting on.
background?: boolean;
// Called once per request when its audio arrives (or is already cached), so
// the client can count it as buffered before playback asks for it.
onDelivered?: (req: SpeechSynthesisRequest, result: SpeechSynthesisResult) => void;
}
export interface SpeechProvider {
// Stable identifier: persisted voice/client preferences and cache
// namespaces key off it, so renaming one is a migration.
@ -51,16 +74,35 @@ export interface SpeechProvider {
// (its voices render disabled in the picker).
init(): Promise<boolean>;
getAllVoices(): Promise<TTSVoice[]>;
synthesize(req: SpeechSynthesisRequest, signal: AbortSignal): Promise<SpeechSynthesisResult>;
// `options.background`: a cache fill for a background prefetch; nobody is
// listening for it yet, so a windowed provider keeps it at preload priority.
synthesize(
req: SpeechSynthesisRequest,
signal: AbortSignal,
options?: PrefetchOptions,
): Promise<SpeechSynthesisResult>;
// Engine-specific default-voice policy for a language's candidate list
// (already filtered and sorted); return undefined to accept the first.
pickDefaultVoice?(voices: TTSVoice[]): string | undefined;
// Last-resort voice when nothing matched and no voice was ever selected.
readonly fallbackVoiceId?: string;
// Never voice a sentence with a voice of another language: when a language
// has no voice, the client asks for '' and the provider skips the sentence.
// Off by default (Edge falls back to a multilingual or last-used voice).
readonly sameLanguageVoicesOnly?: boolean;
// Whether synthesized audio may be persisted. Some services forbid
// storing their output; CachingProvider bypasses the store when false.
readonly cacheable?: boolean;
// Release provider resources (network handles, cache databases) when the
// owning client shuts down.
shutdown?(): Promise<void>;
// Window hint for providers that synthesize several sentences per request:
// these requests will be synthesized soon, in this order. Aborting `signal`
// withdraws them. Providers that synthesize per request omit it.
prefetch?(
reqs: SpeechSynthesisRequest[],
lane: TTSLane,
signal: AbortSignal,
options?: PrefetchOptions,
): void;
}

View file

@ -18,6 +18,8 @@ export type TTSVoice = {
name: string;
lang: string;
disabled?: boolean;
// Premium voices: the plan that unlocks them, shown as a badge.
tier?: 'plus' | 'pro';
};
export type TTSVoicesGroup = {

View file

@ -93,6 +93,19 @@ export const findBoundaryIndexAtTime = (
return result;
};
// No word starts before the speech does. A forced aligner can still place the
// first word inside the leading silence, and its words run early by about the
// same amount throughout the clip, so shift them all by that lead. Otherwise
// the second word lights up as soon as the first becomes audible.
export const alignBoundariesToSpeech = <T extends { offset: number }>(
boundaries: T[],
speechStartSec: number,
): T[] => {
const lead = Math.round(speechStartSec * TICKS_PER_SECOND) - (boundaries[0]?.offset ?? Infinity);
if (!(lead > 0)) return boundaries;
return boundaries.map((boundary) => ({ ...boundary, offset: boundary.offset + lead }));
};
// Extract the sub-range covering [start, end) of base.toString(). Walks the
// text nodes intersecting the base range, slicing partially-contained
// boundary nodes the same way Range stringification does.

View file

@ -7,6 +7,7 @@ export interface UserQuota {
export type UserStorageQuota = UserQuota;
export type UserDailyTranslationQuota = UserQuota;
export type UserDailyTTSQuota = UserQuota;
export type QuotaType = {
name: string;
tooltip: string;

View file

@ -1,7 +1,11 @@
import { jwtDecode } from 'jwt-decode';
import { supabase } from '@/utils/supabase';
import { UserPlan } from '@/types/quota';
import { DEFAULT_DAILY_TRANSLATION_QUOTA, DEFAULT_STORAGE_QUOTA } from '@/services/constants';
import {
DEFAULT_DAILY_TRANSLATION_QUOTA,
DEFAULT_DAILY_TTS_QUOTA,
DEFAULT_STORAGE_QUOTA,
} from '@/services/constants';
import { isWebAppPlatform } from '@/services/environment';
import { getDailyUsage } from '@/services/translators/utils';
import { getRuntimeConfig } from '@/services/runtimeConfig';
@ -223,6 +227,21 @@ export const getTranslationQuota = (plan: UserPlan): number => {
);
};
/**
* Plans that include the self-hosted premium TTS engine ("Readest Voice"):
* Plus and Pro subscriptions only. Unlike EMAIL_IN_PLANS / CLOUD_SYNC_PLANS
* this deliberately excludes `purchase` (lifetime): synthesis has a recurring
* per-character GPU cost that a one-time purchase does not fund.
*/
export const TTS_PLANS: readonly UserPlan[] = ['plus', 'pro'];
export const isTTSInPlan = (plan: UserPlan): boolean => TTS_PLANS.includes(plan);
export const getTTSQuota = (plan: UserPlan): number => {
const fixedQuota = parseInt(process.env['TTS_FIXED_QUOTA'] ?? '0');
return fixedQuota || DEFAULT_DAILY_TTS_QUOTA[plan] || 0;
};
export const getTranslationPlanData = (token: string) => {
const data = jwtDecode<Token>(token) || {};
const plan: UserPlan = data['plan'] || 'free';

View file

@ -0,0 +1,25 @@
// Newline-delimited JSON from a byte stream, one parsed value per line, as the
// lines arrive. The streaming TextDecoder keeps multi-byte characters intact
// across chunk boundaries.
export async function* readNDJSON(body: ReadableStream<Uint8Array>): AsyncGenerator<unknown> {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
for (;;) {
const { done, value } = await reader.read();
buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
let newline = buffer.indexOf('\n');
while (newline >= 0) {
const line = buffer.slice(0, newline).trim();
buffer = buffer.slice(newline + 1);
if (line) yield JSON.parse(line);
newline = buffer.indexOf('\n');
}
if (done) break;
}
if (buffer.trim()) yield JSON.parse(buffer);
} finally {
reader.releaseLock();
}
}

View file

@ -2,6 +2,7 @@ import { createSupabaseAdminClient } from '@/utils/supabase';
export const USAGE_TYPES = {
TRANSLATION_CHARS: 'translation_chars',
TTS_CHARS: 'tts_chars',
} as const;
export const QUOTA_TYPES = {

Some files were not shown because too many files have changed in this diff Show more