From 70031420a6f7386a286270ea86cd4bb9481d3b56 Mon Sep 17 00:00:00 2001 From: FSOTM <45114873+FSOTM@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:52:30 +0800 Subject: [PATCH] feat(voice): read selected passages in chat, mastery and reading --- README.md | 2 + web/components/reading/AnnotationPopover.tsx | 10 + .../space/learning/MasteryStudy.tsx | 2 + .../voice/SelectionSpeechToolbar.tsx | 113 +++++++++ web/components/voice/SpeechButton.tsx | 217 ++++++++++++++++++ .../chat/components/ChatWorkspace.tsx | 1 + .../chat/components/SelectionActions.tsx | 17 +- .../chat/messages/ChatMessageList.tsx | 195 +--------------- web/tests/selection-speech.spec.tsx | 176 ++++++++++++++ 9 files changed, 538 insertions(+), 195 deletions(-) create mode 100644 web/components/voice/SelectionSpeechToolbar.tsx create mode 100644 web/components/voice/SpeechButton.tsx create mode 100644 web/tests/selection-speech.spec.tsx 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 ( +
+ + + +
+ ) +} 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 }} > + +