diff --git a/README.md b/README.md
index 7fd1e39a9..e2cbe50f4 100644
--- a/README.md
+++ b/README.md
@@ -610,6 +610,8 @@ Settings is the operational control plane, opening on **General** for interface
**MiniMax speech** — in Settings → Voice, choose MiniMax for text-to-speech and select `speech-2.8-hd`. Configure a MiniMax API key and explicitly select a system voice or enter a custom voice ID. The API base defaults to `https://api.minimax.io/v1`; for the China region use `https://api.minimaxi.com/v1`. Read-aloud and voice previews use the native speech endpoint, with MP3, WAV, FLAC or PCM output, sample rate, speed and language controls. See the [MiniMax speech API](https://platform.minimax.io/docs/api-reference/speech-t2a-http) for voice IDs and account availability.
+**Selected-text speech:** select a word or passage in Chat, Mastery Path, or Reading and click **Read aloud** in the nearby toolbar. Click **Stop** to cancel synthesis or playback. This reads only the selection, uses the active TTS provider and voice configured under **Settings → Voice**, and does not send a chat turn. Selection alone never starts playback. A working speech service is required; this feature does not install or select one for you.
+
**Video Learning** under Settings → Learning & conversation configures YouTube captions and Invidious access for Reading. To use Invidious, set its administrator-managed backend API origin (for example `http://127.0.0.1:3000`) and browser-accessible public origin, test the connection, select Invidious, and save. **Browse Invidious** in Reading's add-material dialog searches videos and accesses connected subscriptions and playlists. YouTube playback uses the official privacy-enhanced player; missing captions remain visible and limit the tutor's evidence without blocking native playback. In a source checkout, run `python scripts/install_extras.py video-learning` for the default YouTube caption loader. Existing Watching links migrate into Reading with conversation history, compatible transcripts, notes, and progress preserved; new timestamp notes are Reading annotations. Bilibili uses its own playback and caption path.
diff --git a/web/components/reading/AnnotationPopover.tsx b/web/components/reading/AnnotationPopover.tsx
index 037fdda64..340549f57 100644
--- a/web/components/reading/AnnotationPopover.tsx
+++ b/web/components/reading/AnnotationPopover.tsx
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import Tooltip from '@/shared/ui/Tooltip'
import { useDevice } from '@/hooks/useDevice'
import { ANNOTATION_COLORS, ANNOTATION_SWATCH, type AnnotationColor } from '@/lib/reading-api'
+import { PlayAudioButton } from '@/components/voice/SpeechButton'
const AddToNote = dynamic(() => import('@/features/notes/components/AddToNote'), { ssr: false })
@@ -171,6 +172,15 @@ export function AnnotationPopover({
const body = (
<>
+
event.preventDefault()}>
+
+
{ANNOTATION_COLORS.map(swatch => (
diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsx
index d5999f75c..e1a41c89c 100644
--- a/web/components/space/learning/MasteryStudy.tsx
+++ b/web/components/space/learning/MasteryStudy.tsx
@@ -24,6 +24,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { ChatMessageList } from "@/features/chat/messages";
+import { SelectionSpeechToolbar } from "@/components/voice/SelectionSpeechToolbar";
import { ChatViewerBridges } from "@/components/chat/home/ChatViewerBridges";
import { buildSessionActivity } from "@/lib/session-activity";
import { TurnNavigator } from "@/components/chat/home/TurnNavigator";
@@ -870,6 +871,7 @@ export function MasteryStudy({
onJump={jumpToTurn}
onJumpToBottom={resumeFollowingLatest}
/>
+
{!sessionError && (
diff --git a/web/components/voice/SelectionSpeechToolbar.tsx b/web/components/voice/SelectionSpeechToolbar.tsx
new file mode 100644
index 000000000..779a82585
--- /dev/null
+++ b/web/components/voice/SelectionSpeechToolbar.tsx
@@ -0,0 +1,113 @@
+'use client'
+
+import { useEffect, useState, type RefObject } from 'react'
+import { createPortal } from 'react-dom'
+import { useTranslation } from 'react-i18next'
+import { textFromDomSelection } from '@/lib/selection-text'
+import { PlayAudioButton } from './SpeechButton'
+
+type Passage = { text: string; left: number; top: number }
+
+/** A speech-only action for learning transcripts that have no quote toolbar. */
+export function SelectionSpeechToolbar({ rootRef }: { rootRef: RefObject
}) {
+ const { t } = useTranslation()
+ const [passage, setPassage] = useState(null)
+
+ useEffect(() => {
+ const root = rootRef.current
+ if (!root) return
+ const update = () => {
+ const selection = window.getSelection()
+ const focused = document.activeElement
+ if (
+ !selection ||
+ selection.isCollapsed ||
+ !selection.rangeCount ||
+ focused?.matches('input,textarea,[contenteditable="true"]')
+ ) {
+ setPassage(null)
+ return
+ }
+ const range = selection.getRangeAt(0)
+ if (!root.contains(range.commonAncestorContainer)) {
+ setPassage(null)
+ return
+ }
+ const text = textFromDomSelection(selection).trim()
+ const rects = range.getClientRects()
+ const rect = rects.length ? rects[rects.length - 1] : range.getBoundingClientRect()
+ if (
+ !text ||
+ !rect.width ||
+ !rect.height ||
+ rect.bottom < 0 ||
+ rect.top > window.innerHeight
+ ) {
+ setPassage(null)
+ return
+ }
+ const top = rect.top >= 60 ? rect.top - 48 : rect.bottom + 8
+ setPassage({
+ text,
+ left: Math.max(12, Math.min(rect.right - 40, window.innerWidth - 52)),
+ top: Math.max(12, Math.min(top, window.innerHeight - 52)),
+ })
+ }
+ const clear = () => {
+ const selection = window.getSelection()
+ if (
+ !selection ||
+ selection.isCollapsed ||
+ !selection.rangeCount ||
+ !root.contains(selection.getRangeAt(0).commonAncestorContainer)
+ )
+ setPassage(null)
+ }
+ root.addEventListener('mouseup', update)
+ root.addEventListener('keyup', update)
+ root.addEventListener('pointerup', update)
+ root.addEventListener('scroll', update)
+ window.addEventListener('resize', update)
+ document.addEventListener('selectionchange', clear)
+ return () => {
+ root.removeEventListener('mouseup', update)
+ root.removeEventListener('keyup', update)
+ root.removeEventListener('pointerup', update)
+ root.removeEventListener('scroll', update)
+ window.removeEventListener('resize', update)
+ document.removeEventListener('selectionchange', clear)
+ }
+ }, [rootRef])
+
+ useEffect(() => {
+ if (!passage) return
+ const escape = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape') return
+ event.stopPropagation()
+ setPassage(null)
+ window.getSelection()?.removeAllRanges()
+ }
+ document.addEventListener('keydown', escape, true)
+ return () => document.removeEventListener('keydown', escape, true)
+ }, [passage])
+
+ if (!passage) return null
+ return createPortal(
+ event.preventDefault()}
+ className="fixed z-[70] size-10 rounded-xl bg-[var(--foreground)] text-[var(--background)] shadow-lg"
+ style={{ left: passage.left, top: passage.top }}
+ >
+
+
,
+ document.body
+ )
+}
diff --git a/web/components/voice/SpeechButton.tsx b/web/components/voice/SpeechButton.tsx
new file mode 100644
index 000000000..87f07fdfa
--- /dev/null
+++ b/web/components/voice/SpeechButton.tsx
@@ -0,0 +1,217 @@
+'use client'
+
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Loader2, Play, Square, Volume2 } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import Tooltip from '@/shared/ui/Tooltip'
+import { apiFetch, apiUrl } from '@/lib/api'
+import { notify } from '@/lib/notifications'
+import { useVoiceAutoplay } from '@/hooks/useVoiceAutoplay'
+import { SPEECH_PLAYBACK_FAILURE_MESSAGE, SPEECH_TIMEOUT_MESSAGE } from '@/lib/voice-settings'
+
+// Speaker button: synthesizes this one reply and plays it. Auto-play of later
+// replies is a Settings preference (`autoPlayFresh`), not a first-click prompt.
+let activePlayback: { owner: object; stop: () => void } | null = null
+// 50 ms of playable unsigned 8-bit PCM silence; an empty WAV cannot unlock playback.
+const SILENT_UNLOCK_WAV =
+ 'data:audio/wav;base64,UklGRrQBAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YZABAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA'
+
+async function ttsErrorMessage(resp: Response): Promise {
+ try {
+ const body = (await resp.json()) as { detail?: unknown }
+ if (typeof body.detail === 'string' && body.detail.trim()) return body.detail
+ if (Array.isArray(body.detail)) {
+ const first = body.detail[0] as { msg?: string } | undefined
+ if (typeof first?.msg === 'string' && first.msg.trim()) return first.msg
+ }
+ } catch {
+ /* non-JSON error body */
+ }
+ return ''
+}
+
+export function PlayAudioButton({
+ content,
+ conversationKey,
+ autoPlayFresh,
+ selection = false,
+ className,
+}: {
+ content: string
+ conversationKey?: string
+ autoPlayFresh: boolean
+ selection?: boolean
+ className?: string
+}) {
+ const { t } = useTranslation()
+ const { autoplayEnabled } = useVoiceAutoplay(conversationKey)
+ const [state, setState] = useState<'idle' | 'loading' | 'playing'>('idle')
+ const audioRef = useRef(null)
+ const urlRef = useRef(null)
+ const abortRef = useRef(null)
+ const genRef = useRef(0)
+ const autoPlayedRef = useRef(false)
+ const playbackOwnerRef = useRef({})
+
+ const cleanup = useCallback(() => {
+ abortRef.current?.abort()
+ abortRef.current = null
+ if (audioRef.current) {
+ audioRef.current.pause()
+ audioRef.current = null
+ }
+ if (urlRef.current) {
+ URL.revokeObjectURL(urlRef.current)
+ urlRef.current = null
+ }
+ }, [])
+
+ const stop = useCallback(() => {
+ genRef.current += 1
+ cleanup()
+ setState('idle')
+ if (activePlayback?.owner === playbackOwnerRef.current) activePlayback = null
+ }, [cleanup])
+
+ const play = useCallback(async () => {
+ activePlayback?.stop()
+ const gen = ++genRef.current
+ abortRef.current?.abort()
+ const ac = new AbortController()
+ abortRef.current = ac
+ activePlayback = { owner: playbackOwnerRef.current, stop }
+ setState('loading')
+
+ // WebKit evaluates media playback eligibility when play() is called. Keep
+ // this element unlocked in the click task, then replace its source after
+ // synthesis completes rather than constructing a new audio element then.
+ const audio = new Audio(SILENT_UNLOCK_WAV)
+ audioRef.current = audio
+ void Promise.resolve(audio.play()).catch(() => {
+ /* Unlocking playback can fail on clients that already permit it. */
+ })
+
+ try {
+ // Let the active provider apply the user's configured voice, format and
+ // language. Provider-specific voice IDs are not portable across services.
+ const resp = await apiFetch(apiUrl('/api/voice/tts'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ text: content }),
+ signal: ac.signal,
+ })
+ if (gen !== genRef.current) return
+ if (!resp.ok) {
+ const detail = await ttsErrorMessage(resp)
+ if (gen !== genRef.current) return
+ notify(
+ t(
+ detail ||
+ (resp.status === 504 ? SPEECH_TIMEOUT_MESSAGE : SPEECH_PLAYBACK_FAILURE_MESSAGE)
+ ),
+ { tone: 'error' }
+ )
+ stop()
+ return
+ }
+ const blob = await resp.blob()
+ if (!blob.size) throw new Error('Speech returned empty audio')
+ if (gen !== genRef.current) return
+ if (urlRef.current) {
+ URL.revokeObjectURL(urlRef.current)
+ urlRef.current = null
+ }
+ const url = URL.createObjectURL(blob)
+ urlRef.current = url
+ audio.src = url
+ audio.load()
+ audio.onended = () => {
+ if (gen !== genRef.current) return
+ setState('idle')
+ cleanup()
+ if (activePlayback?.owner === playbackOwnerRef.current) activePlayback = null
+ }
+ audio.onerror = () => {
+ if (gen !== genRef.current) return
+ notify(t(SPEECH_PLAYBACK_FAILURE_MESSAGE), {
+ tone: 'error',
+ })
+ stop()
+ }
+ await audio.play()
+ if (gen !== genRef.current) {
+ audio.pause()
+ return
+ }
+ setState('playing')
+ } catch (err) {
+ if (gen !== genRef.current) return
+ if (err instanceof Error && err.name === 'AbortError') return
+ notify(t(SPEECH_PLAYBACK_FAILURE_MESSAGE), {
+ tone: 'error',
+ })
+ stop()
+ }
+ }, [cleanup, content, stop, t])
+
+ const handleClick = useCallback(() => {
+ if (state === 'playing' || state === 'loading') {
+ stop()
+ return
+ }
+ void play()
+ }, [play, state, stop])
+
+ // Auto-play a freshly-generated reply when Settings auto-play is on.
+ useEffect(() => {
+ if (!autoPlayFresh || !autoplayEnabled) return
+ if (autoPlayedRef.current) return
+ if (!content.trim()) return
+ autoPlayedRef.current = true
+ const id = window.setTimeout(() => void play(), 0)
+ return () => window.clearTimeout(id)
+ }, [autoPlayFresh, autoplayEnabled, content, play])
+
+ useEffect(
+ () => () => {
+ genRef.current += 1
+ cleanup()
+ if (activePlayback?.owner === playbackOwnerRef.current) activePlayback = null
+ },
+ [cleanup]
+ )
+
+ return (
+
+
+
+ {state === 'loading' ? (
+
+ ) : state === 'playing' ? (
+
+ ) : selection ? (
+
+ ) : (
+
+ )}
+
+
+
+ )
+}
diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsx
index b28abd0a0..8c0a25108 100644
--- a/web/features/chat/components/ChatWorkspace.tsx
+++ b/web/features/chat/components/ChatWorkspace.tsx
@@ -2835,6 +2835,7 @@ export default function ChatWorkspace() {
{selectedPassage ? (
void;
@@ -89,6 +93,15 @@ export default function SelectionActions({
className="flex items-stretch overflow-hidden rounded-xl bg-[var(--foreground)] text-[var(--background)] shadow-lg"
style={{ height: BAR_HEIGHT }}
>
+
+
void } | null = null;
-// 50 ms of playable unsigned 8-bit PCM silence; an empty WAV cannot unlock playback.
-const SILENT_UNLOCK_WAV =
- "data:audio/wav;base64,UklGRrQBAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YZABAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA";
-
-async function ttsErrorMessage(resp: Response): Promise {
- try {
- const body = (await resp.json()) as { detail?: unknown };
- if (typeof body.detail === "string" && body.detail.trim()) return body.detail;
- if (Array.isArray(body.detail)) {
- const first = body.detail[0] as { msg?: string } | undefined;
- if (typeof first?.msg === "string" && first.msg.trim()) return first.msg;
- }
- } catch {
- /* non-JSON error body */
- }
- return "";
-}
-
-export function PlayAudioButton({
- content,
- conversationKey,
- autoPlayFresh,
-}: {
- content: string;
- conversationKey?: string;
- autoPlayFresh: boolean;
-}) {
- const { t } = useTranslation();
- const { autoplayEnabled } = useVoiceAutoplay(conversationKey);
- const [state, setState] = useState<"idle" | "loading" | "playing">("idle");
- const audioRef = useRef(null);
- const urlRef = useRef(null);
- const abortRef = useRef(null);
- const genRef = useRef(0);
- const autoPlayedRef = useRef(false);
- const playbackOwnerRef = useRef({});
-
- const cleanup = useCallback(() => {
- abortRef.current?.abort();
- abortRef.current = null;
- if (audioRef.current) {
- audioRef.current.pause();
- audioRef.current = null;
- }
- if (urlRef.current) {
- URL.revokeObjectURL(urlRef.current);
- urlRef.current = null;
- }
- }, []);
-
- const stop = useCallback(() => {
- genRef.current += 1;
- cleanup();
- setState("idle");
- if (activePlayback?.owner === playbackOwnerRef.current) activePlayback = null;
- }, [cleanup]);
-
- const play = useCallback(async () => {
- activePlayback?.stop();
- const gen = ++genRef.current;
- abortRef.current?.abort();
- const ac = new AbortController();
- abortRef.current = ac;
- activePlayback = { owner: playbackOwnerRef.current, stop };
- setState("loading");
-
- // WebKit evaluates media playback eligibility when play() is called. Keep
- // this element unlocked in the click task, then replace its source after
- // synthesis completes rather than constructing a new audio element then.
- const audio = new Audio(SILENT_UNLOCK_WAV);
- audioRef.current = audio;
- void Promise.resolve(audio.play()).catch(() => {
- /* Unlocking playback can fail on clients that already permit it. */
- });
-
- try {
- const resp = await apiFetch(apiUrl("/api/voice/tts"), {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ text: content }),
- signal: ac.signal,
- });
- if (gen !== genRef.current) return;
- if (!resp.ok) {
- const detail = await ttsErrorMessage(resp);
- if (gen !== genRef.current) return;
- notify(
- t(detail || (resp.status === 504 ? SPEECH_TIMEOUT_MESSAGE : SPEECH_PLAYBACK_FAILURE_MESSAGE)),
- { tone: "error" },
- );
- stop();
- return;
- }
- const blob = await resp.blob();
- if (gen !== genRef.current) return;
- if (urlRef.current) {
- URL.revokeObjectURL(urlRef.current);
- urlRef.current = null;
- }
- const url = URL.createObjectURL(blob);
- urlRef.current = url;
- audio.src = url;
- audio.load();
- audio.onended = () => {
- if (gen !== genRef.current) return;
- setState("idle");
- cleanup();
- if (activePlayback?.owner === playbackOwnerRef.current) activePlayback = null;
- };
- audio.onerror = () => {
- if (gen !== genRef.current) return;
- notify(t(SPEECH_PLAYBACK_FAILURE_MESSAGE), {
- tone: "error",
- });
- stop();
- };
- await audio.play();
- if (gen !== genRef.current) {
- audio.pause();
- return;
- }
- setState("playing");
- } catch (err) {
- if (gen !== genRef.current) return;
- if (err instanceof Error && err.name === "AbortError") return;
- notify(t(SPEECH_PLAYBACK_FAILURE_MESSAGE), {
- tone: "error",
- });
- stop();
- }
- }, [cleanup, content, stop, t]);
-
- const handleClick = useCallback(() => {
- if (state === "playing" || state === "loading") {
- stop();
- return;
- }
- void play();
- }, [play, state, stop]);
-
- // Auto-play a freshly-generated reply when Settings auto-play is on.
- useEffect(() => {
- if (!autoPlayFresh || !autoplayEnabled) return;
- if (autoPlayedRef.current) return;
- if (!content.trim()) return;
- autoPlayedRef.current = true;
- const id = window.setTimeout(() => void play(), 0);
- return () => window.clearTimeout(id);
- }, [autoPlayFresh, autoplayEnabled, content, play]);
-
- useEffect(() => () => {
- genRef.current += 1;
- cleanup();
- if (activePlayback?.owner === playbackOwnerRef.current) activePlayback = null;
- }, [cleanup]);
-
- return (
-
-
-
- {state === "loading" ? (
-
- ) : state === "playing" ? (
-
- ) : (
-
- )}
-
-
-
- );
-}
function BranchNavigator({
info,
diff --git a/web/tests/selection-speech.spec.tsx b/web/tests/selection-speech.spec.tsx
new file mode 100644
index 000000000..23f84f17f
--- /dev/null
+++ b/web/tests/selection-speech.spec.tsx
@@ -0,0 +1,176 @@
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { createRef } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { PlayAudioButton } from '@/components/voice/SpeechButton'
+import SelectionActions from '@/features/chat/components/SelectionActions'
+import { SelectionSpeechToolbar } from '@/components/voice/SelectionSpeechToolbar'
+
+const mock = vi.hoisted(() => ({ fetch: vi.fn(), notify: vi.fn(), audio: [] as MockAudio[] }))
+vi.mock('@/lib/api', () => ({
+ apiUrl: (url: string) => url,
+ apiFetch: (...args: unknown[]) => mock.fetch(...args),
+}))
+vi.mock('@/lib/notifications', () => ({ notify: mock.notify }))
+vi.mock('@/hooks/useVoiceAutoplay', () => ({
+ useVoiceAutoplay: () => ({ autoplayEnabled: false }),
+}))
+vi.mock('@/components/chat/home/ResponderList', () => ({ default: () => null }))
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s }) }))
+
+class MockAudio {
+ src = ''
+ onended: (() => void) | null = null
+ onerror: (() => void) | null = null
+ play = vi.fn(async () => undefined)
+ pause = vi.fn()
+ load = vi.fn()
+ constructor(src: string) {
+ this.src = src
+ mock.audio.push(this)
+ }
+}
+
+beforeEach(() => {
+ mock.fetch.mockReset()
+ mock.notify.mockReset()
+ mock.audio.length = 0
+ vi.stubGlobal('Audio', MockAudio)
+ vi.stubGlobal(
+ 'URL',
+ Object.assign(URL, { createObjectURL: vi.fn(() => 'blob:speech'), revokeObjectURL: vi.fn() })
+ )
+ mock.fetch.mockResolvedValue({
+ ok: true,
+ blob: async () => new Blob(['test audio'], { type: 'audio/mpeg' }),
+ })
+})
+
+describe('selected-text speech', () => {
+ it('exposes a nearby speech-only action in a learning transcript, even for one character', async () => {
+ const rootRef = createRef()
+ render(
+ <>
+
+
+ >
+ )
+ const range = document.createRange()
+ range.setStart(screen.getByTestId('lesson').firstChild!, 0)
+ range.setEnd(screen.getByTestId('lesson').firstChild!, 1)
+ Object.defineProperty(range, 'getClientRects', {
+ value: () => [{ left: 100, right: 110, top: 130, bottom: 150, width: 10, height: 20 }],
+ })
+ window.getSelection()!.removeAllRanges()
+ window.getSelection()!.addRange(range)
+ fireEvent.mouseUp(screen.getByTestId('lesson'))
+ const toolbar = await screen.findByRole('toolbar', { name: 'Selected text' })
+ expect(toolbar.style.left).toBe('70px')
+ expect(mock.fetch).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Read aloud' }))
+ await waitFor(() => expect(mock.fetch).toHaveBeenCalledTimes(1))
+ expect(JSON.parse(mock.fetch.mock.calls[0][1].body)).toEqual({ text: 'I' })
+ await waitFor(() => expect(mock.audio[0].src).toBe('blob:speech'))
+ await act(async () => {
+ window.getSelection()!.removeAllRanges()
+ document.dispatchEvent(new Event('selectionchange'))
+ })
+ expect(screen.queryByRole('toolbar')).not.toBeInTheDocument()
+ expect(mock.audio[0].pause).toHaveBeenCalled()
+ })
+
+ it('only submits the selected text, never starts a chat turn, and preserves selection', async () => {
+ const ask = vi.fn()
+ const quote = vi.fn()
+ render(
+
+ )
+ const button = screen.getByRole('button', { name: 'Read aloud' })
+ expect(fireEvent.pointerDown(button)).toBe(false)
+ fireEvent.click(button)
+ await waitFor(() => expect(mock.fetch).toHaveBeenCalledTimes(1))
+ const [url, init] = mock.fetch.mock.calls[0]
+ expect(url).toBe('/api/voice/tts')
+ expect(JSON.parse(init.body)).toEqual({ text: 'Only this sentence.' })
+ expect(ask).not.toHaveBeenCalled()
+ expect(quote).not.toHaveBeenCalled()
+ await screen.findByRole('button', { name: 'Stop' })
+ })
+
+ it('uses the current provider settings when replaying a completed selection', async () => {
+ render(
+
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Read aloud' }))
+ await waitFor(() => expect(mock.audio[0].src).toBe('blob:speech'))
+ await act(async () => mock.audio[0].onended?.())
+ fireEvent.click(screen.getByRole('button', { name: 'Read aloud' }))
+ await waitFor(() => expect(mock.audio).toHaveLength(2))
+ await waitFor(() => expect(mock.audio[1].src).toBe('blob:speech'))
+ expect(mock.fetch).toHaveBeenCalledTimes(2)
+ expect(JSON.parse(mock.fetch.mock.calls[1][1].body)).toEqual({
+ text: 'Replay this particular selection.',
+ })
+ })
+
+ it('stops pending synthesis and ignores a late response', async () => {
+ let resolve!: (response: unknown) => void
+ mock.fetch.mockImplementation(
+ () =>
+ new Promise(r => {
+ resolve = r
+ })
+ )
+ render(
+
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Read aloud' }))
+ await waitFor(() => expect(mock.fetch).toHaveBeenCalledTimes(1))
+ fireEvent.click(screen.getByRole('button', { name: 'Stop' }))
+ expect(mock.fetch.mock.calls[0][1].signal.aborted).toBe(true)
+ await act(async () => resolve({ ok: true, blob: async () => new Blob(['late']) }))
+ expect(mock.audio[0].src).not.toBe('blob:speech')
+ expect(mock.notify).not.toHaveBeenCalled()
+ })
+
+ it('stops the old selection when another selection or full-message audio starts', async () => {
+ render(
+ <>
+
+
+ >
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Read aloud' }))
+ await waitFor(() => expect(mock.audio[0].src).toBe('blob:speech'))
+ fireEvent.click(screen.getByRole('button', { name: 'Play aloud' }))
+ await waitFor(() => expect(mock.audio).toHaveLength(2))
+ expect(mock.audio[0].pause).toHaveBeenCalled()
+ await waitFor(() => expect(mock.audio[1].src).toBe('blob:speech'))
+ })
+
+ it('reports provider errors instead of silently pretending to play', async () => {
+ mock.fetch.mockResolvedValue({
+ ok: false,
+ status: 502,
+ json: async () => ({ detail: 'Speech service unavailable' }),
+ })
+ render( )
+ fireEvent.click(screen.getByRole('button', { name: 'Read aloud' }))
+ await waitFor(() =>
+ expect(mock.notify).toHaveBeenCalledWith('Speech service unavailable', { tone: 'error' })
+ )
+ expect(screen.getByRole('button', { name: 'Read aloud' })).toBeVisible()
+ })
+})