fix(tts): resume queued downloads with the session's voice, close the sheet on a failed start (#6739)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run

- A queued download resumed as soon as read aloud had a controller, before
  its clients initialized, so it used the default engine (Edge) while
  playback went on with the chosen voice (e.g. a Readest voice): the
  chapter downloaded in the wrong voice. The book now attaches to the
  download manager only once the clients are initialized.
- The full player can open before init; a start that then failed hid the
  mini player but left the sheet open with dead controls. A failed start
  now closes it too.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-10-13 03:39:28 +08:00 • committed by GitHub
parent e51ca5ca08
commit 2ea1a5328b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 69 additions and 10 deletions

View file

@ -449,6 +449,37 @@ describe('useTTSControl changing the voice', () => {
});
});
describe('useTTSControl a start that fails', () => {
beforeEach(() => {
ttsControllerInstances.length = 0;
pendingInitResolvers.length = 0;
});
afterEach(() => {
cleanup();
});
it('closes the player sheet it may have opened early', async () => {
const onRequestHidePanel = vi.fn();
const FailingHarness = () => {
useTTSControl({ bookKey: 'book-1', onRequestHidePanel });
return null;
};
vi.spyOn(console, 'error').mockImplementation(() => {});
render(<FailingHarness />);
await act(async () => {
const started = eventDispatcher.dispatch('tts-speak', { bookKey: 'book-1' });
for (let i = 0; i < 10; i++) await Promise.resolve();
(
ttsControllerInstances[0] as { initViewTTS: ReturnType<typeof vi.fn> }
).initViewTTS.mockRejectedValueOnce(new Error('no text on this page'));
while (pendingInitResolvers.length > 0) pendingInitResolvers.shift()!();
await started;
});
expect(onRequestHidePanel).toHaveBeenCalled();
});
});
describe('useTTSControl stopping while a start is still initializing', () => {
beforeEach(() => {
ttsControllerInstances.length = 0;

View file

@ -82,7 +82,7 @@ describe('useTTSDownloads', () => {
},
});
const getController = () => controller;
const { result } = renderHook(() => useTTSDownloads('bookhash', getController, false));
const { result } = renderHook(() => useTTSDownloads('bookhash', getController, false, true));
await waitFor(() =>
expect(result.current.chapters.map((c) => [c.label, c.startSection, c.endSection])).toEqual([
@ -100,7 +100,7 @@ describe('useTTSDownloads', () => {
},
});
mocks.getBookData.mockReturnValue({ bookDoc: { toc: [{ label: 'Broken', href: '' }] } });
const { result } = renderHook(() => useTTSDownloads('bookhash', () => controller, false));
const { result } = renderHook(() => useTTSDownloads('bookhash', () => controller, false, true));
await waitFor(() =>
expect(result.current.chapters[0]).toMatchObject({
key: 'section-0',
@ -126,7 +126,7 @@ describe('useTTSDownloads', () => {
bookDoc: { toc: [{ label: key, href: '0' }] },
}));
const { result, rerender } = renderHook(
({ key, controller }) => useTTSDownloads(key, () => controller, false),
({ key, controller }) => useTTSDownloads(key, () => controller, false, true),
{ initialProps: { key: 'old', controller: oldController } },
);
rerender({ key: 'new', controller: newController });
@ -139,6 +139,23 @@ describe('useTTSDownloads', () => {
expect(result.current.chapters[0]?.label).toBe('new');
});
test('resumes queued downloads only once the session picked its engine', async () => {
const controller = makeController(() => new Map());
const getController = () => controller;
const { rerender } = renderHook(
({ ready }) => useTTSDownloads('bookhash', getController, false, ready),
{ initialProps: { ready: false } },
);
// Before the clients initialize, the controller would download with its
// default engine, not the voice the session is about to read with.
await new Promise((r) => setTimeout(r, 0));
expect(mocks.attachController).not.toHaveBeenCalled();
rerender({ ready: true });
await waitFor(() =>
expect(mocks.attachController).toHaveBeenCalledWith('bookhash', getController),
);
});
test('uses the stable book hash for persisted rows and every manager operation', async () => {
const controller = makeController(() => new Map());
const getController = () => controller;
@ -154,7 +171,7 @@ describe('useTTSDownloads', () => {
);
const { result, unmount } = renderHook(() =>
useTTSDownloads('bookhash-reader-session', getController, false),
useTTSDownloads('bookhash-reader-session', getController, false, true),
);
await waitFor(() =>
@ -191,7 +208,7 @@ describe('useTTSDownloads', () => {
'bookhash',
);
const { result } = renderHook(() => useTTSDownloads('bookhash', getController, true));
const { result } = renderHook(() => useTTSDownloads('bookhash', getController, true, true));
await waitFor(() => expect(controller.getSectionCacheStatuses).toHaveBeenCalledTimes(2));
await waitFor(() => expect(result.current.chapters).toHaveLength(1));
expect(result.current.statusOf(result.current.chapters[0]!)).toBe('none');
@ -221,7 +238,7 @@ describe('useTTSDownloads', () => {
resolveNewer = resolve;
}),
);
const { result } = renderHook(() => useTTSDownloads('bookhash', () => controller, false));
const { result } = renderHook(() => useTTSDownloads('bookhash', () => controller, false, true));
let older: Promise<void> = Promise.resolve();
let newer: Promise<void> = Promise.resolve();
@ -244,7 +261,7 @@ describe('useTTSDownloads', () => {
const controller = makeController(() => new Map());
const getController = () => controller;
const { result } = renderHook(() =>
useTTSDownloads('bookhash-reader-session', getController, false),
useTTSDownloads('bookhash-reader-session', getController, false, true),
);
let finishCancellation: () => void = () => {};

View file

@ -31,7 +31,12 @@ const TTSControl: React.FC<TTSControlProps> = ({ bookKey, gridInsets }) => {
onRequestHidePanel: () => setShowPlayerSheet(false),
});
const downloads = useTTSDownloads(bookKey, tts.getController, showPlayerSheet);
const downloads = useTTSDownloads(
bookKey,
tts.getController,
showPlayerSheet,
tts.ttsClientsInited,
);
const activeSectionIndex = tts.ttsSectionIndex;
const viewSettings = getViewSettings(bookKey);

View file

@ -1080,6 +1080,9 @@ export const useTTSControl = ({ bookKey, onRequestHidePanel }: UseTTSControlProp
} catch (error) {
// A start the user cancelled must not touch the session after it.
if (startGenerationRef.current !== generation) return;
// The full player may already be open (it opens before init): close
// it with the mini player rather than leave dead controls up.
onRequestHidePanel?.();
setShowIndicator(false);
setIsPlaying(false);
eventDispatcher.dispatch('toast', {

View file

@ -40,6 +40,9 @@ export const useTTSDownloads = (
bookKey: string,
getController: () => TTSController | null,
isOpen: boolean,
// The session's clients are initialized, so its engine and voice are
// chosen: a download started earlier would use the default engine.
clientsReady: boolean,
): UseTTSDownloadsResult => {
const _ = useTranslation();
const { getBookData } = useBookDataStore();
@ -63,11 +66,11 @@ export const useTTSDownloads = (
// Bind the book to the manager while a download-capable session is live so
// queued items — including rows restored from a previous session — process.
useEffect(() => {
if (!supported) return;
if (!supported || !clientsReady) return;
ttsDownloadManager.attachController(bookHash, getController);
return () => ttsDownloadManager.detachController(bookHash);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [supported, bookHash]);
}, [supported, clientsReady, bookHash]);
useEffect(() => {
let cancelled = false;