feat(voice): read selected passages in chat, mastery and reading

This commit is contained in:
FSOTM
2026-11-01 22:52:30 +08:00
parent f7aed0744c
commit 70031420a6
9 changed files with 538 additions and 195 deletions

View File

@@ -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.
<div align="center">

View File

@@ -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 = (
<>
<div className="flex items-center gap-1">
<div onPointerDown={event => event.preventDefault()}>
<PlayAudioButton
key={quote}
content={quote}
autoPlayFresh={false}
selection
className="inline-flex h-7 w-7 items-center justify-center rounded-lg text-[var(--foreground)] transition hover:bg-[var(--muted)]"
/>
</div>
<div className="flex items-center gap-0.5 pr-1">
{ANNOTATION_COLORS.map(swatch => (
<Tooltip key={swatch} label={t(swatchLabel(swatch))} side="top">

View File

@@ -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}
/>
<SelectionSpeechToolbar rootRef={messagesContainerRef} />
</div>
{!sessionError && (

View File

@@ -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<HTMLDivElement | null> }) {
const { t } = useTranslation()
const [passage, setPassage] = useState<Passage | null>(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(
<div
role="toolbar"
aria-label={t('Selected text')}
onPointerDown={event => 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 }}
>
<PlayAudioButton
key={passage.text}
content={passage.text}
autoPlayFresh={false}
selection
className="inline-flex size-10 items-center justify-center rounded-xl transition hover:opacity-80 focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--primary)]"
/>
</div>,
document.body
)
}

View File

@@ -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<string> {
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<HTMLAudioElement | null>(null)
const urlRef = useRef<string | null>(null)
const abortRef = useRef<AbortController | null>(null)
const genRef = useRef(0)
const autoPlayedRef = useRef(false)
const playbackOwnerRef = useRef<object>({})
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 (
<div className={`relative inline-flex ${selection ? 'h-full' : ''}`}>
<Tooltip
label={state !== 'idle' ? t('Stop') : t(selection ? 'Read aloud' : 'Play aloud')}
side="top"
>
<button
type="button"
onClick={handleClick}
aria-label={state !== 'idle' ? t('Stop') : t(selection ? 'Read aloud' : 'Play aloud')}
aria-busy={state === 'loading'}
className={
className ??
`inline-flex items-center justify-center rounded-md p-1 transition-colors ${
state === 'playing'
? 'text-[var(--primary)]'
: 'text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50 hover:text-[var(--foreground)]'
}`
}
>
{state === 'loading' ? (
<Loader2 size={15} strokeWidth={1.8} className="animate-spin" />
) : state === 'playing' ? (
<Square size={13} strokeWidth={1.8} className="fill-current" />
) : selection ? (
<Play size={15} strokeWidth={1.8} className="fill-current" />
) : (
<Volume2 size={15} strokeWidth={1.5} />
)}
</button>
</Tooltip>
</div>
)
}

View File

@@ -2835,6 +2835,7 @@ export default function ChatWorkspace() {
</div>
{selectedPassage ? (
<SelectionActions
text={selectedPassage.text}
anchor={selectedPassage.anchor}
agents={agentOptions}
onAddToChat={addSelectedPassageToChat}

View File

@@ -3,7 +3,8 @@
/**
* What a passage selected in a reply can become.
*
* Two actions, kept apart because they go to different places: "Add to chat"
* Listening plays only the selection. The two conversation actions go to
* different places: "Add to chat"
* quotes the passage into the main composer (it rides the next message as an
* attachment), and "Ask" opens a side chat about it — with Dito unless the
* learner picks a partner, a partner group, or a connected agent from the
@@ -16,6 +17,7 @@ import { ChevronDown, MessagesSquare, TextQuote } from "lucide-react";
import { useTranslation } from "react-i18next";
import ResponderList from "@/components/chat/home/ResponderList";
import { DITO, type SideChatResponder } from "@/lib/side-chat";
import { PlayAudioButton } from "@/components/voice/SpeechButton";
export interface SelectionAnchor {
left: number;
@@ -24,7 +26,7 @@ export interface SelectionAnchor {
bottom: number;
}
const BAR_WIDTH = 232;
const BAR_WIDTH = 272;
const BAR_HEIGHT = 36;
const MENU_WIDTH = 248;
const MENU_MAX_HEIGHT = 320;
@@ -46,12 +48,14 @@ function place(anchor: SelectionAnchor) {
export default function SelectionActions({
anchor,
text,
agents,
onAddToChat,
onAsk,
onDismiss,
}: {
anchor: SelectionAnchor;
text: string;
/** Connected agents (not partners) this account can talk to. */
agents: { name: string; kind?: string }[];
onAddToChat: () => 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 }}
>
<PlayAudioButton
key={text}
content={text}
autoPlayFresh={false}
selection
className={`${segment} w-10 justify-center`}
/>
<span aria-hidden="true" className="my-2 w-px bg-[color-mix(in_srgb,var(--background)_22%,transparent)]" />
<button
type="button"
onClick={onAddToChat}

View File

@@ -32,7 +32,6 @@ import {
Square,
UserRound,
UsersRound,
Volume2,
X,
Trash2,
type LucideIcon,
@@ -63,11 +62,8 @@ import {
GeneratedOutputFileActions,
supportsGeneratedOutputActions,
} from "@/components/chat/GeneratedOutputFileActions";
import { useVoiceAutoplay } from "@/hooks/useVoiceAutoplay";
import {
SPEECH_PLAYBACK_FAILURE_MESSAGE,
SPEECH_TIMEOUT_MESSAGE,
} from "@/lib/voice-settings";
import { PlayAudioButton } from "@/components/voice/SpeechButton";
export { PlayAudioButton } from "@/components/voice/SpeechButton";
import { extractMathAnimatorResult } from "@/lib/math-animator-types";
import { extractVideoLessonResult } from "@/lib/video-lesson-types";
import {
@@ -1440,193 +1436,6 @@ export function CopyActionButton({
);
}
// 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<string> {
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<HTMLAudioElement | null>(null);
const urlRef = useRef<string | null>(null);
const abortRef = useRef<AbortController | null>(null);
const genRef = useRef(0);
const autoPlayedRef = useRef(false);
const playbackOwnerRef = useRef<object>({});
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 (
<div className="relative inline-flex">
<Tooltip
label={state === "playing" ? t("Stop") : t("Play aloud")}
side="top"
>
<button
type="button"
onClick={handleClick}
aria-label={state === "playing" ? t("Stop") : t("Play aloud")}
className={`inline-flex items-center justify-center rounded-md p-1 transition-colors ${
state === "playing"
? "text-[var(--primary)]"
: "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50 hover:text-[var(--foreground)]"
}`}
>
{state === "loading" ? (
<Loader2 size={15} strokeWidth={1.8} className="animate-spin" />
) : state === "playing" ? (
<Square size={13} strokeWidth={1.8} className="fill-current" />
) : (
<Volume2 size={15} strokeWidth={1.5} />
)}
</button>
</Tooltip>
</div>
);
}
function BranchNavigator({
info,

View File

@@ -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<HTMLDivElement>()
render(
<>
<div ref={rootRef}>
<p data-testid="lesson">I am learning.</p>
</div>
<SelectionSpeechToolbar rootRef={rootRef} />
</>
)
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(
<SelectionActions
text="Only this sentence."
anchor={{ left: 40, right: 140, top: 180, bottom: 200 }}
agents={[]}
onAsk={ask}
onAddToChat={quote}
onDismiss={vi.fn()}
/>
)
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(
<PlayAudioButton
content="Replay this particular selection."
autoPlayFresh={false}
selection
/>
)
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(
<PlayAudioButton content="Cancel this pending request." autoPlayFresh={false} selection />
)
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(
<>
<PlayAudioButton content="First selection." autoPlayFresh={false} selection />
<PlayAudioButton content="Whole message." autoPlayFresh={false} />
</>
)
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(<PlayAudioButton content="Provider error selection." autoPlayFresh={false} selection />)
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()
})
})