From 75aeb8b69476e59e0bf965139e53ffab402565e8 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 12 Nov 2026 21:18:05 -0600 Subject: [PATCH 01/33] feat(read-aloud): add speech playback on web and mobile --- apps/mobile/app.config.ts | 2 +- apps/mobile/package.json | 1 + .../features/read-aloud/ReadAloudButton.tsx | 60 +++ .../src/features/read-aloud/playback.ts | 161 ++++++ .../features/settings/ReadAloudSection.tsx | 383 ++++++++++++++ .../settings/SettingsVoiceRouteScreen.tsx | 2 + .../src/features/threads/ThreadFeed.tsx | 20 + apps/mobile/src/lib/audioSession.ts | 6 +- .../src/persistence/mobile-preferences.ts | 6 + apps/server/src/speech/CloudSpeech.test.ts | 4 + apps/server/src/speech/CloudSpeech.ts | 263 +++++++++- apps/server/src/speech/http.test.ts | 60 +++ apps/server/src/speech/http.ts | 22 + apps/server/src/speech/synthesis.test.ts | 246 +++++++++ apps/server/src/speech/synthesisAudio.ts | 33 ++ .../src/components/chat/MessagesTimeline.tsx | 9 + .../src/components/chat/ReadAloudButton.tsx | 63 +++ .../components/chat/TimelineAssistantRows.tsx | 4 + .../settings/ReadAloudSettingsSection.tsx | 468 ++++++++++++++++++ .../settings/SpeechProviderIcon.tsx | 29 ++ .../settings/VoiceSettingsPanel.tsx | 18 +- .../src/components/settings/settingsSearch.ts | 8 + apps/web/src/speech/readAloud.ts | 81 +++ docs/user/composer.md | 17 + packages/client-runtime/package.json | 1 + packages/client-runtime/src/readAloud.test.ts | 71 +++ packages/client-runtime/src/readAloud.ts | 104 ++++ .../src/voice-input/environment.ts | 27 + .../client-runtime/src/voice-input/index.ts | 2 + packages/contracts/src/environmentHttp.ts | 27 + packages/contracts/src/index.ts | 2 + packages/contracts/src/readAloud.ts | 102 ++++ packages/contracts/src/settings.ts | 3 + packages/shared/package.json | 1 + packages/shared/src/readAloud.test.ts | 33 ++ packages/shared/src/readAloud.ts | 56 +++ pnpm-lock.yaml | 12 + 37 files changed, 2388 insertions(+), 19 deletions(-) create mode 100644 apps/mobile/src/features/read-aloud/ReadAloudButton.tsx create mode 100644 apps/mobile/src/features/read-aloud/playback.ts create mode 100644 apps/mobile/src/features/settings/ReadAloudSection.tsx create mode 100644 apps/server/src/speech/synthesis.test.ts create mode 100644 apps/server/src/speech/synthesisAudio.ts create mode 100644 apps/web/src/components/chat/ReadAloudButton.tsx create mode 100644 apps/web/src/components/settings/ReadAloudSettingsSection.tsx create mode 100644 apps/web/src/components/settings/SpeechProviderIcon.tsx create mode 100644 apps/web/src/speech/readAloud.ts create mode 100644 packages/client-runtime/src/readAloud.test.ts create mode 100644 packages/client-runtime/src/readAloud.ts create mode 100644 packages/contracts/src/readAloud.ts create mode 100644 packages/shared/src/readAloud.test.ts create mode 100644 packages/shared/src/readAloud.ts diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 97fe5cf977acc..65f1ce12aed03 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -385,7 +385,7 @@ const config: ExpoConfig = { { microphonePermission: "Allow T3 Code to use your microphone for voice input.", recordAudioAndroid: true, - enableBackgroundPlayback: false, + enableBackgroundPlayback: true, enableBackgroundRecording: false, }, ], diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 2ab0e38d89e24..9109da3dcc732 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -114,6 +114,7 @@ "expo-secure-store": "~58.0.2", "expo-sensors": "~58.0.4", "expo-sharing": "58.0.22", + "expo-speech": "~58.0.3", "expo-splash-screen": "~58.0.13", "expo-sqlite": "~58.0.15", "expo-symbols": "~58.0.4", diff --git a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx new file mode 100644 index 0000000000000..f6084e8191ce9 --- /dev/null +++ b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx @@ -0,0 +1,60 @@ +import { useSyncExternalStore } from "react"; +import { useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { DEFAULT_READ_ALOUD_SETTINGS } from "@t3tools/contracts"; +import { Pressable } from "react-native"; +import { mobilePreferencesAtom } from "../../state/preferences"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import * as Dialog from "../../components/ui/Dialog"; +import { readAloudController } from "./playback"; + +export function ReadAloudButton({ + id, + text, + buttonSize, + iconSize, +}: { + id: string; + text: string; + buttonSize: number; + iconSize: number; +}) { + const preferences = useAtomValue(mobilePreferencesAtom); + const settings = AsyncResult.isSuccess(preferences) + ? (preferences.value.readAloud ?? DEFAULT_READ_ALOUD_SETTINGS) + : DEFAULT_READ_ALOUD_SETTINGS; + const state = useSyncExternalStore( + readAloudController.subscribe, + readAloudController.getSnapshot, + ); + if (settings.provider === "off") return null; + const active = state.id === id; + const stoppable = active && (state.status === "playing" || state.status === "loading"); + const label = stoppable + ? "Stop reading" + : active && state.status === "paused" + ? "Resume reading" + : "Read aloud"; + return ( + { + if (stoppable) return readAloudController.stop(); + if (active && state.status === "paused") await readAloudController.resume(); + else await readAloudController.start(id, text, settings); + const result = readAloudController.getSnapshot(); + if (result.id === id && result.status === "error") + Dialog.alert("Could not read aloud", result.error); + }} + > + + + ); +} diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts new file mode 100644 index 0000000000000..71ff5e2cf972a --- /dev/null +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -0,0 +1,161 @@ +import { uuidv4 } from "../../lib/uuid"; +import { createReadAloudController, type SpeechPlayback } from "@t3tools/client-runtime/read-aloud"; +import { synthesizeSpeech } from "@t3tools/client-runtime/voice-input"; +import { speechAudioMimeType } from "@t3tools/shared/read-aloud"; +import { createAudioPlayer } from "expo-audio"; +import { File, Paths } from "expo-file-system"; +import * as Speech from "expo-speech"; +import * as Option from "effect/Option"; +import { AppState, Platform } from "react-native"; +import type { ReadAloudSettings } from "@t3tools/contracts"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { environmentSession } from "../../state/session"; +import { createAudioPlaybackSession, disposeAudioPlayer } from "../../lib/audioSession"; +import { runSpeech } from "../voice-input/voiceDestination"; + +function watchForeground(settings: ReadAloudSettings) { + const subscription = AppState.addEventListener("change", (state) => { + if (!settings.backgroundPlayback && state !== "active") readAloudController.pause(); + }); + return () => subscription.remove(); +} + +function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayback { + let done: () => void = () => {}; + let fail: (error: Error) => void = () => {}; + const finished = new Promise((resolve, reject) => { + done = resolve; + fail = reject; + }); + let started = false; + let offset = 0; + let generation = 0; + const player = { + play() { + if (started && Platform.OS === "ios") { + void Speech.resume().catch(fail); + return; + } + started = true; + const current = ++generation; + const start = offset; + Speech.speak(text.slice(start), { + ...(settings.voice ? { voice: settings.voice } : {}), + ...(settings.language !== "auto" ? { language: settings.language } : {}), + rate: settings.speed, + useApplicationAudioSession: true, + onBoundary: (event: { charIndex: number }) => { + if (current === generation) offset = start + event.charIndex; + }, + onDone: () => { + if (current === generation) done(); + }, + onError: (error) => { + if (current === generation) fail(error); + }, + }); + }, + pause() { + if (Platform.OS === "ios") void Speech.pause().catch(fail); + else { + generation++; + void Speech.stop().catch(fail); + } + }, + }; + const stopWatching = watchForeground(settings); + const session = createAudioPlaybackSession( + player, + false, + (requested) => { + if (!requested) readAloudController.pause(); + }, + settings.backgroundPlayback, + ); + return { + play: async () => { + await session.play(); + if (!session.requested) throw new Error("Finish recording before reading aloud."); + }, + pause: () => session.pause(), + stop: () => { + stopWatching(); + session.pause(); + generation++; + void Speech.stop().catch(() => {}); + done(); + }, + finished, + }; +} + +export const readAloudController = createReadAloudController(async (text, settings, signal) => { + if (settings.provider === "system") return systemPlayback(text, settings); + if (settings.provider === "off") throw new Error("Enable read aloud in Settings → Voice."); + const prepared = settings.environmentId + ? Option.getOrNull( + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(settings.environmentId)), + ) + : null; + if (!prepared) + throw new Error("Connect to the read-aloud environment selected in Settings → Voice."); + const bytes = await runSpeech( + synthesizeSpeech(prepared, settings.provider, { + text, + model: settings.model, + voice: settings.voice, + speed: settings.speed, + language: settings.language, + }), + signal, + ); + signal.throwIfAborted(); + const mimeType = speechAudioMimeType(bytes); + const file = new File( + Paths.cache, + `t3-speech-${uuidv4()}.${mimeType === "audio/wav" ? "wav" : mimeType === "audio/aac" ? "aac" : "mp3"}`, + ); + let player: ReturnType; + try { + file.write(bytes); + player = createAudioPlayer(file.uri, { updateInterval: 500 }); + if (settings.provider === "chatgpt") player.setPlaybackRate(settings.speed); + } catch { + if (file.exists) file.delete(); + throw new Error("Could not prepare the generated speech for playback."); + } + const stopWatching = watchForeground(settings); + const session = createAudioPlaybackSession( + player, + false, + (requested) => { + if (!requested) readAloudController.pause(); + }, + settings.backgroundPlayback, + ); + let done: () => void = () => {}; + const finished = new Promise((resolve, reject) => { + done = resolve; + player.addListener("playbackStatusUpdate", (status) => { + if (status.didJustFinish) resolve(); + else if (status.error) reject(new Error("Could not play the generated speech.")); + }); + }); + return { + play: async () => { + if (settings.backgroundPlayback) + player.setActiveForLockScreen(true, { title: "T3 Code", artist: "Read aloud" }); + await session.play(); + if (!session.requested) throw new Error("Finish recording before reading aloud."); + }, + pause: () => session.pause(), + stop: () => { + stopWatching(); + session.pause(); + disposeAudioPlayer(player); + if (file.exists) file.delete(); + done(); + }, + finished, + }; +}); diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx new file mode 100644 index 0000000000000..b6cde220cd7d4 --- /dev/null +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -0,0 +1,383 @@ +import { appAtomRegistry } from "../../state/atom-registry"; +import { useEffect, useState, useSyncExternalStore } from "react"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import * as Option from "effect/Option"; +import * as Speech from "expo-speech"; +import { ScrollView, TextInput, View } from "react-native"; +import { + AuthSettingsWriteScope, + DEFAULT_READ_ALOUD_SETTINGS, + READ_ALOUD_LABELS, + type ReadAloudSettings, + type EnvironmentId, + type SpeechSynthesisCatalog, + type SpeechSynthesisProvider, +} from "@t3tools/contracts"; +import { getSpeechSynthesisModels, setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { useEnvironments } from "../../state/environments"; +import { + useEnvironmentScope, + usePreparedConnection, + environmentSession, +} from "../../state/session"; +import { AppText as Text } from "../../components/ui/AppText"; +import { ListSection } from "../../components/ui/ListSection"; +import { ListActionRow } from "../../components/ui/ListActionRow"; +import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; +import { ListToggleRow } from "../../components/ui/ListToggleRow"; +import { Sheet } from "../../components/ui/Sheet"; +import { Button } from "../../components/ui/Button"; +import { runSpeech } from "../voice-input/voiceDestination"; +import { readAloudController } from "../read-aloud/playback"; + +export function ReadAloudSection() { + const preferences = useAtomValue(mobilePreferencesAtom); + const update = useAtomSet(updateMobilePreferencesAtom); + const settings = AsyncResult.isSuccess(preferences) + ? (preferences.value.readAloud ?? DEFAULT_READ_ALOUD_SETTINGS) + : DEFAULT_READ_ALOUD_SETTINGS; + const prepared = Option.getOrNull(usePreparedConnection(settings.environmentId)); + const canManage = useEnvironmentScope(settings.environmentId, AuthSettingsWriteScope); + const { environments, presentationById } = useEnvironments(); + + const [subscriptionAvailability, setSubscriptionAvailability] = useState<{ + presentations: typeof presentationById; + ids: ReadonlySet; + } | null>(null); + const [sourceSubscriptions, setSourceSubscriptions] = useState>( + () => new Set(), + ); + const availableSubscriptions = + subscriptionAvailability?.presentations === presentationById + ? subscriptionAvailability.ids + : new Set(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Subscription choices reflect native login availability on each paired environment. + useEffect(() => { + const abort = new AbortController(); + void Promise.all( + [...presentationById.keys()].map((environmentId) => { + const connection = Option.getOrNull( + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)), + ); + if (!connection) return null; + return runSpeech(getSpeechSynthesisModels(connection, "chatgpt"), abort.signal).then( + (catalog) => (catalog.models.length > 0 ? environmentId : null), + () => null, + ); + }), + ).then((ids) => { + if (!abort.signal.aborted) + setSubscriptionAvailability({ + presentations: presentationById, + ids: new Set(ids.filter((id) => id !== null)), + }); + }); + return () => abort.abort(); + }, [presentationById]); + + const [sheet, setSheet] = useState<"source" | "model" | "voice" | null>(null); + const [catalogVersion, setCatalogVersion] = useState(0); + const catalogKey = JSON.stringify([settings.environmentId, settings.provider, catalogVersion]); + const [catalogState, setCatalogState] = useState<{ + key: string; + catalog: SpeechSynthesisCatalog; + error: string; + }>({ key: "", catalog: { models: [] }, error: "" }); + const catalog = catalogState.key === catalogKey ? catalogState.catalog : { models: [] }; + const catalogError = catalogState.key === catalogKey ? catalogState.error : ""; + const [voices, setVoices] = useState([]); + const [error, setError] = useState(""); + const [key, setKey] = useState(""); + const state = useSyncExternalStore( + readAloudController.subscribe, + readAloudController.getSnapshot, + ); + const change = (patch: Partial) => { + readAloudController.stop(); + if (patch.provider || patch.environmentId) setKey(""); + update({ readAloud: { ...settings, ...patch } }); + }; + const cloud = settings.provider === "xai" || settings.provider === "openrouter"; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read installed system voices from the native speech engine. + useEffect(() => { + let mounted = true; + void Speech.getAvailableVoicesAsync().then( + (value) => { + if (mounted) setVoices(value); + }, + () => {}, + ); + return () => { + mounted = false; + }; + }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Load models from the selected environment and cancel obsolete requests. + useEffect(() => { + if (!prepared || settings.provider === "system" || settings.provider === "off") return; + const abort = new AbortController(); + void runSpeech(getSpeechSynthesisModels(prepared, settings.provider), abort.signal).then( + (value) => { + if (!abort.signal.aborted) setCatalogState({ key: catalogKey, catalog: value, error: "" }); + }, + () => { + if (!abort.signal.aborted) + setCatalogState({ + key: catalogKey, + catalog: { models: [] }, + error: + "Could not load speech models. Check the environment connection and speech server setup.", + }); + }, + ); + return () => abort.abort(); + }, [prepared, settings.provider, catalogKey]); + const selectedModel = catalog.models.find((entry) => entry.id === settings.model); + const voiceChoices = + settings.provider === "system" + ? voices.map((voice) => ({ id: voice.identifier, name: voice.name })) + : (selectedModel?.voices ?? []).map((voice) => ({ id: voice, name: voice })); + return ( + <> + + { + setSourceSubscriptions(availableSubscriptions); + setSheet("source"); + }} + /> + {settings.provider !== "off" && ( + <> + {settings.provider !== "system" && settings.provider !== "chatgpt" && ( + setSheet("model")} + /> + )} + {settings.provider !== "chatgpt" && ( + voice.id === settings.voice)?.name || + settings.voice || + "Default" + } + onPress={() => setSheet("voice")} + /> + )} + + change({ speed: settings.speed >= 1.5 ? 0.75 : settings.speed + 0.25 }) + } + /> + change({ backgroundPlayback })} + /> + change({ skipCodeBlocks })} + /> + + state.id === "preview" && state.status !== "error" + ? readAloudController.stop() + : void readAloudController.start( + "preview", + "This is T3 Code. Your agent's response is ready to read aloud.", + settings, + ) + } + /> + + )} + + {cloud && prepared && canManage && ( + + + + + } + /> + + {active && state.status === "loading" + ? "Cancel speech generation" + : active && state.error + ? state.error + : label} + + + ); +} diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index b62f6f8e4b10f..342681160e59d 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,3 +1,4 @@ +import { ReadAloudButton } from "./ReadAloudButton"; import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; @@ -250,6 +251,9 @@ function AssistantMessageMeta({ {!message.streaming && projectedItem ? ( ) : null} + {!copyStreaming && message.text?.trim() && ( + + )} {!message.streaming && ( }> diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx new file mode 100644 index 0000000000000..f370bde4f8b87 --- /dev/null +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -0,0 +1,468 @@ +import { useEffect, useState, useSyncExternalStore } from "react"; +import * as Option from "effect/Option"; +import { + getCloudSpeechKeys, + getSpeechSynthesisModels, + setCloudSpeechKey, +} from "@t3tools/client-runtime/voice-input"; +import type { PreparedConnection } from "@t3tools/client-runtime/connection"; +import { + AuthSettingsWriteScope, + READ_ALOUD_LABELS, + type CloudSpeechProvider, + type ReadAloudSettings, + type EnvironmentId, + type SpeechSynthesisCatalog, + type SpeechSynthesisProvider, +} from "@t3tools/contracts"; +import { useClientSettings, updateClientSettings } from "../../hooks/useSettings"; +import { useEnvironments } from "../../state/environments"; +import { + useEnvironmentScope, + usePreparedConnection, + readPreparedConnection, +} from "../../state/session"; +import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; +import { readAloudController } from "../../speech/readAloud"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { Switch } from "../ui/switch"; +import { + Select, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, + SelectGroup, + SelectGroupLabel, +} from "../ui/select"; +import { SettingsRow, SettingsSearchTarget, SettingsSection } from "./settingsLayout"; +import { SecretInput } from "./SecretInput"; +import { SpeechProviderIcon } from "./SpeechProviderIcon"; + +function ReadAloudKey({ + prepared, + provider, + onSaved, +}: { + prepared: PreparedConnection; + provider: CloudSpeechProvider; + onSaved: () => void; +}) { + const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); + const [configured, setConfigured] = useState(null); + const [draft, setDraft] = useState(""); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read credential presence from the selected environment without exposing its secret. + useEffect(() => { + const controller = new AbortController(); + void runEnvironmentSpeech(getCloudSpeechKeys(prepared), { signal: controller.signal }).then( + (keys) => setConfigured(Boolean(keys[provider])), + () => {}, + ); + return () => controller.abort(); + }, [prepared, provider]); + const save = async (remove: boolean) => { + setBusy(true); + setError(""); + try { + await runEnvironmentSpeech( + setCloudSpeechKey(prepared, provider, remove ? null : draft.trim()), + ); + setDraft(""); + setConfigured(!remove); + onSaved(); + } catch { + setError("Could not save the API key. Check your connection and permissions."); + } + setBusy(false); + }; + return ( + + {configured + ? "Uses the key already saved for dictation on this environment." + : "Stored on the selected environment and shared with dictation."} + {error && {error}} + + } + control={ +
+ setDraft(event.target.value)} + /> + + {configured && ( + + )} +
+ } + /> + ); +} + +export function ReadAloudSettingsSection() { + const settings = useClientSettings((value) => value.readAloud); + const { environments, presentationById } = useEnvironments(); + + const [subscriptionAvailability, setSubscriptionAvailability] = useState<{ + presentations: typeof presentationById; + ids: ReadonlySet; + } | null>(null); + const [sourceSubscriptions, setSourceSubscriptions] = useState>( + () => new Set(), + ); + const availableSubscriptions = + subscriptionAvailability?.presentations === presentationById + ? subscriptionAvailability.ids + : new Set(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Subscription choices reflect native login availability on each paired environment. + useEffect(() => { + const abort = new AbortController(); + void Promise.all( + [...presentationById.keys()].map((environmentId) => { + const connection = readPreparedConnection(environmentId); + if (!connection) return null; + return runEnvironmentSpeech(getSpeechSynthesisModels(connection, "chatgpt"), { + signal: abort.signal, + }).then( + (catalog) => (catalog.models.length > 0 ? environmentId : null), + () => null, + ); + }), + ).then((ids) => { + if (!abort.signal.aborted) + setSubscriptionAvailability({ + presentations: presentationById, + ids: new Set(ids.filter((id) => id !== null)), + }); + }); + return () => abort.abort(); + }, [presentationById]); + + const prepared = Option.getOrNull(usePreparedConnection(settings.environmentId)); + const [catalogVersion, setCatalogVersion] = useState(0); + const catalogKey = JSON.stringify([settings.environmentId, settings.provider, catalogVersion]); + const [catalogState, setCatalogState] = useState<{ + key: string; + catalog: SpeechSynthesisCatalog; + error: string; + }>({ key: "", catalog: { models: [] }, error: "" }); + const catalog = catalogState.key === catalogKey ? catalogState.catalog : { models: [] }; + const error = catalogState.key === catalogKey ? catalogState.error : ""; + const [systemVoices, setSystemVoices] = useState([]); + const state = useSyncExternalStore( + readAloudController.subscribe, + readAloudController.getSnapshot, + ); + const remote = settings.provider !== "off" && settings.provider !== "system"; + const change = (patch: Partial) => { + readAloudController.stop(); + void updateClientSettings({ readAloud: { ...settings, ...patch } }); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- The browser loads its installed voices asynchronously. + useEffect(() => { + if (!("speechSynthesis" in window)) return; + const refresh = () => setSystemVoices(speechSynthesis.getVoices()); + refresh(); + speechSynthesis.addEventListener("voiceschanged", refresh); + return () => speechSynthesis.removeEventListener("voiceschanged", refresh); + }, []); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Fetch speech model and voice choices from the selected environment. + useEffect(() => { + if (!remote || !prepared) return; + const abort = new AbortController(); + void runEnvironmentSpeech( + getSpeechSynthesisModels(prepared, settings.provider as SpeechSynthesisProvider), + { signal: abort.signal }, + ).then( + (result) => { + if (!abort.signal.aborted) setCatalogState({ key: catalogKey, catalog: result, error: "" }); + }, + () => { + if (!abort.signal.aborted) + setCatalogState({ + key: catalogKey, + catalog: { models: [] }, + error: + "Could not load speech models. Check the selected environment and provider configuration.", + }); + }, + ); + return () => abort.abort(); + }, [prepared, remote, settings.provider, catalogKey]); + const voices = + settings.provider === "system" + ? systemVoices.map((voice) => ({ id: voice.voiceURI, name: voice.name })) + : (catalog.models.find((model) => model.id === settings.model)?.voices ?? []).map( + (voice) => ({ id: voice, name: voice }), + ); + const source = remote ? `${settings.provider}:${settings.environmentId}` : settings.provider; + const selectedEnvironment = environments.find( + (entry) => entry.environmentId === settings.environmentId, + ); + return ( + + + { + if (open) setSourceSubscriptions(availableSubscriptions); + }} + onValueChange={(value) => { + if (!value) return; + if (value === "off" || value === "system") + change({ provider: value, environmentId: null, model: "", voice: "" }); + else { + const [provider, ...rest] = value.split(":"); + const environment = environments.find( + (entry) => entry.environmentId === rest.join(":"), + ); + if (!environment) return; + change({ + provider: provider as SpeechSynthesisProvider, + environmentId: environment.environmentId, + model: + provider === "xai" + ? "grok-tts" + : provider === "chatgpt" + ? "chatgpt-read-aloud" + : "", + voice: "", + }); + } + }} + > + + + + + + {READ_ALOUD_LABELS[settings.provider]} + {remote && ( + + {" "} + via {selectedEnvironment?.label ?? "unavailable environment"} + + )} + + + + + + + + + Off + + + + On this device + + + + System voices + + + + {environments.map((environment) => ( + + Cloud via {environment.label} + {(["chatgpt", "xai", "openrouter"] as const) + .filter( + (provider) => + provider !== "chatgpt" || + sourceSubscriptions.has(environment.environmentId), + ) + .map((provider) => ( + + + + {READ_ALOUD_LABELS[provider]} + + + ))} + + ))} + {remote && !selectedEnvironment && ( + Chosen environment (unavailable) + )} + + + } + /> + + {settings.provider === "off" ? null : ( + <> + {remote && prepared && settings.provider !== "chatgpt" && ( + setCatalogVersion((value) => value + 1)} + /> + )} + {remote && settings.provider !== "chatgpt" && ( + { + if (value) change({ model: value, voice: "" }); + }} + > + + + {catalog.models.find((entry) => entry.id === settings.model)?.name || + settings.model || + "Choose a model"} + + + + {catalog.models.map((model) => ( + + {model.name} + + ))} + + + } + /> + )} + {settings.provider !== "chatgpt" && ( + { + if (value) change({ voice: value === "default" ? "" : value }); + }} + > + + + {voices.find((entry) => entry.id === settings.voice)?.name || "Default"} + + + + Default + {voices.map((voice) => ( + + {voice.name} + + ))} + + + ) : ( + change({ voice: event.target.value })} + /> + ) + } + /> + )} + { + if (value) change({ speed: Number(value) }); + }} + > + + + + + {[0.75, 1, 1.25, 1.5].map((speed) => ( + + {speed}× + + ))} + + + } + /> + change({ skipCodeBlocks })} + /> + } + /> + + state.id === "read-aloud-preview" + ? readAloudController.stop() + : void readAloudController.start( + "read-aloud-preview", + "This is T3 Code. Your agent's response is ready to read aloud.", + settings, + ) + } + > + {state.id === "read-aloud-preview" && state.status !== "error" + ? "Stop preview" + : "Play preview"} + + } + /> + + )} + + ); +} diff --git a/apps/web/src/components/settings/SpeechProviderIcon.tsx b/apps/web/src/components/settings/SpeechProviderIcon.tsx new file mode 100644 index 0000000000000..6e5ae1a799a20 --- /dev/null +++ b/apps/web/src/components/settings/SpeechProviderIcon.tsx @@ -0,0 +1,29 @@ +import { openRouterIcon } from "@t3tools/client-runtime/provider-clients"; +import { + CLOUD_SPEECH_LABELS, + READ_ALOUD_LABELS, + ProviderDriverKind, + type CloudSpeechProvider, + type ReadAloudSettings, +} from "@t3tools/contracts"; +import { Volume2Icon, VolumeXIcon } from "lucide-react"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { ProviderPackageIcon } from "../chat/ProviderPackageIcon"; + +export function SpeechProviderIcon({ + provider, +}: { + provider: CloudSpeechProvider | ReadAloudSettings["provider"]; +}) { + if (provider === "off") return ; + if (provider === "system") return ; + if (provider === "openrouter") + return ; + return ( + + ); +} diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 66cacf6eb7ee9..738324f57ceae 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -1,3 +1,4 @@ +import { ReadAloudSettingsSection } from "./ReadAloudSettingsSection"; import { cancelEnvironmentSpeechModelDownload, downloadEnvironmentSpeechModel, @@ -10,7 +11,6 @@ import { updateEnvironmentSpeechModelUnloadTimeout, } from "@t3tools/client-runtime/voice-input"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; -import { openRouterIcon } from "@t3tools/client-runtime/provider-clients"; import { AuthFilesystemReadScope, AuthSettingsWriteScope, @@ -21,7 +21,6 @@ import { type EnvironmentSpeechModel, type EnvironmentSpeechStatus, type ProjectId, - ProviderDriverKind, type SpeechAcceleration, type SpeechBenchmarkTier, type SpeechCustomWords, @@ -85,8 +84,7 @@ import { } from "../../speech/useEnvironmentSpeechInput"; import { ComposerSpeechRecordingPill } from "../chat/ComposerSpeechButton"; import { ProviderModelPicker } from "../chat/ProviderModelPicker"; -import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; -import { ProviderPackageIcon } from "../chat/ProviderPackageIcon"; +import { SpeechProviderIcon as CloudSpeechLogo } from "./SpeechProviderIcon"; import { TraitsPicker } from "../chat/TraitsPicker"; import { VoiceInputSetup } from "../chat/VoiceInputSetup"; import { Badge } from "../ui/badge"; @@ -139,17 +137,6 @@ import { useScopedModelDisabledReason } from "./useScopedModelAvailability"; import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings"; const OFF = "off"; -function CloudSpeechLogo({ provider }: { provider: CloudSpeechProvider }) { - if (provider === "openrouter") - return ; - return ( - - ); -} const formatSize = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`; const SHORTCUT_MODES: Record = { auto: { label: "Auto", hint: "Tap to toggle, hold to talk" }, @@ -1692,6 +1679,7 @@ export function VoiceSettingsPanel() { /> ) : null} + ); } diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 7d7939e7f21f9..68e2c84233558 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -547,6 +547,14 @@ export const SETTINGS_SEARCH_ITEMS = [ "send microphone audio dictation destination speech voice stt transcription environment machine consent privacy cloud OpenAI Grok OpenRouter", ], }, + { + id: "read-aloud", + title: "Read aloud", + to: "/settings/voice", + searchTerms: [ + "tts text to speech speak read aloud ChatGPT subscription Codex Grok OpenRouter voice playback", + ], + }, { id: "voice-microphone", title: "Microphone", diff --git a/apps/web/src/speech/readAloud.ts b/apps/web/src/speech/readAloud.ts new file mode 100644 index 0000000000000..7cffa7bea05bb --- /dev/null +++ b/apps/web/src/speech/readAloud.ts @@ -0,0 +1,81 @@ +import { createReadAloudController, type SpeechPlayback } from "@t3tools/client-runtime/read-aloud"; +import { synthesizeSpeech } from "@t3tools/client-runtime/voice-input"; +import { speechAudioMimeType } from "@t3tools/shared/read-aloud"; +import { readPreparedConnection } from "../state/session"; +import { runEnvironmentSpeech } from "./runEnvironmentSpeech"; + +function systemPlayback(text: string, voice: string, speed: number): SpeechPlayback { + if (!("speechSynthesis" in window)) + throw new Error("System voices are not available in this browser."); + const utterance = new SpeechSynthesisUtterance(text); + utterance.rate = speed; + utterance.voice = speechSynthesis.getVoices().find((entry) => entry.voiceURI === voice) ?? null; + let done: () => void = () => {}; + let reject: (error: Error) => void = () => {}; + const finished = new Promise((resolve, fail) => { + done = resolve; + reject = fail; + }); + utterance.onend = done; + utterance.onerror = () => reject(new Error("The system voice could not read this response.")); + let started = false; + return { + play: async () => { + if (started) speechSynthesis.resume(); + else { + started = true; + speechSynthesis.resume(); + speechSynthesis.speak(utterance); + } + }, + pause: () => speechSynthesis.pause(), + stop: () => { + utterance.onerror = null; + speechSynthesis.cancel(); + done(); + }, + finished, + }; +} + +export const readAloudController = createReadAloudController(async (text, settings, signal) => { + if (settings.provider === "system") return systemPlayback(text, settings.voice, settings.speed); + if (settings.provider === "off") throw new Error("Enable read aloud in Settings → Voice."); + const prepared = settings.environmentId ? readPreparedConnection(settings.environmentId) : null; + if (!prepared) + throw new Error("Connect to the read-aloud environment selected in Settings → Voice."); + const bytes = await runEnvironmentSpeech( + synthesizeSpeech(prepared, settings.provider, { + text, + model: settings.model, + voice: settings.voice, + speed: settings.speed, + language: settings.language, + }), + { signal }, + ); + signal.throwIfAborted(); + const url = URL.createObjectURL( + new Blob([new Uint8Array(bytes)], { type: speechAudioMimeType(bytes) }), + ); + const audio = new Audio(url); + if (settings.provider === "chatgpt") audio.playbackRate = settings.speed; + let done: () => void = () => {}; + const finished = new Promise((resolve, reject) => { + done = resolve; + audio.onended = () => resolve(); + audio.onerror = () => reject(new Error("Could not play the generated speech.")); + }); + return { + play: () => audio.play(), + pause: () => audio.pause(), + stop: () => { + audio.pause(); + audio.removeAttribute("src"); + audio.load(); + URL.revokeObjectURL(url); + done(); + }, + finished, + }; +}); diff --git a/docs/user/composer.md b/docs/user/composer.md index 89a96f120d4d0..51d6b9e257e9e 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -196,6 +196,23 @@ Stashes containing uploaded files must be restored in their original environment Those files are retained for 24 hours. After an upload expires, restore the prompt and use **Attach again** or remove the missing file before sending. +## Read replies aloud + +Choose a speech provider in **Settings → Voice → Read aloud**, then use **Read aloud** +beside a completed assistant reply. Select it again to stop playback. Leaving the +thread stops it. Code blocks are skipped by default. + +System voices run on your device. **ChatGPT Subscription** uses the native Codex CLI +login on your selected environment. Sign in to Codex with ChatGPT there first. +This experimental option uses the desktop app's read-aloud service and its default +voice. If the native login expires, sign in to Codex again. + +Grok TTS and OpenRouter send the reply text through your selected environment and +use API billing. They share the API keys saved for dictation. Choose a model and +voice, then use the preview to try it. + +On mobile, **Background playback** allows speech to continue while the app is in the background. + ## Voice input on web and desktop Use the composer's microphone or `mod+shift+d` to dictate into your draft. Audio diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 6fa96cdd493ae..2ec3d04b84bc7 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -3,6 +3,7 @@ "private": true, "type": "module", "exports": { + "./read-aloud": "./src/readAloud.ts", "./pull-request-diff-fold": { "types": "./src/pullRequestDiffFold.ts", "default": "./src/pullRequestDiffFold.ts" diff --git a/packages/client-runtime/src/readAloud.test.ts b/packages/client-runtime/src/readAloud.test.ts new file mode 100644 index 0000000000000..5573b0168d2de --- /dev/null +++ b/packages/client-runtime/src/readAloud.test.ts @@ -0,0 +1,71 @@ +import { expect, it, vi } from "vite-plus/test"; +import { DEFAULT_READ_ALOUD_SETTINGS } from "@t3tools/contracts"; +import { createReadAloudController, type SpeechPlayback } from "./readAloud.ts"; + +function deferred() { + let resolve: (value: A) => void = () => {}; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +it("stops obsolete requests before they can play and owns only the newest message", async () => { + const old = deferred(); + const started = deferred(); + const finished = deferred(); + const stop = vi.fn(); + const obsoletePlay = vi.fn(async () => {}); + const prepare = vi.fn(async (text: string) => + text === "first" + ? old.promise + : { + play: async () => { + started.resolve(); + }, + pause: () => {}, + stop, + finished: finished.promise, + }, + ); + const controller = createReadAloudController(prepare); + const settings = { ...DEFAULT_READ_ALOUD_SETTINGS, provider: "system" as const }; + const first = controller.start("1", "first", settings); + const second = controller.start("2", "second", settings); + await started.promise; + old.resolve({ play: obsoletePlay, pause: () => {}, stop, finished: Promise.resolve() }); + await first; + expect(obsoletePlay).not.toHaveBeenCalled(); + expect(controller.getSnapshot().id).toBe("2"); + finished.resolve(); + await second; + expect(controller.getSnapshot().status).toBe("idle"); + expect(stop).toHaveBeenCalledTimes(2); +}); + +it("pauses without recursive audio-focus callbacks and ignores failures after cancellation", async () => { + const started = deferred(); + const finished = deferred(); + let controller: ReturnType; + const pause = vi.fn(() => controller.pause()); + controller = createReadAloudController(async () => ({ + play: async () => { + started.resolve(); + }, + pause, + stop: () => finished.resolve(), + finished: finished.promise, + })); + const run = controller.start("1", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + }); + await started.promise; + await controller.resume(); + controller.pause(); + expect(pause).toHaveBeenCalledTimes(1); + expect(controller.getSnapshot().status).toBe("paused"); + controller.stop(); + await run; + expect(controller.getSnapshot().status).toBe("idle"); +}); diff --git a/packages/client-runtime/src/readAloud.ts b/packages/client-runtime/src/readAloud.ts new file mode 100644 index 0000000000000..3090ebf94c0af --- /dev/null +++ b/packages/client-runtime/src/readAloud.ts @@ -0,0 +1,104 @@ +import type { ReadAloudSettings } from "@t3tools/contracts"; +import { readAloudText, splitReadAloudText } from "@t3tools/shared/read-aloud"; + +export type SpeechPlayback = { + play: () => Promise; + pause: () => void; + stop: () => void; + finished: Promise; +}; + +export function createReadAloudController( + prepare: ( + text: string, + settings: ReadAloudSettings, + signal: AbortSignal, + ) => Promise, +) { + type State = { + id: string | null; + status: "idle" | "loading" | "playing" | "paused" | "error"; + error?: string; + }; + let state: State = { id: null, status: "idle" }; + let active: AbortController | null = null; + let playback: SpeechPlayback | null = null; + const listeners = new Set<() => void>(); + const publish = (next: State) => { + state = next; + for (const listener of listeners) listener(); + }; + const stop = () => { + active?.abort(); + active = null; + playback?.stop(); + playback = null; + publish({ id: null, status: "idle" }); + }; + return { + getSnapshot: () => state, + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + stop, + pause() { + if (state.status !== "playing") return; + publish({ ...state, status: "paused" }); + playback?.pause(); + }, + async resume() { + if (state.status !== "paused" || !playback || !active) return; + const owner = active; + const id = state.id; + try { + await playback.play(); + if (active === owner) publish({ ...state, status: "playing" }); + } catch { + if (active === owner) { + stop(); + publish({ id, status: "error", error: "Could not resume speech." }); + } + } + }, + async start(id: string, markdown: string, settings: ReadAloudSettings) { + stop(); + if (settings.provider === "off") return; + const chunks = splitReadAloudText(readAloudText(markdown, settings.skipCodeBlocks)); + if (!chunks.length) return; + const owner = new AbortController(); + active = owner; + try { + for (const chunk of chunks) { + publish({ id, status: "loading" }); + const next = await prepare(chunk, settings, owner.signal); + if (active !== owner) { + next.stop(); + return; + } + playback = next; + // Playback can fail while the platform is still activating its audio session. + void next.finished.catch(() => {}); + await next.play(); + if (active !== owner) return; + publish({ id, status: "playing" }); + await next.finished; + if (active !== owner) return; + next.stop(); + playback = null; + } + if (active === owner) stop(); + } catch (error) { + if (active !== owner) return; + stop(); + publish({ + id, + status: "error", + error: error instanceof Error ? error.message : "Could not read this response.", + }); + } + }, + }; +} diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts index a8ea541f75133..0e768cacba6ea 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -1,3 +1,4 @@ +import type { SpeechSynthesisProvider, SpeechSynthesisRequest } from "@t3tools/contracts"; import { encodeSpeechPcmRequest } from "@t3tools/shared/speech"; import * as Effect from "effect/Effect"; import * as Redacted from "effect/Redacted"; @@ -311,3 +312,29 @@ export const removeEnvironmentSpeechModel = (prepared: PreparedConnection, model path: (urls) => urls.removeModel(), run: ({ client, headers }) => client.removeModel({ headers, payload: { modelId } }), }); + +export const getSpeechSynthesisModels = ( + prepared: PreparedConnection, + provider: SpeechSynthesisProvider, +) => + request({ + group: "voice", + prepared, + method: "GET", + path: (urls) => urls.synthesisModels({ params: { provider } }), + run: ({ client, headers }) => client.synthesisModels({ headers, params: { provider } }), + }); + +export const synthesizeSpeech = ( + prepared: PreparedConnection, + provider: SpeechSynthesisProvider, + payload: SpeechSynthesisRequest, +) => + request({ + group: "voice", + prepared, + method: "POST", + timeoutMs: 130_000, + path: (urls) => urls.synthesize({ params: { provider } }), + run: ({ client, headers }) => client.synthesize({ headers, params: { provider }, payload }), + }); diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index 5283d64eb0dc3..e0b02107b7876 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -39,3 +39,5 @@ export { type VoiceTranscriptionErrorCode, type VoiceTranscriptionOptions, } from "./transcription.ts"; + +export { getSpeechSynthesisModels, synthesizeSpeech } from "./environment.ts"; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 8b8cc6b97e2c1..a4023f90bdcd6 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -1,3 +1,9 @@ +import { + SpeechSynthesisProvider, + SpeechSynthesisRequest, + SpeechSynthesisCatalog, + SpeechSynthesisError, +} from "./readAloud.ts"; import * as Context from "effect/Context"; import type * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; @@ -841,6 +847,27 @@ export class EnvironmentVoiceBodyLimit extends HttpApiMiddleware.Service()( + "SpeechSynthesisError", + { + provider: SpeechSynthesisProvider, + reason: Schema.Literals([ + "missing-key", + "key-changed", + "unreadable-key", + "rejected-key", + "rate-limit", + "unavailable", + "model-unavailable", + "subscription-login-required", + "subscription-expired", + "subscription-unavailable", + ]), + }, + { httpApiStatus: 422 }, +) { + override get message() { + const name = READ_ALOUD_LABELS[this.provider]; + switch (this.reason) { + case "subscription-login-required": + return "Sign in to the Codex CLI with ChatGPT on the selected environment. Read aloud uses its native login."; + case "subscription-expired": + return "The native Codex login expired. Sign in again on the selected environment."; + case "subscription-unavailable": + return "ChatGPT read aloud is unavailable for this account. Check its subscription and workspace permissions."; + case "missing-key": + return `Add your ${name} API key in Settings → Voice.`; + case "unreadable-key": + return `Unlock the API key vault on the selected environment. No text was sent to ${name}.`; + case "key-changed": + return `The ${name} API key changed. Start reading again.`; + case "rejected-key": + return `${name} rejected the API key. Check its permissions and billing.`; + case "rate-limit": + return `${name} reached a usage limit. Try again later.`; + case "model-unavailable": + return `Choose an available ${name} speech model in Settings → Voice.`; + case "unavailable": + return `${name} could not generate speech. Try again later.`; + } + } +} diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 7bbb03595d4bb..d7cc495d38735 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1,3 +1,4 @@ +import { ReadAloudPreference, ReadAloudSettings } from "./readAloud.ts"; import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts"; import { AuthOrchestrationOperateScope, @@ -568,6 +569,7 @@ export const ClientSettingsSchema = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed([])), ), voiceShortcutMode: VoiceShortcutMode.pipe(Schema.withDecodingDefault(Effect.succeed("auto"))), + readAloud: ReadAloudPreference, speechLanguage: SpeechLanguage.pipe(Schema.withDecodingDefault(Effect.succeed("auto"))), speechTranslateToEnglish: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), speechCustomWords: SpeechCustomWords.pipe(Schema.withDecodingDefault(Effect.succeed([]))), @@ -2102,6 +2104,7 @@ export const ClientSettingsPatch = Schema.Struct({ voiceMicrophone: Schema.optionalKey(Schema.String), voiceMicrophones: Schema.optionalKey(Schema.Array(VoiceMicrophoneEntry)), voiceShortcutMode: Schema.optionalKey(VoiceShortcutMode), + readAloud: Schema.optionalKey(ReadAloudSettings), speechLanguage: Schema.optionalKey(SpeechLanguage), speechTranslateToEnglish: Schema.optionalKey(Schema.Boolean), speechCustomWords: Schema.optionalKey(SpeechCustomWords), diff --git a/packages/shared/package.json b/packages/shared/package.json index 3de18958220ef..9077be18ced1c 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -3,6 +3,7 @@ "private": true, "type": "module", "exports": { + "./read-aloud": "./src/readAloud.ts", "./png": { "types": "./src/png.ts", "import": "./src/png.ts" diff --git a/packages/shared/src/readAloud.test.ts b/packages/shared/src/readAloud.test.ts new file mode 100644 index 0000000000000..542fb4ab8b150 --- /dev/null +++ b/packages/shared/src/readAloud.test.ts @@ -0,0 +1,33 @@ +import { expect, it } from "vite-plus/test"; +import { readAloudText, splitReadAloudText, speechAudioMimeType } from "./readAloud.ts"; + +it.each([ + { bytes: [0xff, 0xf9, 0x58, 0x40], mime: "audio/aac" }, + { bytes: [0xff, 0xf1, 0x58, 0x40], mime: "audio/aac" }, + { bytes: [0xff, 0xfb, 0x90, 0], mime: "audio/mpeg" }, + { bytes: [82, 73, 70, 70], mime: "audio/wav" }, +])("recognizes $mime audio without treating MPEG frames as AAC", ({ bytes, mime }) => { + expect(speechAudioMimeType(Uint8Array.from(bytes))).toBe(mime); +}); + +it("reads visible prose and identifiers without link targets or fenced code", () => { + const text = + "# Findings\n\nUse **readAloud** and `message.id`. [Details](https://example.com/private).\n\n```ts\nsecret();\n```\n\nDone."; + expect(readAloudText(text, true)).toBe( + "Findings\nUse readAloud and message.id. Details.\n\nDone.", + ); + expect(readAloudText(text, false)).toContain("secret();"); + expect(readAloudText("![image](https://example.com/image)\n\n", true)).toBe(""); + expect(readAloudText("Hello \nworld.\n\n> First.\n>\n> Second.", true)).toBe( + "Hello\nworld.\nFirst.\nSecond.", + ); +}); + +it("splits long replies without losing content or cutting surrogate pairs", () => { + const text = "First sentence. " + "🙂".repeat(15) + " tail"; + const chunks = splitReadAloudText(text, 20); + expect(chunks[0]).toBe("First sentence."); + expect(chunks.every((chunk) => chunk.length <= 20)).toBe(true); + expect(chunks.join("").replaceAll(" ", "")).toBe(text.replaceAll(" ", "")); + expect(chunks.every((chunk) => !/[\uD800-\uDBFF]$/.test(chunk))).toBe(true); +}); diff --git a/packages/shared/src/readAloud.ts b/packages/shared/src/readAloud.ts new file mode 100644 index 0000000000000..666edaf49f4f3 --- /dev/null +++ b/packages/shared/src/readAloud.ts @@ -0,0 +1,56 @@ +import type { RootContent, Root } from "mdast"; +import { unified } from "unified"; +import remarkParse from "remark-parse"; +import remarkGfm from "remark-gfm"; + +const parser = unified().use(remarkParse).use(remarkGfm); + +export function readAloudText(markdown: string, skipCodeBlocks: boolean) { + const root = parser.parse(markdown); + const visit = (node: Root | RootContent): string => { + if (node.type === "break") return "\n"; + if (node.type === "code") return skipCodeBlocks ? "" : node.value; + if ( + node.type === "html" || + node.type === "definition" || + node.type === "image" || + node.type === "imageReference" + ) + return ""; + if ("children" in node) { + const separator = ["root", "list", "listItem", "blockquote", "table", "tableRow"].includes( + node.type, + ) + ? "\n" + : ""; + return node.children.map(visit).join(separator); + } + return "value" in node ? node.value : ""; + }; + return visit(root) + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +export function splitReadAloudText(text: string, limit = 3500) { + const chunks: string[] = []; + let rest = text.trim(); + while (rest.length > limit) { + const part = rest.slice(0, limit); + const sentence = [...part.matchAll(/[.!?。!?](?:\s|$)/gu)].at(-1); + let at = sentence ? sentence.index + sentence[0].length : part.lastIndexOf(" "); + if (at <= 0) at = limit; + if (/[\uD800-\uDBFF]/.test(rest[at - 1] ?? "")) at--; + chunks.push(rest.slice(0, at).trim()); + rest = rest.slice(at).trim(); + } + if (rest) chunks.push(rest); + return chunks; +} + +export function speechAudioMimeType(bytes: Uint8Array) { + if (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xf6) === 0xf0) return "audio/aac"; + return bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 + ? "audio/wav" + : "audio/mpeg"; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5c84d21586059..59cfabb5b08f7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -718,6 +718,9 @@ importers: expo-sharing: specifier: 58.0.22 version: 58.0.22(patch_hash=321a86e1471e34c53f1f2937fbb4304ea3f7b7a78ad9e4d35febc2b9e73e9688)(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) + expo-speech: + specifier: ~58.0.3 + version: 58.0.3(expo@58.0.23) expo-splash-screen: specifier: ~58.0.13 version: 58.0.13(expo@58.0.23)(supports-color@8.1.1)(typescript@6.0.3) @@ -9422,6 +9425,11 @@ packages: react: '*' react-native: '*' + expo-speech@58.0.3: + resolution: {integrity: sha512-jdMTqWL6ciDM8aVJe2/l2g6GTVaK7i/zBOVUhTq+l0Y+DOCz3Nh4HqNrMwmIKzXrlsxRv3ejmjSQPlX1lfOTOA==} + peerDependencies: + expo: '*' + expo-splash-screen@58.0.13: resolution: {integrity: sha512-RsvDF13tU1wQIy2blzmdbZoWpPWNTYks2A0CUq2AENR7i7u8elSSEfQOdh5TeC0lrrFVbiWfPj2JiM7y/m08Ig==} peerDependencies: @@ -19533,6 +19541,10 @@ snapshots: - supports-color - typescript + expo-speech@58.0.3(expo@58.0.23): + dependencies: + expo: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) + expo-splash-screen@58.0.13(expo@58.0.23)(supports-color@8.1.1)(typescript@6.0.3): dependencies: '@expo/config-plugins': 58.0.12(supports-color@8.1.1)(typescript@6.0.3) From e3af29a5d20460d7365ea8eceb4164cf71f2d205 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 12 Nov 2026 23:22:57 -0600 Subject: [PATCH 02/33] fix(read-aloud): address playback and synthesis review findings --- .../src/features/read-aloud/playback.ts | 8 ++ .../src/features/threads/ThreadFeed.tsx | 23 +++--- apps/server/src/speech/CloudSpeech.ts | 78 ++++++++++++++----- apps/server/src/speech/synthesis.test.ts | 44 ++++++++--- .../CloudVoiceConfiguration.browser.test.tsx | 46 ++++++----- .../settings/ReadAloudSettingsSection.tsx | 2 +- packages/client-runtime/src/readAloud.test.ts | 59 ++++++++++++++ packages/client-runtime/src/readAloud.ts | 54 +++++++++++-- 8 files changed, 246 insertions(+), 68 deletions(-) diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts index 71ff5e2cf972a..7472217f0a51a 100644 --- a/apps/mobile/src/features/read-aloud/playback.ts +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -74,6 +74,10 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba ); return { play: async () => { + if (!settings.backgroundPlayback && AppState.currentState !== "active") { + readAloudController.pause(); + return; + } await session.play(); if (!session.requested) throw new Error("Finish recording before reading aloud."); }, @@ -143,6 +147,10 @@ export const readAloudController = createReadAloudController(async (text, settin }); return { play: async () => { + if (!settings.backgroundPlayback && AppState.currentState !== "active") { + readAloudController.pause(); + return; + } if (settings.backgroundPlayback) player.setActiveForLockScreen(true, { title: "T3 Code", artist: "Read aloud" }); await session.play(); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 3c2f402285217..1990fa3befa96 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -2838,17 +2838,18 @@ let lastSplitViewport: { windowWidth: number; width: number; height: number } | export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const formatMessageTime = useMessageTimeFormatter(); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Speech follows the thread rather than virtualized message rows and stops on navigation. - useEffect( - () => () => { - if ( - readAloudController - .getSnapshot() - .id?.startsWith(`${props.environmentId}:${props.threadId}:`) - ) - readAloudController.stop(); - }, - [props.environmentId, props.threadId], + useFocusEffect( + useCallback( + () => () => { + if ( + readAloudController + .getSnapshot() + .id?.startsWith(`${props.environmentId}:${props.threadId}:`) + ) + readAloudController.stop(); + }, + [props.environmentId, props.threadId], + ), ); const { listRef, onIsAtEndChange, onHeaderMaterialVisibilityChange } = props; const workflowOpening = useWorkflowOpening(props.detailRef); diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index 890797f828b59..2a6891c95a0b9 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -24,6 +24,7 @@ import * as Context from "effect/Context"; import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Stream from "effect/Stream"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; @@ -39,6 +40,52 @@ import { applySpeechAliases } from "./customWords.ts"; import { removeSpeechFillerWords } from "./fillerWords.ts"; import { decodeSpeechPcm, SpeechInvalidAudioError } from "./SpeechService.ts"; +const readSynthesisBody = Effect.fn("CloudSpeech.readSynthesisBody")(function* ( + response: HttpClientResponse.HttpClientResponse, + provider: SpeechSynthesisProvider, + limit: number, +) { + const chunks: Uint8Array[] = []; + let size = 0; + const unavailable = () => new SpeechSynthesisError({ provider, reason: "unavailable" }); + yield* response.stream.pipe( + Stream.runForEach((chunk) => { + size += chunk.byteLength; + if (size > limit) return Effect.fail(unavailable()); + chunks.push(chunk); + return Effect.void; + }), + Effect.mapError(unavailable), + ); + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +}); + +const decodeXaiSynthesisCatalog = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ voices: Schema.Array(Schema.Struct({ voice_id: Schema.String })) }), + ), +); + +const decodeOpenRouterSynthesisCatalog = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + data: Schema.Array( + Schema.Struct({ + id: Schema.String, + name: Schema.optionalKey(Schema.String), + supported_voices: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.String))), + }), + ), + }), + ), +); + const endpoints = { openai: { url: "https://api.openai.com/v1/audio/transcriptions", model: "gpt-transcribe" }, xai: { url: "https://api.x.ai/v1/stt", model: "grok-voice-transcribe-2.0" }, @@ -253,9 +300,9 @@ export const layer = Layer.effect( ), ).pipe(Effect.mapError(unavailable)); if (response.status !== 200) return yield* unavailable(); - const catalog = yield* HttpClientResponse.schemaBodyJson( - Schema.Struct({ voices: Schema.Array(Schema.Struct({ voice_id: Schema.String })) }), - )(response).pipe(Effect.mapError(unavailable)); + const catalog = yield* decodeXaiSynthesisCatalog( + new TextDecoder().decode(yield* readSynthesisBody(response, provider, 1024 * 1024)), + ).pipe(Effect.mapError(unavailable)); return { models: [ { @@ -271,17 +318,9 @@ export const layer = Layer.effect( HttpClientRequest.get("https://openrouter.ai/api/v1/models?output_modalities=speech"), ).pipe(Effect.mapError(unavailable)); if (response.status !== 200) return yield* unavailable(); - const catalog = yield* HttpClientResponse.schemaBodyJson( - Schema.Struct({ - data: Schema.Array( - Schema.Struct({ - id: Schema.String, - name: Schema.optionalKey(Schema.String), - supported_voices: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.String))), - }), - ), - }), - )(response).pipe(Effect.mapError(unavailable)); + const catalog = yield* decodeOpenRouterSynthesisCatalog( + new TextDecoder().decode(yield* readSynthesisBody(response, provider, 1024 * 1024)), + ).pipe(Effect.mapError(unavailable)); return { models: catalog.data.map((model) => ({ id: model.id, @@ -338,8 +377,11 @@ export const layer = Layer.effect( ? (yield* openRouterSpeechModels).models.find((model) => model.id === request.model) ?.voices[0] : undefined); - // OpenRouter's MiniMax adapter only emits MP3; all other adapters accept PCM. - const format = request.model.startsWith("minimax/") ? "mp3" : "pcm"; + // MiniMax and Voxtral reject PCM on OpenRouter. + const format = + request.model.startsWith("minimax/") || request.model.startsWith("mistralai/voxtral-") + ? "mp3" + : "pcm"; const body = provider === "chatgpt" ? { text: request.text } @@ -401,9 +443,7 @@ export const layer = Layer.effect( ? "rate-limit" : "unavailable", }); - const bytes = new Uint8Array( - yield* response.arrayBuffer.pipe(Effect.mapError(unavailable)), - ); + const bytes = yield* readSynthesisBody(response, provider, MAX_SYNTHESIS_BYTES); if (!bytes.length || bytes.length > MAX_SYNTHESIS_BYTES) return yield* unavailable(); if (format === "pcm" && provider === "openrouter") { const contentType = response.headers["content-type"] ?? ""; diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index 1bb871d8fe931..95f5daa472c75 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -114,16 +114,18 @@ it.effect.each(["xai", "openrouter"] as const)( if (provider === "openrouter") { yield* service.synthesize(provider, { ...request, voice: "" }); expect(JSON.parse(String(upstream.mock.calls.at(-1)?.[1]?.body)).voice).toBe("reader"); - upstream.mockResolvedValueOnce(new Response(new Uint8Array([73, 68, 51, 1]))); - expect([ - ...(yield* service.synthesize(provider, { - ...request, - model: "minimax/speech-test:free", - })), - ]).toEqual([73, 68, 51, 1]); - expect(JSON.parse(String(upstream.mock.calls.at(-1)?.[1]?.body)).response_format).toBe( - "mp3", - ); + for (const model of ["minimax/speech-test:free", "mistralai/voxtral-mini-tts-2603"]) { + upstream.mockResolvedValueOnce(new Response(new Uint8Array([73, 68, 51, 1]))); + expect([ + ...(yield* service.synthesize(provider, { + ...request, + model, + })), + ]).toEqual([73, 68, 51, 1]); + expect(JSON.parse(String(upstream.mock.calls.at(-1)?.[1]?.body)).response_format).toBe( + "mp3", + ); + } upstream.mockResolvedValueOnce( new Response(new Uint8Array([0, 1]), { headers: { "content-type": "audio/pcm;rate=garbage" }, @@ -139,6 +141,28 @@ it.effect.each(["xai", "openrouter"] as const)( expect(yield* Effect.flip(service.synthesize(provider, request))).toMatchObject({ reason: "rate-limit", }); + for (const operation of ["catalog", "synthesis"] as const) { + let pulls = 0; + const cancel = vi.fn(); + upstream.mockResolvedValueOnce( + new Response( + new ReadableStream({ + pull(controller) { + if (++pulls <= 40) controller.enqueue(new Uint8Array(1024 * 1024)); + else controller.close(); + }, + cancel, + }), + ), + ); + expect( + operation === "catalog" + ? yield* Effect.flip(service.synthesisModels(provider)) + : yield* Effect.flip(service.synthesize(provider, request)), + ).toMatchObject({ reason: "unavailable" }); + expect(pulls).toBeLessThan(40); + expect(cancel).toHaveBeenCalledOnce(); + } yield* service.setKey(provider, null); const count = upstream.mock.calls.length; expect(yield* Effect.flip(service.synthesize(provider, request))).toMatchObject({ diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index b5eddbcc10df8..1a59b6e985d9d 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -15,30 +15,34 @@ vi.mock("../../env", async (original) => ({ ...(await original()), isSecretsFeatureEnabled: true, })); -vi.mock("../../state/environments", async (importOriginal) => ({ - ...(await importOriginal()), - useEnvironments: () => ({ - environments: [ - { - environmentId: "voice-host", - label: "Laptop", - connection: { phase: "available" }, - serverConfig: { - secretReferences: true, - settings: { - secretProviders: { - work: { kind: "one_password", label: "Work vault", config: { account: "work" } }, +vi.mock("../../state/environments", async (importOriginal) => { + const presentationById = new Map(); + return { + ...(await importOriginal()), + useEnvironments: () => ({ + presentationById, + environments: [ + { + environmentId: "voice-host", + label: "Laptop", + connection: { phase: "available" }, + serverConfig: { + secretReferences: true, + settings: { + secretProviders: { + work: { kind: "one_password", label: "Work vault", config: { account: "work" } }, + }, + }, + environment: { + platform: { os: "linux", arch: "x64" }, + capabilities: { voiceTranscription: true, cloudVoiceTranscription: true }, }, - }, - environment: { - platform: { os: "linux", arch: "x64" }, - capabilities: { voiceTranscription: true, cloudVoiceTranscription: true }, }, }, - }, - ], - }), -})); + ], + }), + }; +}); const id = EnvironmentId.make("voice-host"); const grantKey = "t3code:voice-audio-grant:v1"; diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index f370bde4f8b87..028094e9c2161 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -446,7 +446,7 @@ export function ReadAloudSettingsSection() { size="sm" variant="outline" onClick={() => - state.id === "read-aloud-preview" + state.id === "read-aloud-preview" && state.status !== "error" ? readAloudController.stop() : void readAloudController.start( "read-aloud-preview", diff --git a/packages/client-runtime/src/readAloud.test.ts b/packages/client-runtime/src/readAloud.test.ts index 5573b0168d2de..f416af0e95264 100644 --- a/packages/client-runtime/src/readAloud.test.ts +++ b/packages/client-runtime/src/readAloud.test.ts @@ -69,3 +69,62 @@ it("pauses without recursive audio-focus callbacks and ignores failures after ca await run; expect(controller.getSnapshot().status).toBe("idle"); }); + +it.each(["prepare", "play"])("keeps a pause requested during %s", async (phase) => { + const preparing = deferred(); + const playing = deferred(); + const release = deferred(); + const finished = deferred(); + const pauseApplied = deferred(); + const pause = vi.fn(() => pauseApplied.resolve()); + const play = vi.fn(async () => { + playing.resolve(); + if (phase === "play") await release.promise; + }); + const controller = createReadAloudController(async () => { + preparing.resolve(); + if (phase === "prepare") await release.promise; + return { play, pause, stop: () => finished.resolve(), finished: finished.promise }; + }); + const run = controller.start("1", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + }); + await (phase === "prepare" ? preparing.promise : playing.promise); + controller.pause(); + expect(controller.getSnapshot().status).toBe("paused"); + release.resolve(); + if (phase === "play") await pauseApplied.promise; + await controller.resume(); + await playing.promise; + controller.stop(); + await run; +}); + +it("keeps a pause across chunk boundaries", async () => { + const started = deferred(); + const finished = deferred(); + const nextPrepared = deferred(); + const prepare = vi.fn(async () => { + if (prepare.mock.calls.length > 1) nextPrepared.resolve(); + return { + play: async () => started.resolve(), + pause: () => {}, + stop: () => {}, + finished: finished.promise, + }; + }); + const controller = createReadAloudController(prepare); + const run = controller.start("1", "word ".repeat(1000), { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + }); + await started.promise; + await controller.resume(); + finished.resolve(); + controller.pause(); + await nextPrepared.promise; + expect(controller.getSnapshot().status).toBe("paused"); + controller.stop(); + await run; +}); diff --git a/packages/client-runtime/src/readAloud.ts b/packages/client-runtime/src/readAloud.ts index 3090ebf94c0af..5649f1bb7a5b4 100644 --- a/packages/client-runtime/src/readAloud.ts +++ b/packages/client-runtime/src/readAloud.ts @@ -23,6 +23,15 @@ export function createReadAloudController( let state: State = { id: null, status: "idle" }; let active: AbortController | null = null; let playback: SpeechPlayback | null = null; + let paused = false; + let starting = false; + let resumePending: (() => void) | null = null; + const waitForResume = async () => { + if (paused) + await new Promise((resolve) => { + resumePending = resolve; + }); + }; const listeners = new Set<() => void>(); const publish = (next: State) => { state = next; @@ -31,6 +40,10 @@ export function createReadAloudController( const stop = () => { active?.abort(); active = null; + paused = false; + starting = false; + resumePending?.(); + resumePending = null; playback?.stop(); playback = null; publish({ id: null, status: "idle" }); @@ -45,17 +58,35 @@ export function createReadAloudController( }, stop, pause() { - if (state.status !== "playing") return; + if (state.status !== "playing" && state.status !== "loading") return; + paused = true; publish({ ...state, status: "paused" }); - playback?.pause(); + if (!starting) playback?.pause(); }, async resume() { - if (state.status !== "paused" || !playback || !active) return; + if (state.status !== "paused" || !active) return; + paused = false; + if (resumePending) { + const resume = resumePending; + resumePending = null; + publish({ ...state, status: "loading" }); + resume(); + return; + } + if (starting || !playback) { + publish({ ...state, status: "loading" }); + return; + } const owner = active; const id = state.id; try { + starting = true; await playback.play(); - if (active === owner) publish({ ...state, status: "playing" }); + if (active === owner) { + starting = false; + if (paused) playback.pause(); + else publish({ ...state, status: "playing" }); + } } catch { if (active === owner) { stop(); @@ -72,7 +103,7 @@ export function createReadAloudController( active = owner; try { for (const chunk of chunks) { - publish({ id, status: "loading" }); + publish({ id, status: paused ? "paused" : "loading" }); const next = await prepare(chunk, settings, owner.signal); if (active !== owner) { next.stop(); @@ -81,8 +112,19 @@ export function createReadAloudController( playback = next; // Playback can fail while the platform is still activating its audio session. void next.finished.catch(() => {}); - await next.play(); + await waitForResume(); if (active !== owner) return; + do { + starting = true; + await next.play(); + if (active !== owner) return; + starting = false; + if (paused) { + next.pause(); + await waitForResume(); + if (active !== owner) return; + } else break; + } while (active === owner); publish({ id, status: "playing" }); await next.finished; if (active !== owner) return; From 55eeadbf484387214044cafbce106cc2434587d6 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Thu, 12 Nov 2026 23:32:46 -0600 Subject: [PATCH 03/33] fix(read-aloud): preserve playback across chunk cleanup --- .../src/features/read-aloud/playback.test.ts | 94 +++++++++++++++++++ .../src/features/read-aloud/playback.ts | 14 ++- apps/server/src/speech/CloudSpeech.ts | 10 +- apps/server/src/speech/synthesis.test.ts | 19 +++- .../CloudVoiceConfiguration.browser.test.tsx | 39 +++++++- .../settings/ReadAloudSettingsSection.tsx | 4 +- packages/client-runtime/src/readAloud.test.ts | 28 ++++++ packages/client-runtime/src/readAloud.ts | 18 +++- 8 files changed, 208 insertions(+), 18 deletions(-) create mode 100644 apps/mobile/src/features/read-aloud/playback.test.ts diff --git a/apps/mobile/src/features/read-aloud/playback.test.ts b/apps/mobile/src/features/read-aloud/playback.test.ts new file mode 100644 index 0000000000000..fd4ff5404b4bd --- /dev/null +++ b/apps/mobile/src/features/read-aloud/playback.test.ts @@ -0,0 +1,94 @@ +import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import * as Speech from "expo-speech"; +import { createAudioPlayer } from "expo-audio"; +import { acquireAudioSession, releaseAudioSession } from "../../lib/audioSession"; +import { readAloudController } from "./playback"; + +vi.mock("react-native", () => ({ + AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) }, + Platform: { OS: "ios" }, +})); +vi.mock("../../lib/uuid", () => ({ uuidv4: () => "speech-test" })); +vi.mock("expo-speech", () => ({ + getAvailableVoicesAsync: vi.fn(async () => []), + speak: vi.fn(), + resume: vi.fn(async () => {}), + pause: vi.fn(async () => {}), + stop: vi.fn(async () => {}), +})); +vi.mock("expo-audio", () => ({ + AudioModule: { setAudioSessionOwner: vi.fn() }, + setAudioModeAsync: vi.fn(async () => {}), + setIsAudioActiveAsync: vi.fn(async () => {}), + createAudioPlayer: vi.fn(), +})); +vi.mock("expo-file-system", () => ({ + Paths: { cache: "cache" }, + File: class { + uri = "test.mp3"; + exists = true; + write() {} + delete() {} + }, +})); +vi.mock("../../state/atom-registry", async () => { + const Option = await import("effect/Option"); + return { appAtomRegistry: { get: () => Option.some({ environmentId: "host" }) } }; +}); +vi.mock("../../state/session", () => ({ + environmentSession: { preparedConnectionValueAtom: () => null }, +})); +vi.mock("@t3tools/client-runtime/voice-input", () => ({ synthesizeSpeech: vi.fn() })); +vi.mock("../voice-input/voiceDestination", () => ({ + runSpeech: async () => Uint8Array.of(73, 68, 51, 1), +})); + +it("falls back from a removed system voice and completes playback", async () => { + vi.mocked(Speech.getAvailableVoicesAsync).mockResolvedValue([]); + vi.mocked(Speech.speak).mockImplementation((_text, options) => options?.onDone?.()); + try { + await readAloudController.start("system", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + voice: "removed-voice", + }); + expect(Speech.speak).toHaveBeenLastCalledWith( + "reply", + expect.not.objectContaining({ voice: "removed-voice" }), + ); + expect(readAloudController.getSnapshot().status).toBe("idle"); + } finally { + readAloudController.stop(); + } +}); + +it("removes lock-screen playback when recording takes audio focus", async () => { + const started = Promise.withResolvers(); + const player = { + play: vi.fn(() => started.resolve()), + pause: vi.fn(), + release: vi.fn(), + setPlaybackRate: vi.fn(), + setActiveForLockScreen: vi.fn(), + addListener: vi.fn(), + }; + vi.mocked(createAudioPlayer).mockReturnValue( + player as unknown as ReturnType, + ); + const run = readAloudController.start("cloud", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "xai", + environmentId: EnvironmentId.make("host"), + backgroundPlayback: true, + }); + await started.promise; + const recorder = acquireAudioSession("recording"); + try { + expect(player.setActiveForLockScreen).toHaveBeenLastCalledWith(false); + } finally { + readAloudController.stop(); + await run; + await releaseAudioSession(recorder); + } +}); diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts index 7472217f0a51a..722b1b379871a 100644 --- a/apps/mobile/src/features/read-aloud/playback.ts +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -94,7 +94,14 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba } export const readAloudController = createReadAloudController(async (text, settings, signal) => { - if (settings.provider === "system") return systemPlayback(text, settings); + if (settings.provider === "system") { + const voices = settings.voice ? await Speech.getAvailableVoicesAsync() : []; + signal.throwIfAborted(); + return systemPlayback(text, { + ...settings, + voice: voices.some((voice) => voice.identifier === settings.voice) ? settings.voice : "", + }); + } if (settings.provider === "off") throw new Error("Enable read aloud in Settings → Voice."); const prepared = settings.environmentId ? Option.getOrNull( @@ -133,7 +140,10 @@ export const readAloudController = createReadAloudController(async (text, settin player, false, (requested) => { - if (!requested) readAloudController.pause(); + if (!requested) { + player.setActiveForLockScreen(false); + readAloudController.pause(); + } }, settings.backgroundPlayback, ); diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index 2a6891c95a0b9..9d286138f1fd5 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -377,11 +377,11 @@ export const layer = Layer.effect( ? (yield* openRouterSpeechModels).models.find((model) => model.id === request.model) ?.voices[0] : undefined); - // MiniMax and Voxtral reject PCM on OpenRouter. + // Gemini and HeyGen only support PCM; use self-describing MP3 elsewhere. const format = - request.model.startsWith("minimax/") || request.model.startsWith("mistralai/voxtral-") - ? "mp3" - : "pcm"; + request.model.startsWith("google/gemini-") || request.model.startsWith("heygen/") + ? "pcm" + : "mp3"; const body = provider === "chatgpt" ? { text: request.text } @@ -447,7 +447,7 @@ export const layer = Layer.effect( if (!bytes.length || bytes.length > MAX_SYNTHESIS_BYTES) return yield* unavailable(); if (format === "pcm" && provider === "openrouter") { const contentType = response.headers["content-type"] ?? ""; - const rate = Number(/\brate=(\d+)/.exec(contentType)?.[1]); + const rate = Number(/\brate=([^;\s]+)/.exec(contentType)?.[1] ?? "24000"); const channels = Number(/\bchannels=(\d+)/.exec(contentType)?.[1] ?? "1"); return yield* Effect.try({ try: () => speechWave(bytes, rate, channels), diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index 95f5daa472c75..424df4acbe10b 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -23,7 +23,7 @@ it.effect.each(["xai", "openrouter"] as const)( : String(url).includes("/models") ? Response.json({ data: [ - { id: "example/speech", name: "Speech", supported_voices: ["reader"] }, + { id: "google/gemini-test-tts", name: "Speech", supported_voices: ["reader"] }, { id: "minimax/speech-test:free", supported_voices: null }, ], }) @@ -40,7 +40,7 @@ it.effect.each(["xai", "openrouter"] as const)( yield* service.setKey("openai", Redacted.make("must-not-be-forwarded")); const request = { text: "Read this reply.", - model: "example/speech", + model: "google/gemini-test-tts", voice: "reader", speed: 1.25, language: "en", @@ -92,7 +92,7 @@ it.effect.each(["xai", "openrouter"] as const)( ? { text: request.text, voice_id: "reader", language: "en", speed: 1.25 } : { input: request.text, - model: "example/speech", + model: "google/gemini-test-tts", voice: "reader", response_format: "pcm", }, @@ -102,7 +102,7 @@ it.effect.each(["xai", "openrouter"] as const)( provider === "xai" ? [{ id: "grok-tts", name: "Grok TTS", voices: ["reader"] }] : [ - { id: "example/speech", name: "Speech", voices: ["reader"] }, + { id: "google/gemini-test-tts", name: "Speech", voices: ["reader"] }, { id: "minimax/speech-test:free", name: "minimax/speech-test:free", voices: [] }, ], }); @@ -114,6 +114,17 @@ it.effect.each(["xai", "openrouter"] as const)( if (provider === "openrouter") { yield* service.synthesize(provider, { ...request, voice: "" }); expect(JSON.parse(String(upstream.mock.calls.at(-1)?.[1]?.body)).voice).toBe("reader"); + upstream.mockResolvedValueOnce( + new Response(Uint8Array.of(0, 1), { headers: { "content-type": "audio/pcm" } }), + ); + const plainPcm = yield* service.synthesize(provider, { + ...request, + model: "google/gemini-tts", + voice: "reader", + }); + expect(new DataView(plainPcm.buffer, plainPcm.byteOffset).getUint32(24, true)).toBe( + 24000, + ); for (const model of ["minimax/speech-test:free", "mistralai/voxtral-mini-tts-2603"]) { upstream.mockResolvedValueOnce(new Response(new Uint8Array([73, 68, 51, 1]))); expect([ diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index 1a59b6e985d9d..7fd595776a453 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -1,5 +1,5 @@ import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; -import { EnvironmentId } from "@t3tools/contracts"; +import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -7,6 +7,7 @@ import { render } from "../../../test/render"; import "~/index.css"; import { chooseAudioDestination } from "../../speech/voiceConsent"; import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; +import { getClientSettings, updateClientSettings } from "../../hooks/useSettings"; import { VoiceSettingsPanel } from "./VoiceSettingsPanel"; import { SettingsScopeProvider } from "./SettingsScopeContext"; @@ -266,3 +267,39 @@ it("OpenRouter needs an exact model, and changing it writes no credential", asyn }, ); }); + +it("waits for the read-aloud key lookup before allowing a save", async () => { + let resolveKeys: (response: Response) => void = () => {}; + const keys = new Promise((resolve) => { + resolveKeys = resolve; + }); + const previous = getClientSettings().readAloud; + await updateClientSettings({ + readAloud: { ...DEFAULT_READ_ALOUD_SETTINGS, provider: "xai", environmentId: id }, + }); + try { + await withVoicePanel( + (url) => { + if (url.pathname === "/api/voice/cloud/keys") return keys; + if (url.pathname === "/api/voice/cloud/xai/key") + return Promise.resolve(new Response(null, { status: 204 })); + if (url.pathname === "/api/voice/synthesis/xai/models") + return Promise.resolve(Response.json({ models: [] })); + return null; + }, + async (screen) => { + await screen.getByRole("textbox", { name: "Read-aloud API key" }).fill("test-speech-key"); + const save = screen.getByRole("button", { name: "Save", exact: true }); + await expect.element(save).toBeDisabled(); + resolveKeys(Response.json({ openai: false, xai: false, openrouter: false })); + await expect.element(save).toBeEnabled(); + await save.click(); + await expect + .element(screen.getByRole("button", { name: "Remove", exact: true })) + .toBeVisible(); + }, + ); + } finally { + await updateClientSettings({ readAloud: previous }); + } +}); diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 028094e9c2161..082a16c2458bf 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -59,7 +59,7 @@ function ReadAloudKey({ const controller = new AbortController(); void runEnvironmentSpeech(getCloudSpeechKeys(prepared), { signal: controller.signal }).then( (keys) => setConfigured(Boolean(keys[provider])), - () => {}, + () => setConfigured(false), ); return () => controller.abort(); }, [prepared, provider]); @@ -100,7 +100,7 @@ function ReadAloudKey({ /> + ) : install.state === "installed" ? ( + + ) : ( + + ) + } + /> + ); +} + export function ReadAloudSettingsSection() { const settings = useClientSettings((value) => value.readAloud); const { environments } = useEnvironments(); @@ -137,6 +255,8 @@ export function ReadAloudSettingsSection() { ? catalogState.error || catalog.error || "" : ""; const model = settings.model || catalog.defaultModel; + const localModel = catalog.models.find((entry) => entry.id === model && entry.install); + const refreshCatalog = () => setCatalogVersion((value) => value + 1); const [systemVoices, setSystemVoices] = useState([]); const state = useSyncExternalStore( readAloudController.subscribe, @@ -196,7 +316,7 @@ export function ReadAloudSettingsSection() { {environments.map((environment) => ( - Cloud via {environment.label} - {(["openai", "xai", "openrouter"] as const).map((provider) => ( + Via {environment.label} + {(["local", "openai", "xai", "openrouter"] as const).map((provider) => ( setCatalogVersion((value) => value + 1)} /> )} + {settings.provider === "local" && prepared && localModel && ( + + )} {remote && error && (

{error} @@ -327,7 +455,11 @@ export function ReadAloudSettingsSection() { {(settings.provider === "system" || catalog.supportsVoiceSelection) && ( ; if (provider === "system") return ; + if (provider === "local") return ; if (provider === "openrouter") return ; return ( diff --git a/apps/web/src/speech/readAloud.ts b/apps/web/src/speech/readAloud.ts index 3a65255465e0e..e1380e808b27e 100644 --- a/apps/web/src/speech/readAloud.ts +++ b/apps/web/src/speech/readAloud.ts @@ -1,7 +1,9 @@ import type { SpeechSynthesisCatalog } from "@t3tools/contracts"; import { createReadAloudController, type SpeechPlayback } from "@t3tools/client-runtime/read-aloud"; -import { getSpeechSynthesisModels, synthesizeSpeech } from "@t3tools/client-runtime/voice-input"; -import { speechAudioMimeType } from "@t3tools/shared/read-aloud"; +import { + getSpeechSynthesisModels, + startSpeechSynthesis, +} from "@t3tools/client-runtime/voice-input"; import { readPreparedConnection } from "../state/session"; import { runEnvironmentSpeech } from "./runEnvironmentSpeech"; @@ -57,8 +59,8 @@ export const readAloudController = createReadAloudController(async (text, settin const catalog = await pendingCatalog; signal.throwIfAborted(); if (catalog.error) throw new Error(catalog.error); - const bytes = await runEnvironmentSpeech( - synthesizeSpeech(prepared, settings.provider, { + const url = await runEnvironmentSpeech( + startSpeechSynthesis(prepared, settings.provider, { text, model: settings.model || catalog.defaultModel, voice: settings.voice, @@ -68,9 +70,6 @@ export const readAloudController = createReadAloudController(async (text, settin { signal }, ); signal.throwIfAborted(); - const url = URL.createObjectURL( - new Blob([new Uint8Array(bytes)], { type: speechAudioMimeType(bytes) }), - ); const audio = new Audio(url); if (!catalog.speedAppliedByProvider) audio.playbackRate = settings.speed; let done: () => void = () => {}; @@ -86,7 +85,6 @@ export const readAloudController = createReadAloudController(async (text, settin audio.pause(); audio.removeAttribute("src"); audio.load(); - URL.revokeObjectURL(url); done(); }, finished, diff --git a/docs/user/composer.md b/docs/user/composer.md index 757c6030d1ac6..868661f8b340b 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -206,6 +206,12 @@ System voices run on your device. OpenAI, Grok TTS, and OpenRouter send the repl through your selected environment and use API billing. They share the API keys saved for dictation. Choose a model and voice, then use the preview to try it. +**Local model** reads replies in English with Supertonic 3 on your selected environment, +so the text never leaves it. Download it once from the same settings page (330–360 MB). +It uses the GPU through Metal on macOS and Vulkan on Windows and Linux. Without a GPU it runs on +the CPU and takes a few seconds longer to start speaking. Local models run on macOS, Windows x64, +and Linux x64 with glibc 2.43 or newer, such as Ubuntu 26.04. + On mobile, **Background playback** allows speech to continue while the app is in the background. ## Voice input on web and desktop diff --git a/knip.jsonc b/knip.jsonc index e3589f643c325..c6fbd0dccd15b 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -73,6 +73,7 @@ "@t3tools/web", "@napi-rs/keyring", "ffi-rs", + "koffi", "transcribe-cpp", ], }, diff --git a/packages/audio-cpp/package.json b/packages/audio-cpp/package.json new file mode 100644 index 0000000000000..b0923b4e493ed --- /dev/null +++ b/packages/audio-cpp/package.json @@ -0,0 +1,20 @@ +{ + "name": "@t3tools/audio-cpp", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "import": "./src/index.ts" + } + }, + "scripts": { + "typecheck": "effect-tsgo tsrs --noEmit", + "test": "vp test run --config ../../vite.config.ts --dir ." + }, + "devDependencies": { + "@types/node": "catalog:", + "koffi": "3.3.6", + "vite-plus": "catalog:" + } +} diff --git a/packages/audio-cpp/src/bindings.ts b/packages/audio-cpp/src/bindings.ts new file mode 100644 index 0000000000000..11ebebe25b4b6 --- /dev/null +++ b/packages/audio-cpp/src/bindings.ts @@ -0,0 +1,245 @@ +import type * as Koffi from "koffi"; + +export type AudioCppAudio = { + /** Interleaved samples in [-1, 1]. */ + readonly samples: Float32Array; + readonly sampleRate: number; + readonly channels: number; +}; + +export type AudioCppSynthesisRequest = { + readonly text: string; + /** Omit when the model should pick its own language. */ + readonly language?: string; + /** Request options the model spec declares, such as `voice_id` or `speed`. */ + readonly options?: Readonly>; +}; + +export type AudioCppSpeechStream = { + /** Synthesizes the model's next text chunk; `undefined` once the text is spoken. */ + readonly next: () => AudioCppAudio | undefined; + readonly close: () => void; +}; + +export type AudioCppModel = { + readonly family: string; + readonly backend: string; + readonly languages: readonly string[]; + /** One stream at a time: starting another resets the first. */ + readonly stream: (request: AudioCppSynthesisRequest) => AudioCppSpeechStream; + readonly dispose: () => void; +}; + +export type AudioCppLibrary = { + readonly buildVersion: string; + /** Opens a streaming text-to-speech session, falling back to the CPU when `backend` fails. */ + readonly loadSpeechModel: ( + path: string, + options: { readonly backend: string; readonly threads: number }, + ) => AudioCppModel; +}; + +/** + * Binds audio.cpp's C ABI. Self-contained so a worker can inline it with `toString()`: + * reference nothing from module scope. Calls block the thread, so run it off the server's. + */ +export function bindAudioCpp(koffi: typeof Koffi, libraryPath: string): AudioCppLibrary { + const lib = koffi.load(libraryPath); + // Anonymous types, so binding twice in one process does not collide on names. + const Registry = koffi.pointer(koffi.opaque()); + const Model = koffi.pointer(koffi.opaque()); + const Session = koffi.pointer(koffi.opaque()); + const Request = koffi.pointer(koffi.opaque()); + const Result = koffi.pointer(koffi.opaque()); + const Event = koffi.pointer(koffi.opaque()); + const BackendConfig = koffi.struct({ backend: "const char *", device: "int", threads: "int" }); + const out = (type: string | Koffi.TypeObject) => koffi.out(koffi.pointer(type)); + const native = { + abiVersion: lib.func("audiocpp_abi_version", "uint32_t", []), + buildVersion: lib.func("audiocpp_build_version", "const char *", []), + lastError: lib.func("audiocpp_last_error", "const char *", []), + statusString: lib.func("audiocpp_status_string", "const char *", ["int"]), + registryCreate: lib.func("audiocpp_registry_create", "int", ["const char *", out(Registry)]), + registryFree: lib.func("audiocpp_registry_free", "void", [Registry]), + modelLoad: lib.func("audiocpp_model_load", "int", [ + Registry, + "const char *", + "void *", + "void *", + out(Model), + ]), + modelFree: lib.func("audiocpp_model_free", "void", [Model]), + modelFamily: lib.func("audiocpp_model_family", "const char *", [Model]), + modelSupports: lib.func("audiocpp_model_supports", "int", [ + Model, + "const char *", + "const char *", + ]), + languageCount: lib.func("audiocpp_model_language_count", "size_t", [Model]), + language: lib.func("audiocpp_model_language", "int", [Model, "size_t", out("const char *")]), + sessionCreate: lib.func("audiocpp_session_create", "int", [ + Model, + "const char *", + "const char *", + koffi.pointer(BackendConfig), + "void *", + out(Session), + ]), + sessionFree: lib.func("audiocpp_session_free", "void", [Session]), + streamStart: lib.func("audiocpp_stream_start", "int", [Session, Request]), + streamNextEvent: lib.func("audiocpp_stream_next_event", "int", [Session, out(Event)]), + streamReset: lib.func("audiocpp_stream_reset", "int", [Session]), + eventFree: lib.func("audiocpp_event_free", "void", [Event]), + eventAsResult: lib.func("audiocpp_event_as_result", Result, [Event]), + namedAudio: lib.func("audiocpp_result_named_audio", "int", [ + Result, + "size_t", + out("const char *"), + out("void *"), + out("size_t"), + out("int"), + out("int"), + ]), + requestCreate: lib.func("audiocpp_request_create", Request, []), + requestFree: lib.func("audiocpp_request_free", "void", [Request]), + requestSetText: lib.func("audiocpp_request_set_text", "int", [ + Request, + "const char *", + "const char *", + ]), + requestSetOption: lib.func("audiocpp_request_set_option", "int", [ + Request, + "const char *", + "const char *", + ]), + }; + // Refuse a library whose major ABI differs from the one these signatures describe. + if (native.abiVersion() >>> 16 !== 0) throw new Error("Unsupported audio.cpp ABI version."); + const check = (status: number, operation: string) => { + if (status === 0) return; + const detail = native.lastError(); + throw new Error( + `audio.cpp ${operation} failed (${native.statusString(status)})${detail ? `: ${detail}` : ""}`, + ); + }; + const registry: [unknown] = [null]; + check(native.registryCreate(null, registry), "registry creation"); + + const openSession = (model: unknown, backend: string, threads: number) => { + const session: [unknown] = [null]; + check( + native.sessionCreate( + model, + "tts", + "streaming", + { backend, device: 0, threads }, + null, + session, + ), + `${backend} session creation`, + ); + return session[0]; + }; + + return { + buildVersion: native.buildVersion(), + loadSpeechModel(path, { backend, threads }) { + const loaded: [unknown] = [null]; + check(native.modelLoad(registry[0], path, null, null, loaded), "model load"); + const model = loaded[0]; + let session: unknown; + let sessionBackend = backend; + try { + if (!native.modelSupports(model, "tts", "streaming")) + throw new Error("This model does not support streaming text to speech."); + try { + session = openSession(model, backend, threads); + } catch (error) { + if (backend === "cpu") throw error; + sessionBackend = "cpu"; + session = openSession(model, "cpu", threads); + } + } catch (error) { + native.modelFree(model); + throw error; + } + const languages: string[] = []; + for (let index = 0; index < native.languageCount(model); index++) { + const language: [string] = [""]; + if (native.language(model, index, language) === 0 && language[0]) + languages.push(language[0]); + } + return { + family: native.modelFamily(model), + backend: sessionBackend, + languages, + stream({ text, language, options = {} }) { + const request = native.requestCreate(); + if (!request) throw new Error("audio.cpp could not allocate a request."); + try { + check(native.requestSetText(request, text, language ?? null), "request text"); + for (const [key, value] of Object.entries(options)) + check(native.requestSetOption(request, key, value), `request option ${key}`); + // Starting copies the request into the session, so it can be freed right away. + check(native.streamStart(session, request), "stream start"); + } finally { + native.requestFree(request); + } + let open = true; + const close = () => { + if (!open) return; + open = false; + native.streamReset(session); + }; + return { + next() { + if (!open) return undefined; + const event: [unknown] = [null]; + try { + check(native.streamNextEvent(session, event), "synthesis"); + } catch (error) { + close(); + throw error; + } + if (!event[0]) { + close(); + return undefined; + } + try { + const id: [string] = [""]; + const samples: [unknown] = [null]; + const frames: [number | bigint] = [0]; + const sampleRate: [number] = [0]; + const channels: [number] = [0]; + check( + native.namedAudio( + native.eventAsResult(event[0]), + 0, + id, + samples, + frames, + sampleRate, + channels, + ), + "audio read", + ); + const length = Number(frames[0]) * channels[0]; + // The view borrows event memory, so copy it before the event is freed. + const copy = new Float32Array(length); + if (length) copy.set(new Float32Array(koffi.view(samples[0], length * 4))); + return { samples: copy, sampleRate: sampleRate[0], channels: channels[0] }; + } finally { + native.eventFree(event[0]); + } + }, + close, + }; + }, + dispose() { + native.sessionFree(session); + native.modelFree(model); + }, + }; + }, + }; +} diff --git a/packages/audio-cpp/src/index.ts b/packages/audio-cpp/src/index.ts new file mode 100644 index 0000000000000..1cfb726edb342 --- /dev/null +++ b/packages/audio-cpp/src/index.ts @@ -0,0 +1,8 @@ +export { + bindAudioCpp, + type AudioCppAudio, + type AudioCppLibrary, + type AudioCppModel, + type AudioCppSynthesisRequest, +} from "./bindings.ts"; +export { AUDIO_CPP_VERSION, audioCppRuntimes, type AudioCppRuntime } from "./runtime.ts"; diff --git a/packages/audio-cpp/src/runtime.ts b/packages/audio-cpp/src/runtime.ts new file mode 100644 index 0000000000000..688ec54636342 --- /dev/null +++ b/packages/audio-cpp/src/runtime.ts @@ -0,0 +1,88 @@ +export const AUDIO_CPP_VERSION = "v0.9.4"; + +export type AudioCppRuntime = { + readonly filename: string; + readonly url: string; + readonly size: number; + readonly sha256: string; + /** The real library file inside the archive, not a version symlink. */ + readonly library: string; + /** The session backend the build accelerates; every build can also run on the CPU. */ + readonly backend: "metal" | "vulkan" | "cpu"; + /** The oldest glibc the build loads on, from the versions its symbols require. */ + readonly minimumGlibc?: string; +}; + +const runtime = ( + name: string, + size: number, + sha256: string, + library: string, + backend: AudioCppRuntime["backend"], + minimumGlibc?: string, +): AudioCppRuntime => { + const filename = `audio-${AUDIO_CPP_VERSION}-lib-${name}`; + return { + filename, + url: `https://github.com/0xShug0/audio.cpp/releases/download/${AUDIO_CPP_VERSION}/${filename}`, + size, + sha256, + library, + backend, + ...(minimumGlibc ? { minimumGlibc } : {}), + }; +}; + +// Upstream publishes no Linux arm64 library. The portable Linux build loads Vulkan as a plugin and +// otherwise runs on the CPU. The Windows Vulkan build links vulkan-1.dll and fails to load without +// a GPU driver, so the CPU build is installed beside it as the fallback. +const RUNTIMES: Readonly> = { + "darwin-arm64": [ + runtime( + "macos-arm64-metal.tar.gz", + 14_422_864, + "bb1141185d15891d1c6b53f05cd55b0b93614804b340289799cff497fe87cf5b", + "libs/libaudiocpp.0.1.0.dylib", + "metal", + ), + ], + "darwin-x64": [ + runtime( + "macos-x64-metal.tar.gz", + 15_509_881, + "f0b6c392be9ca933ee2b813d036484c03a15838c55345e08472ec14251a64ad8", + "libs/libaudiocpp.0.1.0.dylib", + "metal", + ), + ], + "linux-x64": [ + runtime( + "ubuntu-x64-vulkan-portable.tar.gz", + 47_415_047, + "d5dfe390c78acadd153fdb6b8c448cca1ce2d1255fc7998d99ec3df0c29fddfb", + "libs/libaudiocpp.so.0.1.0", + "vulkan", + "2.43", + ), + ], + "win32-x64": [ + runtime( + "windows-x64-vulkan.zip", + 30_751_615, + "cf2fabd8630050491a92c002d7bdfd29eca722c31fb3b8cb0ba9b9c5e6e9ff3d", + "libs/audiocpp.dll", + "vulkan", + ), + runtime( + "windows-x64-cpu.zip", + 13_542_870, + "41f779687dc20e36900797f43d6762a9542c593931d4b3f3f5e877b0db9baa5e", + "libs/audiocpp.dll", + "cpu", + ), + ], +}; + +/** All builds a host installs, in preference order: the first that loads is used. */ +export const audioCppRuntimes = (platform: string, architecture: string) => + RUNTIMES[`${platform}-${architecture}`] ?? []; diff --git a/packages/audio-cpp/tsconfig.json b/packages/audio-cpp/tsconfig.json new file mode 100644 index 0000000000000..374bac55202dd --- /dev/null +++ b/packages/audio-cpp/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/packages/client-runtime/src/readAloud.ts b/packages/client-runtime/src/readAloud.ts index c4130ddb8d64f..081ce9333ea43 100644 --- a/packages/client-runtime/src/readAloud.ts +++ b/packages/client-runtime/src/readAloud.ts @@ -1,4 +1,4 @@ -import type { ReadAloudSettings } from "@t3tools/contracts"; +import { SPEECH_SYNTHESIS_MAX_TEXT, type ReadAloudSettings } from "@t3tools/contracts"; import { readAloudText, splitReadAloudText } from "@t3tools/shared/read-aloud"; export type SpeechPlayback = { @@ -108,7 +108,11 @@ export function createReadAloudController( async start(id: string, markdown: string, settings: ReadAloudSettings) { stop(); if (settings.provider === "off") return; - const chunks = splitReadAloudText(readAloudText(markdown, settings.skipCodeBlocks)); + // Platform speech engines cap utterance length; environments stream a whole reply. + const chunks = splitReadAloudText( + readAloudText(markdown, settings.skipCodeBlocks), + settings.provider === "system" ? undefined : SPEECH_SYNTHESIS_MAX_TEXT, + ); if (!chunks.length) return; const owner = new AbortController(); active = owner; diff --git a/packages/client-runtime/src/voice-input/environment.test.ts b/packages/client-runtime/src/voice-input/environment.test.ts new file mode 100644 index 0000000000000..1e0bdcae480c5 --- /dev/null +++ b/packages/client-runtime/src/voice-input/environment.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { PrimaryConnectionTarget, type PreparedConnection } from "../connection/model.ts"; +import * as RpcHttp from "../rpc/http.ts"; +import { startSpeechSynthesis } from "./environment.ts"; + +const TARGET = new PrimaryConnectionTarget({ + environmentId: "environment-speech" as never, + label: "Speech", + httpBaseUrl: "https://environment.example.test", + wsBaseUrl: "wss://environment.example.test", +}); + +const PREPARED: PreparedConnection = { + environmentId: TARGET.environmentId, + label: TARGET.label, + httpBaseUrl: TARGET.httpBaseUrl, + socketUrl: TARGET.wsBaseUrl, + httpAuthorization: null, + target: TARGET, +}; + +const start = (response: Response) => + startSpeechSynthesis(PREPARED, "local", { + text: "Hello", + model: "", + voice: "", + speed: 1, + language: "en", + }).pipe(Effect.provide(RpcHttp.layerRemoteHttpClient(() => Promise.resolve(response)))); + +describe("startSpeechSynthesis", () => { + it.effect("returns the environment's stream URL for the started synthesis", () => + Effect.gen(function* () { + expect(yield* start(Response.json({ token: "stream-token" }))).toBe( + "https://environment.example.test/api/voice/synthesis/audio?token=stream-token", + ); + }), + ); + + it.effect("fails with the environment's speech error instead of a fetch failure", () => + Effect.gen(function* () { + const error = yield* Effect.flip( + start( + Response.json( + { _tag: "SpeechSynthesisError", provider: "local", reason: "missing-model" }, + { status: 422 }, + ), + ), + ); + expect(error._tag).toBe("SpeechSynthesisError"); + expect(error.message).toBe("Download a local speech model in Settings → Voice."); + }), + ); +}); diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts index 0e768cacba6ea..7f6c8c714332e 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -3,7 +3,12 @@ import { encodeSpeechPcmRequest } from "@t3tools/shared/speech"; import * as Effect from "effect/Effect"; import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; -import { CloudSpeechError, SPEECH_STREAM_PATH } from "@t3tools/contracts"; +import { + CloudSpeechError, + SPEECH_STREAM_PATH, + SPEECH_SYNTHESIS_AUDIO_PATH, + SpeechSynthesisError, +} from "@t3tools/contracts"; import type { CloudSpeechModelId, CloudSpeechProvider, @@ -26,6 +31,7 @@ import { VoiceTranscriptionError } from "./transcription.ts"; const INFERENCE_OR_DOWNLOAD_TIMEOUT_MS = 30 * 60_000; const isCloudSpeechError = Schema.is(CloudSpeechError); +const isSpeechSynthesisError = Schema.is(SpeechSynthesisError); type EnvironmentApiClient = Effect.Success< ReturnType> >; @@ -325,16 +331,61 @@ export const getSpeechSynthesisModels = ( run: ({ client, headers }) => client.synthesisModels({ headers, params: { provider } }), }); -export const synthesizeSpeech = ( +/** Starts synthesis and resolves, once audio exists, with the URL of its live MP3 stream. */ +export const startSpeechSynthesis = ( prepared: PreparedConnection, provider: SpeechSynthesisProvider, payload: SpeechSynthesisRequest, -) => - request({ +) => { + let endpoint = prepared.httpBaseUrl; + return request({ group: "voice", prepared, method: "POST", timeoutMs: 130_000, - path: (urls) => urls.synthesize({ params: { provider } }), - run: ({ client, headers }) => client.synthesize({ headers, params: { provider }, payload }), + path: (urls) => { + endpoint = urls.startSynthesis({ params: { provider } }); + return endpoint; + }, + run: ({ client, headers }) => client.startSynthesis({ headers, params: { provider }, payload }), + }).pipe( + Effect.mapError((error) => + error._tag === "RemoteEnvironmentAuthFetchError" && isSpeechSynthesisError(error.cause) + ? error.cause + : error, + ), + Effect.map(({ token }) => { + const url = new URL(SPEECH_SYNTHESIS_AUDIO_PATH, endpoint); + url.searchParams.set("token", token); + return url.toString(); + }), + ); +}; + +export const downloadSpeechSynthesisModel = (prepared: PreparedConnection, modelId: string) => + request({ + group: "voice", + prepared, + method: "POST", + path: (urls) => urls.downloadSynthesisModel(), + timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS, + run: ({ client, headers }) => client.downloadSynthesisModel({ headers, payload: { modelId } }), + }); + +export const cancelSpeechSynthesisModelDownload = (prepared: PreparedConnection, modelId: string) => + request({ + group: "voice", + prepared, + method: "POST", + path: (urls) => urls.cancelSynthesisModel(), + run: ({ client, headers }) => client.cancelSynthesisModel({ headers, payload: { modelId } }), + }); + +export const removeSpeechSynthesisModel = (prepared: PreparedConnection, modelId: string) => + request({ + group: "voice", + prepared, + method: "POST", + path: (urls) => urls.removeSynthesisModel(), + run: ({ client, headers }) => client.removeSynthesisModel({ headers, payload: { modelId } }), }); diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index e0b02107b7876..416bae47c8764 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -40,4 +40,10 @@ export { type VoiceTranscriptionOptions, } from "./transcription.ts"; -export { getSpeechSynthesisModels, synthesizeSpeech } from "./environment.ts"; +export { + cancelSpeechSynthesisModelDownload, + downloadSpeechSynthesisModel, + getSpeechSynthesisModels, + removeSpeechSynthesisModel, + startSpeechSynthesis, +} from "./environment.ts"; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index a4023f90bdcd6..290ccb23fe076 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -3,6 +3,8 @@ import { SpeechSynthesisRequest, SpeechSynthesisCatalog, SpeechSynthesisError, + SpeechSynthesisModelRequest, + SpeechSynthesisStream, } from "./readAloud.ts"; import * as Context from "effect/Context"; import type * as DateTime from "effect/DateTime"; @@ -856,11 +858,11 @@ export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice") }).middleware(EnvironmentAuthenticatedAuth), ) .add( - HttpApiEndpoint.post("synthesize", "/api/voice/synthesis/:provider", { + HttpApiEndpoint.post("startSynthesis", "/api/voice/synthesis/:provider/stream", { headers: OptionalBearerHeaders, params: Schema.Struct({ provider: SpeechSynthesisProvider }), payload: SpeechSynthesisRequest, - success: Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()), + success: SpeechSynthesisStream, error: [ ...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError, @@ -868,6 +870,30 @@ export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice") ], }).middleware(EnvironmentAuthenticatedAuth), ) + .add( + HttpApiEndpoint.post("downloadSynthesisModel", "/api/voice/synthesis/local/models/download", { + headers: OptionalBearerHeaders, + payload: SpeechSynthesisModelRequest, + success: SpeechSynthesisCatalog, + error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.post("cancelSynthesisModel", "/api/voice/synthesis/local/models/cancel", { + headers: OptionalBearerHeaders, + payload: SpeechSynthesisModelRequest, + success: SpeechSynthesisCatalog, + error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.post("removeSynthesisModel", "/api/voice/synthesis/local/models/remove", { + headers: OptionalBearerHeaders, + payload: SpeechSynthesisModelRequest, + success: SpeechSynthesisCatalog, + error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], + }).middleware(EnvironmentAuthenticatedAuth), + ) .add( HttpApiEndpoint.get("cloudKeys", "/api/voice/cloud/keys", { headers: OptionalBearerHeaders, diff --git a/packages/contracts/src/readAloud.ts b/packages/contracts/src/readAloud.ts index ec39da13d6ef1..32a9b0983ff0c 100644 --- a/packages/contracts/src/readAloud.ts +++ b/packages/contracts/src/readAloud.ts @@ -4,20 +4,30 @@ import * as SchemaTransformation from "effect/SchemaTransformation"; import { EnvironmentId } from "./baseSchemas.ts"; import { CloudSpeechProvider } from "./speech.ts"; -export const SpeechSynthesisProvider = CloudSpeechProvider; +/** `local` runs a downloaded model on the selected environment; the rest are hosted APIs. */ +export const SpeechSynthesisProvider = Schema.Union([CloudSpeechProvider, Schema.Literal("local")]); export type SpeechSynthesisProvider = typeof SpeechSynthesisProvider.Type; export const READ_ALOUD_LABELS = { off: "Off", system: "System voices", + local: "Local model", openai: "OpenAI", xai: "Grok TTS", openrouter: "OpenRouter", } as const; export const ReadAloudSettings = Schema.Struct({ - provider: Schema.Literals(["off", "system", "openai", "chatgpt", "xai", "openrouter"]).pipe( + provider: Schema.Literals([ + "off", + "system", + "local", + "openai", + "chatgpt", + "xai", + "openrouter", + ]).pipe( Schema.decodeTo( - Schema.Literals(["off", "system", "openai", "xai", "openrouter"]), + Schema.Literals(["off", "system", "local", "openai", "xai", "openrouter"]), SchemaTransformation.transform({ decode: (value) => (value === "chatgpt" ? ("off" as const) : value), encode: (value) => value, @@ -46,14 +56,30 @@ export const DEFAULT_READ_ALOUD_SETTINGS: ReadAloudSettings = { export const ReadAloudPreference = ReadAloudSettings.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_READ_ALOUD_SETTINGS)), ); +/** The environment splits longer text for providers with smaller input limits. */ +export const SPEECH_SYNTHESIS_MAX_TEXT = 32_000; +/** Serves a started synthesis as one MP3 stream that native players read while it is produced. */ +export const SPEECH_SYNTHESIS_AUDIO_PATH = "/api/voice/synthesis/audio"; export const SpeechSynthesisRequest = Schema.Struct({ - text: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(4096)), + text: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(SPEECH_SYNTHESIS_MAX_TEXT)), model: Schema.String.check(Schema.isMaxLength(160)), voice: Schema.String.check(Schema.isMaxLength(160)), speed: Schema.Number.check(Schema.isBetween({ minimum: 0.7, maximum: 1.5 })), language: Schema.String.check(Schema.isMinLength(2), Schema.isMaxLength(16)), }); export type SpeechSynthesisRequest = typeof SpeechSynthesisRequest.Type; +/** Single-purpose credential for `SPEECH_SYNTHESIS_AUDIO_PATH`, so media elements need no headers. */ +export const SpeechSynthesisStream = Schema.Struct({ token: Schema.String }); +export const SpeechSynthesisModelInstall = Schema.Struct({ + state: Schema.Literals(["downloadable", "downloading", "verifying", "installed"]), + /** Bytes to download, including the speech runtime when this environment lacks it. */ + size: Schema.Finite, + downloaded: Schema.optionalKey(Schema.Finite), +}); +export type SpeechSynthesisModelInstall = typeof SpeechSynthesisModelInstall.Type; +export const SpeechSynthesisModelRequest = Schema.Struct({ + modelId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(160)), +}); export const SpeechSynthesisCatalog = Schema.Struct({ defaultModel: Schema.String, apiKeyProvider: Schema.NullOr(CloudSpeechProvider), @@ -66,6 +92,8 @@ export const SpeechSynthesisCatalog = Schema.Struct({ id: Schema.String, name: Schema.String, voices: Schema.Array(Schema.String), + /** Present for models that run on the environment and must be downloaded first. */ + install: Schema.optionalKey(SpeechSynthesisModelInstall), }), ), }); @@ -93,6 +121,7 @@ export class SpeechSynthesisError extends Schema.TaggedError( }, ); +/** The running glibc, such as `2.39`; undefined off glibc. */ +export const GlibcVersion = Context.Reference( + "@t3tools/shared/HostProcess/GlibcVersion", + { + defaultValue: () => { + try { + const report = process.report?.getReport() as + | { header?: { glibcVersionRuntime?: unknown } } + | undefined; + const version = report?.header?.glibcVersionRuntime; + return typeof version === "string" ? version : undefined; + } catch { + return undefined; + } + }, + }, +); + export const Hostname = Context.Reference("@t3tools/shared/HostProcess/Hostname", { defaultValue: () => NodeOS.hostname(), }); diff --git a/packages/shared/src/readAloud.test.ts b/packages/shared/src/readAloud.test.ts index 542fb4ab8b150..ab999a7861fbb 100644 --- a/packages/shared/src/readAloud.test.ts +++ b/packages/shared/src/readAloud.test.ts @@ -1,14 +1,5 @@ import { expect, it } from "vite-plus/test"; -import { readAloudText, splitReadAloudText, speechAudioMimeType } from "./readAloud.ts"; - -it.each([ - { bytes: [0xff, 0xf9, 0x58, 0x40], mime: "audio/aac" }, - { bytes: [0xff, 0xf1, 0x58, 0x40], mime: "audio/aac" }, - { bytes: [0xff, 0xfb, 0x90, 0], mime: "audio/mpeg" }, - { bytes: [82, 73, 70, 70], mime: "audio/wav" }, -])("recognizes $mime audio without treating MPEG frames as AAC", ({ bytes, mime }) => { - expect(speechAudioMimeType(Uint8Array.from(bytes))).toBe(mime); -}); +import { readAloudText, splitReadAloudText } from "./readAloud.ts"; it("reads visible prose and identifiers without link targets or fenced code", () => { const text = diff --git a/packages/shared/src/readAloud.ts b/packages/shared/src/readAloud.ts index 666edaf49f4f3..adcdb38f319ce 100644 --- a/packages/shared/src/readAloud.ts +++ b/packages/shared/src/readAloud.ts @@ -47,10 +47,3 @@ export function splitReadAloudText(text: string, limit = 3500) { if (rest) chunks.push(rest); return chunks; } - -export function speechAudioMimeType(bytes: Uint8Array) { - if (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xf6) === 0xf0) return "audio/aac"; - return bytes[0] === 82 && bytes[1] === 73 && bytes[2] === 70 && bytes[3] === 70 - ? "audio/wav" - : "audio/mpeg"; -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 59cfabb5b08f7..535e29cf52749 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -854,6 +854,9 @@ importers: '@anthropic-ai/claude-agent-sdk': specifier: ^0.3.321 version: 0.3.321(@anthropic-ai/sdk@0.93.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.2(supports-color@8.1.1)(zod@4.6.7))(zod@4.6.7) + '@breezystack/lamejs': + specifier: 1.2.7 + version: 1.2.7 '@cursor/sdk': specifier: 1.3.1 version: 1.3.1(patch_hash=74bb82d3804752a413af72c7ffedc5fb24039216ab85e3330874a4892a0fdce9)(zod@4.6.7) @@ -941,6 +944,9 @@ importers: ffi-rs: specifier: 1.3.2 version: 1.3.2 + koffi: + specifier: 3.3.6 + version: 3.3.6 node-pty: specifier: 1.2.0-beta.15 version: 1.2.0-beta.15(patch_hash=ff8117509663fe1d5a07ef2648c324e80a9349b7d90401a00a591702615b8b30) @@ -987,6 +993,9 @@ importers: '@opencode-ai/sdk': specifier: ^1.3.15 version: 1.15.13 + '@t3tools/audio-cpp': + specifier: workspace:* + version: link:../../packages/audio-cpp '@t3tools/contracts': specifier: workspace:* version: link:../../packages/contracts @@ -1509,6 +1518,18 @@ importers: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/audio-cpp: + devDependencies: + '@types/node': + specifier: 24.12.4 + version: 24.12.4 + koffi: + specifier: 3.3.6 + version: 3.3.6 + vite-plus: + specifier: 1.4.0 + version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + packages/client-runtime: dependencies: '@pierre/diffs': @@ -3354,6 +3375,9 @@ packages: resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==} hasBin: true + '@breezystack/lamejs@1.2.7': + resolution: {integrity: sha512-6wc7ck65ctA75Hq7FYHTtTvGnYs6msgdxiSUICQ+A01nVOWg6rqouZB8IdyteRlfpYYiFovkf67dIeOgWIUzTA==} + '@bruits/satteri-darwin-arm64@0.10.5': resolution: {integrity: sha512-27KTVl4TJkVahMy/ohyA7qd4938G5UNneFUz/PsScYfpIhj0IVAS23mpcJXdPF44sa6nva198lmV/cKIb2YPyA==} cpu: [arm64] @@ -13929,6 +13953,8 @@ snapshots: dependencies: css-tree: 3.2.1 + '@breezystack/lamejs@1.2.7': {} + '@bruits/satteri-darwin-arm64@0.10.5': optional: true diff --git a/scripts/lib/cli-external-packages.ts b/scripts/lib/cli-external-packages.ts index b3df99797cfad..5ebe435625174 100644 --- a/scripts/lib/cli-external-packages.ts +++ b/scripts/lib/cli-external-packages.ts @@ -13,6 +13,8 @@ const CLI_RUNTIME_EXTERNAL_PREFIXES = [ "@transcribe-cpp/", "koffi", "@koromix/", + // The local speech worker imports it from disk to encode MP3 off the server's thread. + "@breezystack/lamejs", "@napi-rs/keyring", "@clerk/electron-passkeys", "node-gyp-build", diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3a4afdb20e3d3..f84a367c76e32 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -24,6 +24,7 @@ const workspaceFiles = [ "apps/marketing/package.json", "infra/relay/package.json", "oxlint-plugin-t3code/package.json", + "packages/audio-cpp/package.json", "packages/client-runtime/package.json", "packages/contracts/package.json", "packages/shared/package.json", From 31c75afc7210b18d321583400e0ccf8bf4dc139c Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 16:32:56 -0600 Subject: [PATCH 12/33] fix(web): system voices read in the chosen language Co-authored-by: Cursor --- .../components/settings/ReadAloudSettingsSection.tsx | 6 +----- apps/web/src/speech/readAloud.ts | 11 +++++++++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 8eeed4dd4af25..4dc2fceac34e1 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -455,11 +455,7 @@ export function ReadAloudSettingsSection() { {(settings.provider === "system" || catalog.supportsVoiceSelection) && ( entry.voiceURI === voice) ?? null; let done: () => void = () => {}; let reject: (error: Error) => void = () => {}; @@ -44,7 +50,8 @@ function systemPlayback(text: string, voice: string, speed: number): SpeechPlayb const catalogs = new WeakMap>(); export const readAloudController = createReadAloudController(async (text, settings, signal) => { - if (settings.provider === "system") return systemPlayback(text, settings.voice, settings.speed); + if (settings.provider === "system") + return systemPlayback(text, settings.voice, settings.speed, settings.language); if (settings.provider === "off") throw new Error("Enable read aloud in Settings → Voice."); const prepared = settings.environmentId ? readPreparedConnection(settings.environmentId) : null; if (!prepared) From 4bcf36a8ccc41babc28d49f56b8d7db0958d1c2a Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 16:38:01 -0600 Subject: [PATCH 13/33] fix(read-aloud): download progress waits for each catalog request Co-authored-by: Cursor --- .../src/features/settings/ReadAloudSection.tsx | 10 ++++++---- .../components/settings/ReadAloudSettingsSection.tsx | 12 ++++++++---- packages/audio-cpp/package.json | 3 +-- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index e6cefe429fcb1..99ac2b7e26d65 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -120,12 +120,14 @@ export function ReadAloudSection() { const [installing, setInstalling] = useState(false); const downloading = installing || install?.state === "downloading" || install?.state === "verifying"; + // Waits for the catalog request in flight; refreshing again would abort it. + const refreshing = catalogState.version !== catalogVersion; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Poll the environment's download progress while it runs. useEffect(() => { - if (!downloading) return; - const timer = setInterval(() => setCatalogVersion((value) => value + 1), 1_000); - return () => clearInterval(timer); - }, [downloading]); + if (!downloading || refreshing) return; + const timer = setTimeout(() => setCatalogVersion((value) => value + 1), 1_000); + return () => clearTimeout(timer); + }, [downloading, refreshing]); const changeInstall = (action: "download" | "cancel" | "remove") => { if (!prepared || !selectedModel) return; setInstalling(action === "download"); diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 4dc2fceac34e1..c1a0563baac55 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -126,10 +126,13 @@ const formatSize = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`; function LocalSpeechModel({ prepared, model, + refreshing, onChanged, }: { prepared: PreparedConnection; model: SpeechSynthesisCatalog["models"][number]; + /** A catalog request is in flight; polling waits for it rather than aborting it. */ + refreshing: boolean; onChanged: () => void; }) { const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); @@ -139,10 +142,10 @@ function LocalSpeechModel({ const downloading = install?.state === "downloading" || install?.state === "verifying"; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Poll the environment's download progress while it runs. useEffect(() => { - if (!downloading && !requesting) return; - const timer = window.setInterval(onChanged, 1_000); - return () => window.clearInterval(timer); - }, [downloading, requesting, onChanged]); + if ((!downloading && !requesting) || refreshing) return; + const timer = window.setTimeout(onChanged, 1_000); + return () => window.clearTimeout(timer); + }, [downloading, requesting, refreshing, onChanged]); if (!install) return null; const run = async (action: "download" | "cancel" | "remove") => { setRequesting(true); @@ -415,6 +418,7 @@ export function ReadAloudSettingsSection() { key={`${prepared.environmentId}:${localModel.id}`} prepared={prepared} model={localModel} + refreshing={catalogState.version !== catalogVersion} onChanged={refreshCatalog} /> )} diff --git a/packages/audio-cpp/package.json b/packages/audio-cpp/package.json index b0923b4e493ed..849f8db2ad003 100644 --- a/packages/audio-cpp/package.json +++ b/packages/audio-cpp/package.json @@ -9,8 +9,7 @@ } }, "scripts": { - "typecheck": "effect-tsgo tsrs --noEmit", - "test": "vp test run --config ../../vite.config.ts --dir ." + "typecheck": "effect-tsgo tsrs --noEmit" }, "devDependencies": { "@types/node": "catalog:", From f37d2b2374f0c8ebda11b3d58d7e57b8af84a460 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 16:39:29 -0600 Subject: [PATCH 14/33] chore(audio-cpp): drop the unused test runner dependency Co-authored-by: Cursor --- packages/audio-cpp/package.json | 3 +-- pnpm-lock.yaml | 3 --- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/audio-cpp/package.json b/packages/audio-cpp/package.json index 849f8db2ad003..5e7494a59b298 100644 --- a/packages/audio-cpp/package.json +++ b/packages/audio-cpp/package.json @@ -13,7 +13,6 @@ }, "devDependencies": { "@types/node": "catalog:", - "koffi": "3.3.6", - "vite-plus": "catalog:" + "koffi": "3.3.6" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 535e29cf52749..007b17cc8bd5e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1526,9 +1526,6 @@ importers: koffi: specifier: 3.3.6 version: 3.3.6 - vite-plus: - specifier: 1.4.0 - version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) packages/client-runtime: dependencies: From 4a907ab45d63996e296f2418d7be19bf04d4deca Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 16:54:12 -0600 Subject: [PATCH 15/33] fix(read-aloud): stalled providers fail, mobile can cancel downloads, loads are not leaked Co-authored-by: Cursor --- .../features/settings/ReadAloudSection.tsx | 1 - apps/server/src/speech/CloudSpeech.ts | 6 ++++++ .../server/src/speech/LocalSpeechSynthesis.ts | 16 ++++++++++++---- apps/server/src/speech/synthesis.test.ts | 19 +++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index 99ac2b7e26d65..6ffba1f1d9dee 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -238,7 +238,6 @@ export function ReadAloudSection() { install.state === "verifying" ? "Verifying…" : `${installProgress}% downloaded` } disabled={!canManage} - loading onPress={() => changeInstall("cancel")} /> ) : install.state === "installed" ? ( diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index e845d95ac1612..bc9b9f6b1fe45 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -168,6 +168,7 @@ type SynthesisBackend = { // OpenAI accepts at most 4096 characters per request. const CLOUD_SYNTHESIS_TEXT_LIMIT = 4000; +const SYNTHESIS_STALL_TIMEOUT = "30 seconds"; function wave(samples: Float32Array) { const buffer = new ArrayBuffer(44 + samples.length * 2); @@ -525,6 +526,11 @@ export const layer = Layer.effect( ? Effect.fail(unavailable()) : Effect.succeed(chunk), ), + // The request timeout ends at the headers; a body that stalls must fail too. + Stream.timeoutOrElse({ + duration: SYNTHESIS_STALL_TIMEOUT, + orElse: () => Stream.fail(unavailable()), + }), ); }, (effect, provider) => diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index ef7e997d2d6bb..51b393f164618 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -401,7 +401,8 @@ const make = Effect.gen(function* () { ); if (!worker?.model.alive || worker.modelId !== definition.id) { yield* unloadWorker; - const model = yield* Effect.tryPromise({ + // Uninterruptible, so a stream stopped mid-load still records the process it started. + const loaded = yield* Effect.tryPromise({ try: () => loadLocalSynthesisModel({ libraries: installs.map((install) => ({ @@ -413,10 +414,17 @@ const make = Effect.gen(function* () { signal: lifetime.signal, }), catch: (cause) => failure("unavailable", cause), - }); - yield* Effect.logInfo("Loaded the local speech model.", { backend: model.backend }); - worker = { modelId: definition.id, model }; + }).pipe( + Effect.tap((model) => + Effect.sync(() => { + worker = { modelId: definition.id, model }; + }), + ), + Effect.uninterruptible, + ); + yield* Effect.logInfo("Loaded the local speech model.", { backend: loaded.backend }); } + if (!worker) return yield* failure("unavailable"); const { model } = worker; const language = localSynthesisLanguage(request.language, model.languages); const spoken = model diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index 7a82dfe25534a..c32ffa1167774 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -276,6 +276,25 @@ it.effect.each(["openai", "xai", "openrouter"] as const)( const streamFailure = yield* Effect.flip(synthesize(provider, request)); expect(streamFailure).toHaveProperty("cause"); expect(streamFailure.message).not.toContain("private stream diagnostic"); + const reading = Promise.withResolvers(); + upstream.mockResolvedValueOnce( + new Response( + // No buffer, so pull runs only once synthesis reads the body. + new ReadableStream( + { + pull: () => { + reading.resolve(); + return new Promise(() => {}); + }, + }, + { highWaterMark: 0 }, + ), + ), + ); + const stalled = yield* Effect.forkChild(Effect.flip(synthesize(provider, request))); + yield* Effect.promise(() => reading.promise); + yield* TestClock.adjust("2 minutes"); + expect(yield* Fiber.join(stalled)).toMatchObject({ reason: "unavailable" }); for (const operation of (provider === "openai" ? ["synthesis"] : ["catalog", "synthesis"]) as ReadonlyArray<"catalog" | "synthesis">) { From e90bc993ba3a62cedea338bac1bddf88e367fd35 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 17:02:46 -0600 Subject: [PATCH 16/33] fix(read-aloud): resolve the key per piece and claim a download before yielding Co-authored-by: Cursor --- apps/server/src/speech/CloudSpeech.test.ts | 40 +++++++++++ apps/server/src/speech/CloudSpeech.ts | 35 ++++------ .../src/speech/LocalSpeechSynthesis.test.ts | 66 +++++++++++++++++++ .../server/src/speech/LocalSpeechSynthesis.ts | 3 +- 4 files changed, 120 insertions(+), 24 deletions(-) create mode 100644 apps/server/src/speech/LocalSpeechSynthesis.test.ts diff --git a/apps/server/src/speech/CloudSpeech.test.ts b/apps/server/src/speech/CloudSpeech.test.ts index 0f0542e551fe5..c6de2608369b6 100644 --- a/apps/server/src/speech/CloudSpeech.test.ts +++ b/apps/server/src/speech/CloudSpeech.test.ts @@ -6,6 +6,7 @@ import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import { expect, vi } from "vite-plus/test"; import * as ServerSettings from "../serverSettings.ts"; @@ -98,6 +99,45 @@ it.effect.each(["openai", "xai"] as const)("sends only to %s using its own saved }), ); +it.effect("stops a long reply when its vault-backed key locks between pieces", () => + Effect.gen(function* () { + const reference = { provider: SecretProviderId.make("work"), reference: "op://Work/Voice/key" }; + let secret: string | undefined = "vault-key"; + const upstream = vi.fn(async () => { + secret = undefined; + return new Response(Uint8Array.of(0xff, 0xfb), { headers: { "content-type": "audio/mpeg" } }); + }); + const service = yield* CloudSpeech.CloudSpeech.pipe( + Effect.provide( + CloudSpeech.layer.pipe( + Layer.provide(NodeServices.layer), + Layer.provide(FetchHttpClient.layer), + Layer.provide(ServerSettings.ServerSettingsService.layerTest()), + Layer.provide( + Layer.mock(SecretResolver.SecretResolver)({ + read: () => Effect.sync(() => [secret]), + label: () => Effect.succeed("Work"), + invalidate: () => Effect.void, + }), + ), + ), + ), + ); + yield* service.setKey("openai", reference); + const failure = yield* service + .stream("openai", { + text: "Read this sentence aloud. ".repeat(200), + model: "", + voice: "", + speed: 1, + language: "en", + }) + .pipe(Stream.runDrain, Effect.flip, Effect.provideService(FetchHttpClient.Fetch, upstream)); + expect(failure).toMatchObject({ reason: "unreadable-key" }); + expect(upstream).toHaveBeenCalledTimes(1); + }), +); + it.effect("uploads to OpenRouter only for a listed exact model, as zero-retention JSON WAV", () => Effect.gen(function* () { const upstream = vi.fn(async (input) => diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index bc9b9f6b1fe45..77f24b691e347 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -490,16 +490,17 @@ export const layer = Layer.effect( ); }); const synthesizePiece = Effect.fn("CloudSpeech.synthesizePiece")( - function* ( - provider: CloudSpeechProvider, - source: SettingsSecretValue | undefined, - key: string, - input: SpeechSynthesisRequest, - ) { + function* (provider: CloudSpeechProvider, input: SpeechSynthesisRequest) { const unavailable = (cause?: unknown) => isSynthesisError(cause) ? cause : new SpeechSynthesisError({ provider, reason: "unavailable", cause }); + // Resolved per piece, so a long reply stops when its key is locked, removed, or replaced. + const source = (yield* credentials)[provider]; + const key = yield* resolveKey( + source, + (reason, cause) => new SpeechSynthesisError({ provider, reason, cause }), + ); const backend: SynthesisBackend = synthesisBackends[provider]; const synthesisRequest = yield* backend.request(input); const current = (yield* credentials)[provider]; @@ -542,24 +543,12 @@ export const layer = Layer.effect( }), ), ); + // Pieces play back to back as one stream; each is requested once the last one ends. const stream = (provider: CloudSpeechProvider, request: SpeechSynthesisRequest) => - Stream.unwrap( - Effect.gen(function* () { - const source = (yield* credentials)[provider]; - const key = yield* resolveKey( - source, - (reason, cause) => new SpeechSynthesisError({ provider, reason, cause }), - ); - // Pieces play back to back as one stream; each is requested once the last one ends. - return Stream.fromIterable( - splitReadAloudText(request.text, CLOUD_SYNTHESIS_TEXT_LIMIT), - ).pipe( - Stream.flatMap((text) => - Stream.unwrap(synthesizePiece(provider, source, key, { ...request, text })), - ), - ); - }), - ).pipe(Stream.withSpan("CloudSpeech.stream")); + Stream.fromIterable(splitReadAloudText(request.text, CLOUD_SYNTHESIS_TEXT_LIMIT)).pipe( + Stream.flatMap((text) => Stream.unwrap(synthesizePiece(provider, { ...request, text }))), + Stream.withSpan("CloudSpeech.stream"), + ); const setKey = Effect.fn("CloudSpeech.setKey")(function* ( provider: CloudSpeechProvider, key: Redacted.Redacted | SecretReference | null, diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts new file mode 100644 index 0000000000000..22ddf5f758df7 --- /dev/null +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -0,0 +1,66 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { AUDIO_CPP_VERSION } from "@t3tools/audio-cpp"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import { expect, vi } from "vite-plus/test"; +import * as ServerConfig from "../config.ts"; +import * as LocalSpeechSynthesis from "./LocalSpeechSynthesis.ts"; +import * as SpeechModelStore from "./SpeechModelStore.ts"; + +it.effect("joins a second download of the same model instead of starting another install", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const download = vi.fn(() => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as("/unused"), + ), + ); + const layer = LocalSpeechSynthesis.layer.pipe( + Layer.provide( + Layer.mock(SpeechModelStore.SpeechModelStore)({ + download, + isReady: () => Effect.succeed(false), + }), + ), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-local-speech-" })), + Layer.provide(SecureRandom.layerWebCrypto), + Layer.provideMerge(NodeServices.layer), + ); + yield* Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // An extracted runtime, so each install downloads only the model. + const runtime = path.join( + config.stateDir, + "speech", + "runtime", + `audio-cpp-${AUDIO_CPP_VERSION}-darwin-arm64`, + "metal", + ); + yield* fs.makeDirectory(path.join(runtime, "libs"), { recursive: true }); + yield* fs.writeFileString(path.join(runtime, ".t3-complete"), AUDIO_CPP_VERSION); + yield* fs.writeFileString(path.join(runtime, "libs", "libaudiocpp.0.1.0.dylib"), ""); + const service = yield* LocalSpeechSynthesis.LocalSpeechSynthesis; + const first = yield* Effect.forkChild(service.download("supertonic-3")); + const second = yield* Effect.forkChild(service.download("supertonic-3")); + yield* Deferred.await(started); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + expect(download).toHaveBeenCalledTimes(1); + }).pipe(Effect.provide(layer)); + }).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Architecture, "arm64"), + ), +); diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 51b393f164618..b2034ea9f53f5 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -262,10 +262,11 @@ const make = Effect.gen(function* () { const model = yield* findModel(modelId); if (!installs.length) return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); + // Read before the checks below: no yield may separate them from claiming `transfer`. + const missing = yield* missingRuntimes; if (transfer && transfer.modelId !== modelId) return yield* new LocalSynthesisInstallError({ reason: "busy" }); if (!transfer) { - const missing = yield* missingRuntimes; const state: Transfer = { modelId, size: missing.reduce((size, install) => size + install.file.size, model.file.size), From 28343fe77d9d45861bd5015c2843a78f6b59ea1b Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 17:05:34 -0600 Subject: [PATCH 17/33] fix(read-aloud): resolve the speech key after building each request Co-authored-by: Cursor --- apps/server/src/speech/CloudSpeech.test.ts | 89 +++++++++++++--------- apps/server/src/speech/CloudSpeech.ts | 7 +- 2 files changed, 58 insertions(+), 38 deletions(-) diff --git a/apps/server/src/speech/CloudSpeech.test.ts b/apps/server/src/speech/CloudSpeech.test.ts index c6de2608369b6..b6f64ec34aa24 100644 --- a/apps/server/src/speech/CloudSpeech.test.ts +++ b/apps/server/src/speech/CloudSpeech.test.ts @@ -99,43 +99,62 @@ it.effect.each(["openai", "xai"] as const)("sends only to %s using its own saved }), ); -it.effect("stops a long reply when its vault-backed key locks between pieces", () => - Effect.gen(function* () { - const reference = { provider: SecretProviderId.make("work"), reference: "op://Work/Voice/key" }; - let secret: string | undefined = "vault-key"; - const upstream = vi.fn(async () => { - secret = undefined; - return new Response(Uint8Array.of(0xff, 0xfb), { headers: { "content-type": "audio/mpeg" } }); - }); - const service = yield* CloudSpeech.CloudSpeech.pipe( - Effect.provide( - CloudSpeech.layer.pipe( - Layer.provide(NodeServices.layer), - Layer.provide(FetchHttpClient.layer), - Layer.provide(ServerSettings.ServerSettingsService.layerTest()), - Layer.provide( - Layer.mock(SecretResolver.SecretResolver)({ - read: () => Effect.sync(() => [secret]), - label: () => Effect.succeed("Work"), - invalidate: () => Effect.void, - }), +it.effect.each([ + { + provider: "openai", + window: "between pieces", + text: "Read this sentence aloud. ".repeat(200), + model: "", + uploads: 1, + }, + // An empty voice makes OpenRouter's request builder fetch the catalog for a default. + { + provider: "openrouter", + window: "while the request is built", + text: "Read this reply.", + model: "acme/voice", + uploads: 0, + }, +] as const)( + "stops a reply when its vault-backed key locks $window", + ({ provider, text, model, uploads }) => + Effect.gen(function* () { + const reference = { + provider: SecretProviderId.make("work"), + reference: "op://Work/Voice/key", + }; + let secret: string | undefined = "vault-key"; + const upstream = vi.fn(async (input) => { + secret = undefined; + return new URL(String(input)).pathname.endsWith("/models") + ? Response.json({ data: [{ id: "acme/voice", supported_voices: ["reader"] }] }) + : new Response(Uint8Array.of(0xff, 0xfb), { headers: { "content-type": "audio/mpeg" } }); + }); + const service = yield* CloudSpeech.CloudSpeech.pipe( + Effect.provide( + CloudSpeech.layer.pipe( + Layer.provide(NodeServices.layer), + Layer.provide(FetchHttpClient.layer), + Layer.provide(ServerSettings.ServerSettingsService.layerTest()), + Layer.provide( + Layer.mock(SecretResolver.SecretResolver)({ + read: () => Effect.sync(() => [secret]), + label: () => Effect.succeed("Work"), + invalidate: () => Effect.void, + }), + ), ), ), - ), - ); - yield* service.setKey("openai", reference); - const failure = yield* service - .stream("openai", { - text: "Read this sentence aloud. ".repeat(200), - model: "", - voice: "", - speed: 1, - language: "en", - }) - .pipe(Stream.runDrain, Effect.flip, Effect.provideService(FetchHttpClient.Fetch, upstream)); - expect(failure).toMatchObject({ reason: "unreadable-key" }); - expect(upstream).toHaveBeenCalledTimes(1); - }), + ); + yield* service.setKey(provider, reference); + const failure = yield* service + .stream(provider, { text, model, voice: "", speed: 1, language: "en" }) + .pipe(Stream.runDrain, Effect.flip, Effect.provideService(FetchHttpClient.Fetch, upstream)); + expect(failure).toMatchObject({ reason: "unreadable-key" }); + expect( + upstream.mock.calls.filter(([url]) => String(url).endsWith("/audio/speech")), + ).toHaveLength(uploads); + }), ); it.effect("uploads to OpenRouter only for a listed exact model, as zero-retention JSON WAV", () => diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index 77f24b691e347..6ac6e1af60c52 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -495,14 +495,15 @@ export const layer = Layer.effect( isSynthesisError(cause) ? cause : new SpeechSynthesisError({ provider, reason: "unavailable", cause }); - // Resolved per piece, so a long reply stops when its key is locked, removed, or replaced. const source = (yield* credentials)[provider]; + const backend: SynthesisBackend = synthesisBackends[provider]; + const synthesisRequest = yield* backend.request(input); + // Resolved per piece and after building, which may fetch a catalog, so the key sent is + // never older than the vault's state at send time. const key = yield* resolveKey( source, (reason, cause) => new SpeechSynthesisError({ provider, reason, cause }), ); - const backend: SynthesisBackend = synthesisBackends[provider]; - const synthesisRequest = yield* backend.request(input); const current = (yield* credentials)[provider]; if (!current || !source || !sameCredential(source, current)) return yield* new SpeechSynthesisError({ provider, reason: "key-changed" }); From 668aba2fee375e570bf16e166d95bbe6bfb4e8dd Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 17:16:47 -0600 Subject: [PATCH 18/33] fix(read-aloud): removals and installs do not overlap, cloud pieces fit every model Co-authored-by: Cursor --- apps/server/src/speech/CloudSpeech.test.ts | 34 ++++ apps/server/src/speech/CloudSpeech.ts | 5 +- .../src/speech/LocalSpeechSynthesis.test.ts | 147 +++++++++++++----- .../server/src/speech/LocalSpeechSynthesis.ts | 40 +++-- 4 files changed, 173 insertions(+), 53 deletions(-) diff --git a/apps/server/src/speech/CloudSpeech.test.ts b/apps/server/src/speech/CloudSpeech.test.ts index b6f64ec34aa24..a42313c9bdcd5 100644 --- a/apps/server/src/speech/CloudSpeech.test.ts +++ b/apps/server/src/speech/CloudSpeech.test.ts @@ -157,6 +157,40 @@ it.effect.each([ }), ); +it.effect("splits CJK replies below gpt-4o-mini-tts's token limit", () => + Effect.gen(function* () { + const upstream = vi.fn( + async () => + new Response(Uint8Array.of(0xff, 0xfb), { headers: { "content-type": "audio/mpeg" } }), + ); + const service = yield* CloudSpeech.CloudSpeech.pipe( + Effect.provide( + CloudSpeech.layer.pipe( + Layer.provide(NodeServices.layer), + Layer.provide(FetchHttpClient.layer), + Layer.provide(ServerSettings.ServerSettingsService.layerTest()), + Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})), + ), + ), + ); + yield* service.setKey("openai", Redacted.make("speech-key")); + yield* service + .stream("openai", { + text: "読み上げのテストです。".repeat(250), + model: "gpt-4o-mini-tts", + voice: "", + speed: 1, + language: "ja", + }) + .pipe(Stream.runDrain, Effect.provideService(FetchHttpClient.Fetch, upstream)); + const inputs = upstream.mock.calls.map( + ([, init]) => (JSON.parse(String(init?.body)) as { input: string }).input, + ); + expect(inputs.length).toBeGreaterThan(1); + expect(inputs.every((input) => input.length <= 1000)).toBe(true); + }), +); + it.effect("uploads to OpenRouter only for a listed exact model, as zero-retention JSON WAV", () => Effect.gen(function* () { const upstream = vi.fn(async (input) => diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index 6ac6e1af60c52..af893c95d872a 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -166,8 +166,9 @@ type SynthesisBackend = { errorReason: (status: number) => SpeechSynthesisError["reason"]; }; -// OpenAI accepts at most 4096 characters per request. -const CLOUD_SYNTHESIS_TEXT_LIMIT = 4000; +// gpt-4o-mini-tts accepts 2,000 tokens, which Chinese or Japanese reaches near 2,000 characters, +// and OpenRouter's Seed Audio accepts 3,000 characters. Pieces stream back to back, so small is cheap. +const CLOUD_SYNTHESIS_TEXT_LIMIT = 1000; const SYNTHESIS_STALL_TIMEOUT = "30 seconds"; function wave(samples: Float32Array) { diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts index 22ddf5f758df7..09a848ef858f2 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.test.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -14,53 +14,126 @@ import * as ServerConfig from "../config.ts"; import * as LocalSpeechSynthesis from "./LocalSpeechSynthesis.ts"; import * as SpeechModelStore from "./SpeechModelStore.ts"; +/** + * Runs `body` against the service with an extracted runtime, so installs download only the model. + * `checkingRuntime` wraps the service's last file check before it decides whether to install. + */ +const withService = ( + store: Partial, + body: ( + service: LocalSpeechSynthesis.LocalSpeechSynthesis["Service"], + ) => Effect.Effect, + checkingRuntime: (check: Effect.Effect) => Effect.Effect = (check) => check, +) => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const runtime = path.join( + config.stateDir, + "speech", + "runtime", + `audio-cpp-${AUDIO_CPP_VERSION}-darwin-arm64`, + "metal", + ); + yield* fs.makeDirectory(path.join(runtime, "libs"), { recursive: true }); + yield* fs.writeFileString(path.join(runtime, ".t3-complete"), AUDIO_CPP_VERSION); + yield* fs.writeFileString(path.join(runtime, "libs", "libaudiocpp.0.1.0.dylib"), ""); + return yield* body(yield* LocalSpeechSynthesis.LocalSpeechSynthesis); + }).pipe( + Effect.provide( + LocalSpeechSynthesis.layer.pipe( + Layer.provide( + Layer.effect( + FileSystem.FileSystem, + Effect.map(FileSystem.FileSystem, (fs) => + FileSystem.FileSystem.of({ + ...fs, + exists: (path) => + path.endsWith("libaudiocpp.0.1.0.dylib") + ? checkingRuntime(fs.exists(path)) + : fs.exists(path), + }), + ), + ), + ), + Layer.provide( + Layer.mock(SpeechModelStore.SpeechModelStore)({ + isReady: () => Effect.succeed(false), + ...store, + }), + ), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-local-speech-" })), + Layer.provide(SecureRandom.layerWebCrypto), + Layer.provideMerge(NodeServices.layer), + ), + ), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Architecture, "arm64"), + ); + it.effect("joins a second download of the same model instead of starting another install", () => Effect.gen(function* () { + const bothChecking = yield* Deferred.make(); + const checked = yield* Deferred.make(); const started = yield* Deferred.make(); const release = yield* Deferred.make(); + let checking = 0; const download = vi.fn(() => Deferred.succeed(started, undefined).pipe( Effect.andThen(Deferred.await(release)), Effect.as("/unused"), ), ); - const layer = LocalSpeechSynthesis.layer.pipe( - Layer.provide( - Layer.mock(SpeechModelStore.SpeechModelStore)({ - download, - isReady: () => Effect.succeed(false), + yield* withService( + { download }, + (service) => + Effect.gen(function* () { + const first = yield* Effect.forkChild(service.download("supertonic-3")); + const second = yield* Effect.forkChild(service.download("supertonic-3")); + // Both are mid-check, the window in which they could both claim the install. + yield* Deferred.await(bothChecking); + yield* Deferred.succeed(checked, undefined); + yield* Deferred.await(started); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + expect(download).toHaveBeenCalledTimes(1); }), - ), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-local-speech-" })), - Layer.provide(SecureRandom.layerWebCrypto), - Layer.provideMerge(NodeServices.layer), + // Holds each finished check, so nothing asynchronous separates the gate from the decision. + (check) => + check.pipe( + Effect.tap(() => + ++checking === 2 ? Deferred.succeed(bothChecking, undefined) : Effect.void, + ), + Effect.tap(() => Deferred.await(checked)), + ), ); - yield* Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - // An extracted runtime, so each install downloads only the model. - const runtime = path.join( - config.stateDir, - "speech", - "runtime", - `audio-cpp-${AUDIO_CPP_VERSION}-darwin-arm64`, - "metal", - ); - yield* fs.makeDirectory(path.join(runtime, "libs"), { recursive: true }); - yield* fs.writeFileString(path.join(runtime, ".t3-complete"), AUDIO_CPP_VERSION); - yield* fs.writeFileString(path.join(runtime, "libs", "libaudiocpp.0.1.0.dylib"), ""); - const service = yield* LocalSpeechSynthesis.LocalSpeechSynthesis; - const first = yield* Effect.forkChild(service.download("supertonic-3")); - const second = yield* Effect.forkChild(service.download("supertonic-3")); - yield* Deferred.await(started); - yield* Deferred.succeed(release, undefined); - yield* Fiber.join(first); - yield* Fiber.join(second); - expect(download).toHaveBeenCalledTimes(1); - }).pipe(Effect.provide(layer)); - }).pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(HostProcess.Architecture, "arm64"), - ), + }), +); + +it.effect("refuses a download while a removal deletes the shared runtime", () => + Effect.gen(function* () { + const removing = yield* Deferred.make(); + const release = yield* Deferred.make(); + const download = vi.fn(() => Effect.succeed("/unused")); + yield* withService( + { + download, + remove: () => + Deferred.succeed(removing, undefined).pipe(Effect.andThen(Deferred.await(release))), + }, + (service) => + Effect.gen(function* () { + const removal = yield* Effect.forkChild(service.remove("supertonic-3")); + yield* Deferred.await(removing); + expect(yield* Effect.flip(service.download("supertonic-3"))).toMatchObject({ + reason: "busy", + }); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(removal); + expect(download).not.toHaveBeenCalled(); + }), + ); + }), ); diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index b2034ea9f53f5..d2635790805eb 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -215,6 +215,8 @@ const make = Effect.gen(function* () { fiber?: Fiber.Fiber; }; let transfer: Transfer | undefined; + // A removal deletes the shared runtime, so it and an install must not overlap. + let removing = false; const catalog = Effect.gen(function* () { const missing = yield* missingRuntimes; @@ -264,7 +266,7 @@ const make = Effect.gen(function* () { return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); // Read before the checks below: no yield may separate them from claiming `transfer`. const missing = yield* missingRuntimes; - if (transfer && transfer.modelId !== modelId) + if (removing || (transfer && transfer.modelId !== modelId)) return yield* new LocalSynthesisInstallError({ reason: "busy" }); if (!transfer) { const state: Transfer = { @@ -356,20 +358,30 @@ const make = Effect.gen(function* () { const remove = Effect.fn("LocalSpeechSynthesis.remove")(function* (modelId: string) { const model = yield* findModel(modelId); - if (transfer?.modelId === modelId) - return yield* new LocalSynthesisInstallError({ reason: "busy" }); - yield* permit.withPermits(1)( - Effect.gen(function* () { - if (worker?.modelId === modelId) yield* unloadWorker; - yield* store.remove(model.file).pipe(Effect.mapError(installFailed)); - const remaining = yield* Effect.filter(LOCAL_SYNTHESIS_MODELS, (entry) => - store.isReady(entry.file), - ); - if (remaining.length === 0) - yield* fs - .remove(runtimeRoot, { recursive: true, force: true }) - .pipe(Effect.mapError(installFailed)); + yield* Effect.acquireUseRelease( + Effect.suspend(() => { + if (transfer || removing) return new LocalSynthesisInstallError({ reason: "busy" }); + removing = true; + return Effect.void; }), + () => + permit.withPermits(1)( + Effect.gen(function* () { + if (worker?.modelId === modelId) yield* unloadWorker; + yield* store.remove(model.file).pipe(Effect.mapError(installFailed)); + const remaining = yield* Effect.filter(LOCAL_SYNTHESIS_MODELS, (entry) => + store.isReady(entry.file), + ); + if (remaining.length === 0) + yield* fs + .remove(runtimeRoot, { recursive: true, force: true }) + .pipe(Effect.mapError(installFailed)); + }), + ), + () => + Effect.sync(() => { + removing = false; + }), ); return yield* catalog; }); From aeb6dc4a743c620553812fd3535b8f7a47ca0cb3 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 17:20:09 -0600 Subject: [PATCH 19/33] fix(read-aloud): claim a model install before reading which runtimes it needs Co-authored-by: Cursor --- .../src/speech/LocalSpeechSynthesis.test.ts | 56 ++++--------------- .../server/src/speech/LocalSpeechSynthesis.ts | 12 ++-- 2 files changed, 18 insertions(+), 50 deletions(-) diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts index 09a848ef858f2..4f3041450e97a 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.test.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -14,16 +14,12 @@ import * as ServerConfig from "../config.ts"; import * as LocalSpeechSynthesis from "./LocalSpeechSynthesis.ts"; import * as SpeechModelStore from "./SpeechModelStore.ts"; -/** - * Runs `body` against the service with an extracted runtime, so installs download only the model. - * `checkingRuntime` wraps the service's last file check before it decides whether to install. - */ +/** Runs `body` against the service with an extracted runtime, so installs download only the model. */ const withService = ( store: Partial, body: ( service: LocalSpeechSynthesis.LocalSpeechSynthesis["Service"], ) => Effect.Effect, - checkingRuntime: (check: Effect.Effect) => Effect.Effect = (check) => check, ) => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -43,20 +39,6 @@ const withService = ( }).pipe( Effect.provide( LocalSpeechSynthesis.layer.pipe( - Layer.provide( - Layer.effect( - FileSystem.FileSystem, - Effect.map(FileSystem.FileSystem, (fs) => - FileSystem.FileSystem.of({ - ...fs, - exists: (path) => - path.endsWith("libaudiocpp.0.1.0.dylib") - ? checkingRuntime(fs.exists(path)) - : fs.exists(path), - }), - ), - ), - ), Layer.provide( Layer.mock(SpeechModelStore.SpeechModelStore)({ isReady: () => Effect.succeed(false), @@ -74,40 +56,24 @@ const withService = ( it.effect("joins a second download of the same model instead of starting another install", () => Effect.gen(function* () { - const bothChecking = yield* Deferred.make(); - const checked = yield* Deferred.make(); const started = yield* Deferred.make(); const release = yield* Deferred.make(); - let checking = 0; const download = vi.fn(() => Deferred.succeed(started, undefined).pipe( Effect.andThen(Deferred.await(release)), Effect.as("/unused"), ), ); - yield* withService( - { download }, - (service) => - Effect.gen(function* () { - const first = yield* Effect.forkChild(service.download("supertonic-3")); - const second = yield* Effect.forkChild(service.download("supertonic-3")); - // Both are mid-check, the window in which they could both claim the install. - yield* Deferred.await(bothChecking); - yield* Deferred.succeed(checked, undefined); - yield* Deferred.await(started); - yield* Deferred.succeed(release, undefined); - yield* Fiber.join(first); - yield* Fiber.join(second); - expect(download).toHaveBeenCalledTimes(1); - }), - // Holds each finished check, so nothing asynchronous separates the gate from the decision. - (check) => - check.pipe( - Effect.tap(() => - ++checking === 2 ? Deferred.succeed(bothChecking, undefined) : Effect.void, - ), - Effect.tap(() => Deferred.await(checked)), - ), + yield* withService({ download }, (service) => + Effect.gen(function* () { + const first = yield* Effect.forkChild(service.download("supertonic-3")); + const second = yield* Effect.forkChild(service.download("supertonic-3")); + yield* Deferred.await(started); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + expect(download).toHaveBeenCalledTimes(1); + }), ); }), ); diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index d2635790805eb..54e88d49bd264 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -207,8 +207,8 @@ const make = Effect.gen(function* () { type Transfer = { readonly modelId: string; - /** Fixed at the start, so extracting the runtime mid-transfer does not shrink it. */ - readonly size: number; + /** Fixed once the install knows its runtimes, so extracting one does not shrink it. */ + size: number; runtime: number; model: number; verifying: boolean; @@ -264,20 +264,22 @@ const make = Effect.gen(function* () { const model = yield* findModel(modelId); if (!installs.length) return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); - // Read before the checks below: no yield may separate them from claiming `transfer`. - const missing = yield* missingRuntimes; + // Checked and claimed without yielding, so a concurrent download or removal cannot interleave. if (removing || (transfer && transfer.modelId !== modelId)) return yield* new LocalSynthesisInstallError({ reason: "busy" }); if (!transfer) { const state: Transfer = { modelId, - size: missing.reduce((size, install) => size + install.file.size, model.file.size), + size: model.file.size, runtime: 0, model: 0, verifying: false, }; transfer = state; const install = Effect.gen(function* () { + // Read after claiming: no removal can start while this transfer exists. + const missing = yield* missingRuntimes; + state.size = missing.reduce((size, install) => size + install.file.size, state.size); let installed = 0; for (const install of missing) { const archivePath = yield* store.download(install.file, { From 058f5e01612542f178495e170f35f752beefc978 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 18:31:48 -0600 Subject: [PATCH 20/33] feat(read-aloud): local speech uses pingdotgg/audio.cpp builds with GPU and older Linux support Co-authored-by: Cursor --- .../src/speech/LocalSpeechSynthesis.test.ts | 1 - .../server/src/speech/LocalSpeechSynthesis.ts | 119 ++++++++---------- .../server/src/speech/localSynthesisWorker.ts | 24 ++-- apps/server/src/speech/synthesis.test.ts | 36 +++--- docs/user/composer.md | 6 +- packages/audio-cpp/src/index.ts | 2 +- packages/audio-cpp/src/runtime.ts | 98 +++++++-------- 7 files changed, 126 insertions(+), 160 deletions(-) diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts index 4f3041450e97a..22b2bddaa4d83 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.test.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -30,7 +30,6 @@ const withService = ( "speech", "runtime", `audio-cpp-${AUDIO_CPP_VERSION}-darwin-arm64`, - "metal", ); yield* fs.makeDirectory(path.join(runtime, "libs"), { recursive: true }); yield* fs.writeFileString(path.join(runtime, ".t3-complete"), AUDIO_CPP_VERSION); diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 54e88d49bd264..01e0639909abe 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -5,7 +5,7 @@ import { type SpeechSynthesisCatalog, type SpeechSynthesisRequest, } from "@t3tools/contracts"; -import { AUDIO_CPP_VERSION, audioCppRuntimes, type AudioCppRuntime } from "@t3tools/audio-cpp"; +import { AUDIO_CPP_VERSION, audioCppRuntime, type AudioCppRuntime } from "@t3tools/audio-cpp"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; @@ -97,28 +97,25 @@ const atLeast = (version: string, minimum: string) => { return major > wantedMajor || (major === wantedMajor && minor >= wantedMinor); }; -/** The audio.cpp builds a host installs, or why it cannot run local speech models. */ -export function localSynthesisRuntimes(host: { +/** The audio.cpp build a host installs, or why it cannot run local speech models. */ +export function localSynthesisRuntime(host: { readonly platform: string; readonly architecture: string; readonly libc: "gnu" | "musl" | undefined; readonly glibc: string | undefined; -}): { readonly runtimes: readonly AudioCppRuntime[]; readonly error?: string } { - const runtimes = isSpeechPlatformSupported(host.platform, host.architecture, host.libc) - ? audioCppRuntimes(host.platform, host.architecture) - : []; - if (!runtimes.length) +}): { readonly runtime?: AudioCppRuntime; readonly error?: string } { + const runtime = isSpeechPlatformSupported(host.platform, host.architecture, host.libc) + ? audioCppRuntime(host.platform, host.architecture) + : undefined; + if (!runtime) return { - runtimes, error: `Local speech models are not available on ${host.platform}-${host.architecture}.`, }; - const minimum = runtimes.find((runtime) => runtime.minimumGlibc)?.minimumGlibc; - if (minimum && !(host.glibc && atLeast(host.glibc, minimum))) + if (runtime.minimumGlibc && !(host.glibc && atLeast(host.glibc, runtime.minimumGlibc))) return { - runtimes: [], - error: `Local speech models need glibc ${minimum} or newer, such as Ubuntu 26.04. This environment has glibc ${host.glibc ?? "unknown"}.`, + error: `Local speech models need glibc ${runtime.minimumGlibc} or newer. This environment has glibc ${host.glibc ?? "unknown"}.`, }; - return { runtimes }; + return { runtime }; } const make = Effect.gen(function* () { @@ -131,52 +128,41 @@ const make = Effect.gen(function* () { const scope = yield* Effect.scope; const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; - const { runtimes, error: unavailable } = localSynthesisRuntimes({ + const { runtime, error: unavailable } = localSynthesisRuntime({ platform, architecture, libc: platform === "linux" ? yield* HostProcess.LinuxLibc : undefined, glibc: platform === "linux" ? yield* HostProcess.GlibcVersion : undefined, }); - const runtimeRoot = path.join( + const runtimeFile = runtime && { + id: "pingdotgg/audio.cpp", + revision: AUDIO_CPP_VERSION, + filename: runtime.filename, + url: runtime.url, + size: runtime.size, + sha256: runtime.sha256, + }; + const runtimeDirectory = path.join( config.stateDir, "speech", "runtime", `audio-cpp-${AUDIO_CPP_VERSION}-${platform}-${architecture}`, ); - const installs = runtimes.map((runtime) => { - const directory = path.join(runtimeRoot, runtime.backend); - return { - runtime, - file: { - id: "0xShug0/audio.cpp", - revision: AUDIO_CPP_VERSION, - filename: runtime.filename, - url: runtime.url, - size: runtime.size, - sha256: runtime.sha256, - }, - directory, - libraryPath: path.join(directory, runtime.library), - // Written last, so a directory without it is an interrupted extraction. - completeMarker: path.join(directory, ".t3-complete"), - }; - }); - type RuntimeInstall = (typeof installs)[number]; + const libraryPath = runtime && path.join(runtimeDirectory, runtime.library); + // Written last, so a directory without it is an interrupted extraction. + const completeMarker = path.join(runtimeDirectory, ".t3-complete"); - const missingRuntimes = Effect.filter(installs, (install) => - Effect.gen(function* () { - return !( - (yield* fs.exists(install.completeMarker)) && (yield* fs.exists(install.libraryPath)) - ); - }).pipe(Effect.orElseSucceed(() => true)), - ); + const runtimeReady = Effect.gen(function* () { + if (!libraryPath) return false; + return (yield* fs.exists(completeMarker)) && (yield* fs.exists(libraryPath)); + }).pipe(Effect.orElseSucceed(() => false)); // System tar reads .tar.gz on macOS and Linux and .zip on Windows 10 and later. const extract = Effect.fn("LocalSpeechSynthesis.extract")(function* ( - install: RuntimeInstall, + library: string, archivePath: string, ) { - const staging = `${install.directory}.${yield* random.uuidV4()}.part`; + const staging = `${runtimeDirectory}.${yield* random.uuidV4()}.part`; yield* fs.makeDirectory(staging, { recursive: true }); yield* Effect.gen(function* () { const child = yield* spawner.spawn( @@ -187,14 +173,14 @@ const make = Effect.gen(function* () { }), ); const exitCode = yield* child.exitCode; - if (exitCode !== 0 || !(yield* fs.exists(path.join(staging, install.runtime.library)))) + if (exitCode !== 0 || !(yield* fs.exists(path.join(staging, library)))) return yield* new LocalSynthesisInstallError({ reason: "failed", cause: `tar exited with ${exitCode} or the archive has no library.`, }); yield* fs.writeFileString(path.join(staging, ".t3-complete"), AUDIO_CPP_VERSION); - yield* fs.remove(install.directory, { recursive: true, force: true }); - yield* fs.rename(staging, install.directory); + yield* fs.remove(runtimeDirectory, { recursive: true, force: true }); + yield* fs.rename(staging, runtimeDirectory); }).pipe( Effect.scoped, Effect.onExit((exit) => @@ -207,7 +193,7 @@ const make = Effect.gen(function* () { type Transfer = { readonly modelId: string; - /** Fixed once the install knows its runtimes, so extracting one does not shrink it. */ + /** Fixed once the install knows whether it needs the runtime, so extracting it does not shrink it. */ size: number; runtime: number; model: number; @@ -219,8 +205,8 @@ const make = Effect.gen(function* () { let removing = false; const catalog = Effect.gen(function* () { - const missing = yield* missingRuntimes; - const runtimeSize = missing.reduce((size, install) => size + install.file.size, 0); + const ready = yield* runtimeReady; + const runtimeSize = ready || !runtimeFile ? 0 : runtimeFile.size; const models = yield* Effect.forEach(LOCAL_SYNTHESIS_MODELS, (model) => Effect.gen(function* () { const active = transfer?.modelId === model.id ? transfer : undefined; @@ -233,7 +219,7 @@ const make = Effect.gen(function* () { } : { state: - installs.length && !missing.length && (yield* store.isReady(model.file)) + ready && (yield* store.isReady(model.file)) ? ("installed" as const) : ("downloadable" as const), size, @@ -262,7 +248,7 @@ const make = Effect.gen(function* () { // Publishes the transfer before forking: a cached file can finish before forkIn returns. const reserve = Effect.fn("LocalSpeechSynthesis.reserve")(function* (modelId: string) { const model = yield* findModel(modelId); - if (!installs.length) + if (!runtimeFile || !runtime) return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); // Checked and claimed without yielding, so a concurrent download or removal cannot interleave. if (removing || (transfer && transfer.modelId !== modelId)) @@ -278,13 +264,11 @@ const make = Effect.gen(function* () { transfer = state; const install = Effect.gen(function* () { // Read after claiming: no removal can start while this transfer exists. - const missing = yield* missingRuntimes; - state.size = missing.reduce((size, install) => size + install.file.size, state.size); - let installed = 0; - for (const install of missing) { - const archivePath = yield* store.download(install.file, { + if (!(yield* runtimeReady)) { + state.size += runtimeFile.size; + const archivePath = yield* store.download(runtimeFile, { onProgress: (downloaded) => { - state.runtime = installed + downloaded; + state.runtime = downloaded; state.verifying = false; }, onVerificationStart: () => { @@ -292,10 +276,9 @@ const make = Effect.gen(function* () { }, }); state.verifying = true; - yield* extract(install, archivePath); - yield* store.remove(install.file).pipe(Effect.ignore); - installed += install.file.size; - state.runtime = installed; + yield* extract(runtime.library, archivePath); + yield* store.remove(runtimeFile).pipe(Effect.ignore); + state.runtime = runtimeFile.size; } state.verifying = false; yield* store.download(model.file, { @@ -376,7 +359,7 @@ const make = Effect.gen(function* () { ); if (remaining.length === 0) yield* fs - .remove(runtimeRoot, { recursive: true, force: true }) + .remove(runtimeDirectory, { recursive: true, force: true }) .pipe(Effect.mapError(installFailed)); }), ), @@ -400,12 +383,12 @@ const make = Effect.gen(function* () { request: SpeechSynthesisRequest, queue: Queue.Queue, ) { - if (!installs.length) return yield* failure("unavailable"); + if (!runtime || !libraryPath) return yield* failure("unavailable"); const definition = LOCAL_SYNTHESIS_MODELS.find( (model) => model.id === (request.model || LOCAL_SYNTHESIS_MODELS[0]!.id), ); if (!definition) return yield* failure("model-unavailable"); - if ((yield* missingRuntimes).length) return yield* failure("missing-model"); + if (!(yield* runtimeReady)) return yield* failure("missing-model"); const modelPath = yield* store.installedPath(definition.file); if (!modelPath) return yield* failure("missing-model"); // Held until the stream ends, after any cancelled synthesis has stopped. @@ -420,10 +403,8 @@ const make = Effect.gen(function* () { const loaded = yield* Effect.tryPromise({ try: () => loadLocalSynthesisModel({ - libraries: installs.map((install) => ({ - path: install.libraryPath, - backend: install.runtime.backend, - })), + libraryPath, + backend: runtime.backend, modelPath, threads: Math.max(1, Math.min(8, NodeOS.availableParallelism() - 1)), signal: lifetime.signal, diff --git a/apps/server/src/speech/localSynthesisWorker.ts b/apps/server/src/speech/localSynthesisWorker.ts index 34fb802fad43e..96b1dec1ea68b 100644 --- a/apps/server/src/speech/localSynthesisWorker.ts +++ b/apps/server/src/speech/localSynthesisWorker.ts @@ -41,19 +41,9 @@ const entry = ` const lamePath = packageJson("@breezystack/lamejs"); const lameEntry = join(dirname(lamePath), JSON.parse(readFileSync(lamePath, "utf8")).module); lame = await import(pathToFileURL(lameEntry).href); - // A Vulkan build will not load without the Vulkan loader, so fall back to the next build. - let failure; - for (const library of message.libraries) { - try { - model = bindAudioCpp(koffi, library.path).loadSpeechModel(message.modelPath, { - backend: library.backend, threads: message.threads, - }); - break; - } catch (error) { - failure ??= error; - } - } - if (!model) throw failure; + model = bindAudioCpp(koffi, message.libraryPath).loadSpeechModel(message.modelPath, { + backend: message.backend, threads: message.threads, + }); reply({ ok: true, backend: model.backend, languages: model.languages }); } else if (message.kind === "synthesize") { cancelled = false; @@ -111,8 +101,9 @@ export type LocalSynthesisModel = Awaited { @@ -43,24 +43,19 @@ it.each([ architecture: "arm64", libc: undefined, glibc: undefined, - backends: ["metal"], + backend: "metal", }, - { - platform: "win32", - architecture: "x64", - libc: undefined, - glibc: undefined, - backends: ["vulkan", "cpu"], - }, - { platform: "linux", architecture: "x64", libc: "gnu", glibc: "2.43", backends: ["vulkan"] }, + { platform: "darwin", architecture: "x64", libc: undefined, glibc: undefined, backend: "cpu" }, + { platform: "win32", architecture: "x64", libc: undefined, glibc: undefined, backend: "vulkan" }, + { platform: "linux", architecture: "x64", libc: "gnu", glibc: "2.28", backend: "vulkan" }, + { platform: "linux", architecture: "arm64", libc: "gnu", glibc: "2.39", backend: "vulkan" }, { platform: "linux", architecture: "x64", libc: "gnu", - glibc: "2.39", - error: "glibc 2.43 or newer", + glibc: "2.17", + error: "glibc 2.28 or newer", }, - { platform: "linux", architecture: "arm64", libc: "gnu", glibc: "2.43", error: "not available" }, { platform: "linux", architecture: "x64", @@ -68,11 +63,18 @@ it.each([ glibc: undefined, error: "not available", }, + { + platform: "win32", + architecture: "arm64", + libc: undefined, + glibc: undefined, + error: "not available", + }, ] as const)( - "installs the speech builds that load on $platform-$architecture with glibc $glibc", - ({ backends = [], error, ...host }) => { - const result = localSynthesisRuntimes(host); - expect(result.runtimes.map((runtime) => runtime.backend)).toEqual(backends); + "installs the speech build that loads on $platform-$architecture with glibc $glibc", + ({ backend, error, ...host }) => { + const result = localSynthesisRuntime(host); + expect(result.runtime?.backend).toBe(backend); if (error) expect(result.error).toContain(error); else expect(result.error).toBeUndefined(); }, diff --git a/docs/user/composer.md b/docs/user/composer.md index 868661f8b340b..06245ed75b1c6 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -208,9 +208,9 @@ voice, then use the preview to try it. **Local model** reads replies in English with Supertonic 3 on your selected environment, so the text never leaves it. Download it once from the same settings page (330–360 MB). -It uses the GPU through Metal on macOS and Vulkan on Windows and Linux. Without a GPU it runs on -the CPU and takes a few seconds longer to start speaking. Local models run on macOS, Windows x64, -and Linux x64 with glibc 2.43 or newer, such as Ubuntu 26.04. +It uses the GPU through Metal on Apple silicon Macs and Vulkan on Windows and Linux. Intel Macs and +machines without a GPU run it on the CPU, which takes a few seconds longer to start speaking. Local +models run on macOS, Windows x64, and Linux x64 or arm64 with glibc 2.28 or newer. On mobile, **Background playback** allows speech to continue while the app is in the background. diff --git a/packages/audio-cpp/src/index.ts b/packages/audio-cpp/src/index.ts index 1cfb726edb342..4b4865067f3ff 100644 --- a/packages/audio-cpp/src/index.ts +++ b/packages/audio-cpp/src/index.ts @@ -5,4 +5,4 @@ export { type AudioCppModel, type AudioCppSynthesisRequest, } from "./bindings.ts"; -export { AUDIO_CPP_VERSION, audioCppRuntimes, type AudioCppRuntime } from "./runtime.ts"; +export { AUDIO_CPP_VERSION, audioCppRuntime, type AudioCppRuntime } from "./runtime.ts"; diff --git a/packages/audio-cpp/src/runtime.ts b/packages/audio-cpp/src/runtime.ts index 688ec54636342..abc6e002b04ae 100644 --- a/packages/audio-cpp/src/runtime.ts +++ b/packages/audio-cpp/src/runtime.ts @@ -1,4 +1,5 @@ -export const AUDIO_CPP_VERSION = "v0.9.4"; +/** A release of github.com/pingdotgg/audio.cpp, whose `T3 release` workflow builds these libraries. */ +export const AUDIO_CPP_VERSION = "t3-2026.11.15"; export type AudioCppRuntime = { readonly filename: string; @@ -24,7 +25,7 @@ const runtime = ( const filename = `audio-${AUDIO_CPP_VERSION}-lib-${name}`; return { filename, - url: `https://github.com/0xShug0/audio.cpp/releases/download/${AUDIO_CPP_VERSION}/${filename}`, + url: `https://github.com/pingdotgg/audio.cpp/releases/download/${AUDIO_CPP_VERSION}/${filename}`, size, sha256, library, @@ -33,56 +34,47 @@ const runtime = ( }; }; -// Upstream publishes no Linux arm64 library. The portable Linux build loads Vulkan as a plugin and -// otherwise runs on the CPU. The Windows Vulkan build links vulkan-1.dll and fails to load without -// a GPU driver, so the CPU build is installed beside it as the fallback. -const RUNTIMES: Readonly> = { - "darwin-arm64": [ - runtime( - "macos-arm64-metal.tar.gz", - 14_422_864, - "bb1141185d15891d1c6b53f05cd55b0b93614804b340289799cff497fe87cf5b", - "libs/libaudiocpp.0.1.0.dylib", - "metal", - ), - ], - "darwin-x64": [ - runtime( - "macos-x64-metal.tar.gz", - 15_509_881, - "f0b6c392be9ca933ee2b813d036484c03a15838c55345e08472ec14251a64ad8", - "libs/libaudiocpp.0.1.0.dylib", - "metal", - ), - ], - "linux-x64": [ - runtime( - "ubuntu-x64-vulkan-portable.tar.gz", - 47_415_047, - "d5dfe390c78acadd153fdb6b8c448cca1ce2d1255fc7998d99ec3df0c29fddfb", - "libs/libaudiocpp.so.0.1.0", - "vulkan", - "2.43", - ), - ], - "win32-x64": [ - runtime( - "windows-x64-vulkan.zip", - 30_751_615, - "cf2fabd8630050491a92c002d7bdfd29eca722c31fb3b8cb0ba9b9c5e6e9ff3d", - "libs/audiocpp.dll", - "vulkan", - ), - runtime( - "windows-x64-cpu.zip", - 13_542_870, - "41f779687dc20e36900797f43d6762a9542c593931d4b3f3f5e877b0db9baa5e", - "libs/audiocpp.dll", - "cpu", - ), - ], +// Linux and Windows load Vulkan as a plugin and otherwise run on the CPU. Intel Macs build +// without Metal, as upstream's do. +const RUNTIMES: Readonly> = { + "darwin-arm64": runtime( + "macos-arm64-metal.tar.gz", + 15_050_502, + "d310a03ec334c9eca108afddc155285d415c4a9de7de6f1f11852792dea4ef40", + "libs/libaudiocpp.0.1.0.dylib", + "metal", + ), + "darwin-x64": runtime( + "macos-x64-cpu.tar.gz", + 16_205_264, + "e28f38d904ca2f62582e30b66daf223a102c49d72dfc4de6652ebc49d560b497", + "libs/libaudiocpp.0.1.0.dylib", + "cpu", + ), + "linux-x64": runtime( + "linux-x64-vulkan.tar.gz", + 46_480_833, + "bfb156d9803a9d72321edf2618132f5c253d62774d87b8a84404c908bcb14c8d", + "libs/libaudiocpp.so.0.1.0", + "vulkan", + "2.28", + ), + "linux-arm64": runtime( + "linux-arm64-vulkan.tar.gz", + 40_185_095, + "5dcf0ca69930cb326228379d21c357a9474e5fb414b7fbbdbad8d59dc6be9eb8", + "libs/libaudiocpp.so.0.1.0", + "vulkan", + "2.28", + ), + "win32-x64": runtime( + "windows-x64-vulkan.zip", + 34_389_751, + "80c98ef7ccb2ebdb343838727cfce20cceefbf35eeeda6a0ffae4a344f06a613", + "libs/audiocpp.dll", + "vulkan", + ), }; -/** All builds a host installs, in preference order: the first that loads is used. */ -export const audioCppRuntimes = (platform: string, architecture: string) => - RUNTIMES[`${platform}-${architecture}`] ?? []; +export const audioCppRuntime = (platform: string, architecture: string) => + RUNTIMES[`${platform}-${architecture}`]; From aaf838b1229ea8a31186e0fbafa202e121ae7750 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 15 Nov 2026 18:37:26 -0600 Subject: [PATCH 21/33] fix(read-aloud): a request waiting for the local model can be cancelled Co-authored-by: Cursor --- apps/server/src/speech/LocalSpeechSynthesis.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 01e0639909abe..1b3148dc6831b 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -392,10 +392,14 @@ const make = Effect.gen(function* () { const modelPath = yield* store.installedPath(definition.file); if (!modelPath) return yield* failure("missing-model"); // Held until the stream ends, after any cancelled synthesis has stopped. - yield* Effect.acquireRelease(Semaphore.take(permit, 1), () => - Semaphore.release(permit, 1).pipe( - Effect.andThen(Effect.sync(() => Queue.offerUnsafe(idleDeadlines, undefined))), - ), + // Interruptible, so a request abandoned while waiting stops waiting. + yield* Effect.acquireRelease( + Semaphore.take(permit, 1), + () => + Semaphore.release(permit, 1).pipe( + Effect.andThen(Effect.sync(() => Queue.offerUnsafe(idleDeadlines, undefined))), + ), + { interruptible: true }, ); if (!worker?.model.alive || worker.modelId !== definition.id) { yield* unloadWorker; From c1d3407b0012f62d770017129b92cd1167a7227b Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 16 Nov 2026 02:35:11 -0600 Subject: [PATCH 22/33] feat(server): run local speech models on Windows arm64 Co-authored-by: Cursor --- .../server/src/speech/LocalSpeechSynthesis.ts | 9 +++--- apps/server/src/speech/synthesis.test.ts | 9 +++++- docs/user/composer.md | 2 +- packages/audio-cpp/src/runtime.ts | 29 ++++++++++++------- 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 1b3148dc6831b..b807c7c26ae8d 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -24,7 +24,6 @@ import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ServerConfig from "../config.ts"; -import { isSpeechPlatformSupported } from "./platform.ts"; import * as SpeechModelStore from "./SpeechModelStore.ts"; import { loadLocalSynthesisModel, type LocalSynthesisModel } from "./localSynthesisWorker.ts"; @@ -104,9 +103,11 @@ export function localSynthesisRuntime(host: { readonly libc: "gnu" | "musl" | undefined; readonly glibc: string | undefined; }): { readonly runtime?: AudioCppRuntime; readonly error?: string } { - const runtime = isSpeechPlatformSupported(host.platform, host.architecture, host.libc) - ? audioCppRuntime(host.platform, host.architecture) - : undefined; + // Independent of dictation's platform list: the speech builds cover hosts transcribe-cpp does not. + const runtime = + host.platform !== "linux" || host.libc === "gnu" + ? audioCppRuntime(host.platform, host.architecture) + : undefined; if (!runtime) return { error: `Local speech models are not available on ${host.platform}-${host.architecture}.`, diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index 90978bc320599..c6f43b4660df3 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -63,12 +63,19 @@ it.each([ glibc: undefined, error: "not available", }, + { + platform: "freebsd", + architecture: "x64", + libc: undefined, + glibc: undefined, + error: "not available", + }, { platform: "win32", architecture: "arm64", libc: undefined, glibc: undefined, - error: "not available", + backend: "vulkan", }, ] as const)( "installs the speech build that loads on $platform-$architecture with glibc $glibc", diff --git a/docs/user/composer.md b/docs/user/composer.md index 06245ed75b1c6..8297e4bbf43ca 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -210,7 +210,7 @@ voice, then use the preview to try it. so the text never leaves it. Download it once from the same settings page (330–360 MB). It uses the GPU through Metal on Apple silicon Macs and Vulkan on Windows and Linux. Intel Macs and machines without a GPU run it on the CPU, which takes a few seconds longer to start speaking. Local -models run on macOS, Windows x64, and Linux x64 or arm64 with glibc 2.28 or newer. +models run on macOS, Windows, and Linux with glibc 2.28 or newer. On mobile, **Background playback** allows speech to continue while the app is in the background. diff --git a/packages/audio-cpp/src/runtime.ts b/packages/audio-cpp/src/runtime.ts index abc6e002b04ae..fa3aaca3fa0d2 100644 --- a/packages/audio-cpp/src/runtime.ts +++ b/packages/audio-cpp/src/runtime.ts @@ -1,5 +1,5 @@ /** A release of github.com/pingdotgg/audio.cpp, whose `T3 release` workflow builds these libraries. */ -export const AUDIO_CPP_VERSION = "t3-2026.11.15"; +export const AUDIO_CPP_VERSION = "t3-2026.11.16"; export type AudioCppRuntime = { readonly filename: string; @@ -39,38 +39,45 @@ const runtime = ( const RUNTIMES: Readonly> = { "darwin-arm64": runtime( "macos-arm64-metal.tar.gz", - 15_050_502, - "d310a03ec334c9eca108afddc155285d415c4a9de7de6f1f11852792dea4ef40", + 15_050_495, + "81ee4b878e26c8c7b3eb12f6c50c94e2db3e77916e2eadb180957e97838271e2", "libs/libaudiocpp.0.1.0.dylib", "metal", ), "darwin-x64": runtime( "macos-x64-cpu.tar.gz", - 16_205_264, - "e28f38d904ca2f62582e30b66daf223a102c49d72dfc4de6652ebc49d560b497", + 16_205_261, + "94465d3a325d776198821f7216a52caa6db1f4f11fb20b5490f2789f7e7e54a6", "libs/libaudiocpp.0.1.0.dylib", "cpu", ), "linux-x64": runtime( "linux-x64-vulkan.tar.gz", - 46_480_833, - "bfb156d9803a9d72321edf2618132f5c253d62774d87b8a84404c908bcb14c8d", + 46_480_819, + "d6774bc02102fa554db246e2dbf30c452cbec7dfe7d33844b89c399d758d8d01", "libs/libaudiocpp.so.0.1.0", "vulkan", "2.28", ), "linux-arm64": runtime( "linux-arm64-vulkan.tar.gz", - 40_185_095, - "5dcf0ca69930cb326228379d21c357a9474e5fb414b7fbbdbad8d59dc6be9eb8", + 40_185_132, + "6b03aebe87eb85f433faf3a0cd4e54ed7d45dde2654cf98ae8ac0eebfa2163a3", "libs/libaudiocpp.so.0.1.0", "vulkan", "2.28", ), + "win32-arm64": runtime( + "windows-arm64-vulkan.zip", + 34_518_475, + "576729077a80984c24a5b54c5ca237b388e5d0d8b90b394f8463314fd38b1bfc", + "libs/audiocpp.dll", + "vulkan", + ), "win32-x64": runtime( "windows-x64-vulkan.zip", - 34_389_751, - "80c98ef7ccb2ebdb343838727cfce20cceefbf35eeeda6a0ffae4a344f06a613", + 34_389_747, + "91780513f8c374e4736c27850a988f4205526488388698e24eaa322682c16471", "libs/audiocpp.dll", "vulkan", ), From 5c531511f6c10e7063792bc2dedc9301d0ae0859 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 09:11:27 -0600 Subject: [PATCH 23/33] fix(server): local and PCM read-aloud audio is no longer near-silent lamejs resamples 44.1 and 48 kHz input to 32 kHz at 48 kbps, and its resampler turns speech into near-silence. Encode at the lowest bitrate that keeps the input rate instead. Co-authored-by: Cursor --- apps/server/src/speech/localSynthesisWorker.ts | 7 ++++--- apps/server/src/speech/synthesis.test.ts | 18 ++++++++++++++---- apps/server/src/speech/synthesisAudio.ts | 12 +++++++++--- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/apps/server/src/speech/localSynthesisWorker.ts b/apps/server/src/speech/localSynthesisWorker.ts index 96b1dec1ea68b..fbeeca694f235 100644 --- a/apps/server/src/speech/localSynthesisWorker.ts +++ b/apps/server/src/speech/localSynthesisWorker.ts @@ -2,7 +2,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeSea from "node:sea"; import { bindAudioCpp, type AudioCppSynthesisRequest } from "@t3tools/audio-cpp"; -import { ENCODE_SLICE_SAMPLES, MP3_KBPS, pcm16Mono } from "./synthesisAudio.ts"; +import { ENCODE_SLICE_SAMPLES, mp3Kbps, pcm16Mono } from "./synthesisAudio.ts"; // Inlined like the dictation worker, so packaged builds need no separate worker artifact. const entry = ` @@ -12,6 +12,7 @@ const entry = ` const { pathToFileURL } = await import("node:url"); const bindAudioCpp = ${bindAudioCpp.toString()}; const pcm16Mono = ${pcm16Mono.toString()}; + const mp3Kbps = ${mp3Kbps.toString()}; const packageJson = (name) => { const path = findPackageJSON(name, baseUrl); if (!path) throw new Error("The " + name + " package is unavailable."); @@ -53,7 +54,7 @@ const entry = ` while (!cancelled) { const audio = stream.next(); if (!audio) break; - encoder ??= new lame.Mp3Encoder(1, audio.sampleRate, message.kbps); + encoder ??= new lame.Mp3Encoder(1, audio.sampleRate, mp3Kbps(audio.sampleRate)); const pcm = pcm16Mono(audio.samples, audio.channels); // Encoding a text chunk takes longer than synthesizing it, so send it slice by slice. for (let start = 0; start < pcm.length && !cancelled; start += ${ENCODE_SLICE_SAMPLES}) { @@ -193,7 +194,7 @@ export async function loadLocalSynthesisModel(options: { stream: async (request: AudioCppSynthesisRequest, onAudio: (bytes: Uint8Array) => void) => { receive = onAudio; try { - await send({ kind: "synthesize", request, kbps: MP3_KBPS }); + await send({ kind: "synthesize", request }); } finally { receive = undefined; } diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index c6f43b4660df3..4ba0d2d541bbc 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -12,7 +12,7 @@ import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretReso import * as ServerSettings from "../serverSettings.ts"; import * as CloudSpeech from "./CloudSpeech.ts"; import { localSynthesisLanguage, localSynthesisRuntime } from "./LocalSpeechSynthesis.ts"; -import { pcm16Mono } from "./synthesisAudio.ts"; +import { encodeMp3, pcm16Mono } from "./synthesisAudio.ts"; it("encodes model samples as clipped mono 16-bit PCM", () => { const pcm = pcm16Mono(Float32Array.of(0, 1, -1, 2, -2, Number.NaN, 0.5), 1); @@ -21,13 +21,23 @@ it("encodes model samples as clipped mono 16-bit PCM", () => { }); // An MPEG audio frame header's version bits and sample-rate index give the encoded rate. -// At 48 kbps, LAME keeps 24 kHz input and resamples 44.1 kHz input to 32 kHz. function mp3SampleRate(bytes: Uint8Array) { expect(bytes[0]).toBe(0xff); const rates = { 0: [11025, 12000, 8000], 2: [22050, 24000, 16000], 3: [44100, 48000, 32000] }; return rates[((bytes[1]! >> 3) & 3) as 0 | 2 | 3][(bytes[2]! >> 2) & 3]; } +// lamejs's resampler turns speech into near-silence, so the encoded rate must match the input. +it.effect.each([8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000])( + "encodes %i Hz speech without resampling it", + (rate) => + Effect.gen(function* () { + const pcm = new Uint8Array(rate * 2); + const [first] = yield* Stream.runCollect(Stream.take(encodeMp3(pcm, rate), 1)); + expect(mp3SampleRate(first!)).toBe(rate); + }), +); + it.each([ ["en-US", "en"], ["PT", "pt"], @@ -167,7 +177,7 @@ it.effect.each(["openai", "xai", "openrouter"] as const)( upstream.mockClear(); } const result = yield* synthesize(provider, request); - if (provider === "openrouter") expect(mp3SampleRate(result)).toBe(32000); + if (provider === "openrouter") expect(mp3SampleRate(result)).toBe(44100); else expect([...result]).toEqual([73, 68, 51, 1]); const [url, init] = upstream.mock.calls[0]!; expect(String(url)).toBe( @@ -230,7 +240,7 @@ it.effect.each(["openai", "xai", "openrouter"] as const)( expect(JSON.parse(String(upstream.mock.calls.at(-1)?.[1]?.body)).voice).toBe("reader"); for (const [model, expectedRate] of [ ["google/gemini-tts", 24000], - ["heygen/heygen-voice-1", 32000], + ["heygen/heygen-voice-1", 44100], ] as const) { upstream.mockResolvedValueOnce( new Response(Uint8Array.of(0, 1), { headers: { "content-type": "audio/pcm" } }), diff --git a/apps/server/src/speech/synthesisAudio.ts b/apps/server/src/speech/synthesisAudio.ts index 9bb9d040efab7..9dd6fa5022856 100644 --- a/apps/server/src/speech/synthesisAudio.ts +++ b/apps/server/src/speech/synthesisAudio.ts @@ -3,8 +3,14 @@ import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; export const MAX_SYNTHESIS_BYTES = 32 * 1024 * 1024; -/** Mono speech stays intelligible here at a tenth of 16-bit PCM's size. */ -export const MP3_KBPS = 48; + +/** + * The lowest bitrate at which LAME keeps the input rate: lamejs's resampler turns speech into + * near-silence. Self-contained so the synthesis worker can inline it with `toString()`. + */ +export function mp3Kbps(sampleRate: number) { + return sampleRate > 32000 ? 64 : 48; +} const MP3_SAMPLE_RATES = [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000]; // About half a second at 44.1 kHz, which encodes in about 15 ms. export const ENCODE_SLICE_SAMPLES = 1152 * 20; @@ -44,7 +50,7 @@ export function encodeMp3( for (let index = 0; index < samples.length; index++) samples[index] = view.getInt16(index * 2, true) / 0x8000; const mono = pcm16Mono(samples, channels); - const encoder = new Mp3Encoder(1, rate, MP3_KBPS); + const encoder = new Mp3Encoder(1, rate, mp3Kbps(rate)); const slices = Math.ceil(mono.length / ENCODE_SLICE_SAMPLES); return Stream.range(0, slices - 1).pipe( Stream.mapEffect((slice) => From ad99a8391f2b82cfa1c0bd550d2f3390ec1ac650 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 09:11:27 -0600 Subject: [PATCH 24/33] feat(read-aloud): use a local speech model file already on the environment Matches dictation: paste a model file or folder path and choose Use existing to link it instead of downloading. The download size now counts only the missing files, and installing a new runtime removes earlier releases' copies. Co-authored-by: Cursor --- .../src/speech/LocalSpeechSynthesis.test.ts | 67 ++++++++- .../server/src/speech/LocalSpeechSynthesis.ts | 128 ++++++++++++------ apps/server/src/speech/http.test.ts | 59 +++++--- apps/server/src/speech/http.ts | 41 +++++- .../settings/ReadAloudSettingsSection.tsx | 62 ++++++++- docs/user/composer.md | 3 +- .../src/voice-input/environment.ts | 11 ++ .../client-runtime/src/voice-input/index.ts | 1 + packages/contracts/src/environmentHttp.ts | 8 ++ packages/contracts/src/readAloud.ts | 2 + 10 files changed, 310 insertions(+), 72 deletions(-) diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts index 22b2bddaa4d83..548f9ecf76f83 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.test.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -1,6 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { AUDIO_CPP_VERSION } from "@t3tools/audio-cpp"; +import { AUDIO_CPP_VERSION, audioCppRuntime } from "@t3tools/audio-cpp"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; @@ -14,12 +14,13 @@ import * as ServerConfig from "../config.ts"; import * as LocalSpeechSynthesis from "./LocalSpeechSynthesis.ts"; import * as SpeechModelStore from "./SpeechModelStore.ts"; -/** Runs `body` against the service with an extracted runtime, so installs download only the model. */ +/** Runs `body` against the service, with an extracted runtime unless `runtime` is false. */ const withService = ( store: Partial, body: ( service: LocalSpeechSynthesis.LocalSpeechSynthesis["Service"], ) => Effect.Effect, + options: { readonly runtime?: boolean } = {}, ) => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -31,9 +32,11 @@ const withService = ( "runtime", `audio-cpp-${AUDIO_CPP_VERSION}-darwin-arm64`, ); - yield* fs.makeDirectory(path.join(runtime, "libs"), { recursive: true }); - yield* fs.writeFileString(path.join(runtime, ".t3-complete"), AUDIO_CPP_VERSION); - yield* fs.writeFileString(path.join(runtime, "libs", "libaudiocpp.0.1.0.dylib"), ""); + if (options.runtime !== false) { + yield* fs.makeDirectory(path.join(runtime, "libs"), { recursive: true }); + yield* fs.writeFileString(path.join(runtime, ".t3-complete"), AUDIO_CPP_VERSION); + yield* fs.writeFileString(path.join(runtime, "libs", "libaudiocpp.0.1.0.dylib"), ""); + } return yield* body(yield* LocalSpeechSynthesis.LocalSpeechSynthesis); }).pipe( Effect.provide( @@ -41,6 +44,7 @@ const withService = ( Layer.provide( Layer.mock(SpeechModelStore.SpeechModelStore)({ isReady: () => Effect.succeed(false), + linkedFrom: () => Effect.undefined, ...store, }), ), @@ -53,6 +57,52 @@ const withService = ( Effect.provideService(HostProcess.Architecture, "arm64"), ); +it.effect("counts only the files an install still needs in its download size", () => + withService( + { isReady: (file) => Effect.succeed(file.id !== "pingdotgg/audio.cpp") }, + (service) => + Effect.gen(function* () { + const { models } = yield* service.catalog; + expect(models[0]?.install).toEqual({ + state: "downloadable", + size: audioCppRuntime("darwin", "arm64")!.size, + }); + }), + { runtime: false }, + ), +); + +it.effect("links a model file already on this machine instead of downloading it", () => + Effect.gen(function* () { + let linked = false; + const download = vi.fn(() => Effect.succeed("/unused")); + yield* withService( + { + download, + link: (models, source) => + Effect.sync(() => { + linked = source === "~/models"; + return linked ? models.map((model) => model.id) : []; + }), + isReady: () => Effect.sync(() => linked), + linkedFrom: () => Effect.sync(() => (linked ? "/Users/me/models/model.gguf" : undefined)), + }, + (service) => + Effect.gen(function* () { + expect(yield* Effect.flip(service.link("~/elsewhere"))).toMatchObject({ + reason: "not-found", + }); + const { models } = yield* service.link("~/models"); + expect(models[0]?.install).toMatchObject({ + state: "installed", + linkedFrom: "/Users/me/models/model.gguf", + }); + expect(download).not.toHaveBeenCalled(); + }), + ); + }), +); + it.effect("joins a second download of the same model instead of starting another install", () => Effect.gen(function* () { const started = yield* Deferred.make(); @@ -77,14 +127,17 @@ it.effect("joins a second download of the same model instead of starting another }), ); -it.effect("refuses a download while a removal deletes the shared runtime", () => +it.effect("refuses a download or link while a removal deletes the shared runtime", () => Effect.gen(function* () { const removing = yield* Deferred.make(); const release = yield* Deferred.make(); const download = vi.fn(() => Effect.succeed("/unused")); + const linked = vi.fn(); + const link = () => Effect.sync(() => (linked(), [])); yield* withService( { download, + link, remove: () => Deferred.succeed(removing, undefined).pipe(Effect.andThen(Deferred.await(release))), }, @@ -95,9 +148,11 @@ it.effect("refuses a download while a removal deletes the shared runtime", () => expect(yield* Effect.flip(service.download("supertonic-3"))).toMatchObject({ reason: "busy", }); + expect(yield* Effect.flip(service.link("~/models"))).toMatchObject({ reason: "busy" }); yield* Deferred.succeed(release, undefined); yield* Fiber.join(removal); expect(download).not.toHaveBeenCalled(); + expect(linked).not.toHaveBeenCalled(); }), ); }), diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index b807c7c26ae8d..289f84ffcb1de 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -56,7 +56,13 @@ const IDLE_UNLOAD_MS = 10 * 60_000; export class LocalSynthesisInstallError extends Schema.TaggedError()( "LocalSynthesisInstallError", { - reason: Schema.Literals(["unknown-model", "unsupported-platform", "busy", "failed"]), + reason: Schema.Literals([ + "unknown-model", + "unsupported-platform", + "busy", + "not-found", + "failed", + ]), cause: Schema.optionalKey(Schema.Defect()), }, ) {} @@ -70,6 +76,10 @@ export class LocalSpeechSynthesis extends Context.Service< modelId: string, ) => Effect.Effect; readonly cancel: (modelId: string) => Effect.Effect; + /** Uses model files already on this machine, from a file or a folder to search. */ + readonly link: ( + source: string, + ) => Effect.Effect; /** Removes the model, and the shared runtime once no installed model needs it. */ readonly remove: ( modelId: string, @@ -182,6 +192,17 @@ const make = Effect.gen(function* () { yield* fs.writeFileString(path.join(staging, ".t3-complete"), AUDIO_CPP_VERSION); yield* fs.remove(runtimeDirectory, { recursive: true, force: true }); yield* fs.rename(staging, runtimeDirectory); + // Runtimes from earlier releases for this platform; nothing loads them again. + const parent = path.dirname(runtimeDirectory); + for (const name of yield* fs.readDirectory(parent).pipe(Effect.orElseSucceed(() => []))) { + const entry = path.join(parent, name); + if ( + entry !== runtimeDirectory && + name.startsWith("audio-cpp-") && + name.endsWith(`-${platform}-${architecture}`) + ) + yield* fs.remove(entry, { recursive: true, force: true }).pipe(Effect.ignore); + } }).pipe( Effect.scoped, Effect.onExit((exit) => @@ -194,7 +215,7 @@ const make = Effect.gen(function* () { type Transfer = { readonly modelId: string; - /** Fixed once the install knows whether it needs the runtime, so extracting it does not shrink it. */ + /** Fixed once the install knows which files it needs, so finishing one does not shrink it. */ size: number; runtime: number; model: number; @@ -202,8 +223,9 @@ const make = Effect.gen(function* () { fiber?: Fiber.Fiber; }; let transfer: Transfer | undefined; - // A removal deletes the shared runtime, so it and an install must not overlap. - let removing = false; + // A removal deletes the shared runtime and a link replaces model files, so neither may + // overlap an install or each other. + let changing = false; const catalog = Effect.gen(function* () { const ready = yield* runtimeReady; @@ -211,20 +233,24 @@ const make = Effect.gen(function* () { const models = yield* Effect.forEach(LOCAL_SYNTHESIS_MODELS, (model) => Effect.gen(function* () { const active = transfer?.modelId === model.id ? transfer : undefined; - const size = active?.size ?? model.file.size + runtimeSize; + const modelReady = yield* store.isReady(model.file); + const linkedFrom = ready && modelReady ? yield* store.linkedFrom(model.file) : undefined; const install = active ? { state: active.verifying ? ("verifying" as const) : ("downloading" as const), - size, + size: active.size, downloaded: active.runtime + active.model, } - : { - state: - ready && (yield* store.isReady(model.file)) - ? ("installed" as const) - : ("downloadable" as const), - size, - }; + : ready && modelReady + ? { + state: "installed" as const, + size: model.file.size, + ...(linkedFrom && { linkedFrom }), + } + : { + state: "downloadable" as const, + size: (modelReady ? 0 : model.file.size) + runtimeSize, + }; return { id: model.id, name: model.name, voices: model.voices, install }; }), ); @@ -252,7 +278,7 @@ const make = Effect.gen(function* () { if (!runtimeFile || !runtime) return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); // Checked and claimed without yielding, so a concurrent download or removal cannot interleave. - if (removing || (transfer && transfer.modelId !== modelId)) + if (changing || (transfer && transfer.modelId !== modelId)) return yield* new LocalSynthesisInstallError({ reason: "busy" }); if (!transfer) { const state: Transfer = { @@ -264,9 +290,12 @@ const make = Effect.gen(function* () { }; transfer = state; const install = Effect.gen(function* () { - // Read after claiming: no removal can start while this transfer exists. - if (!(yield* runtimeReady)) { - state.size += runtimeFile.size; + // Read after claiming: no removal or link can start while this transfer exists. + const needsRuntime = !(yield* runtimeReady); + state.size = + (needsRuntime ? runtimeFile.size : 0) + + ((yield* store.isReady(model.file)) ? 0 : model.file.size); + if (needsRuntime) { const archivePath = yield* store.download(runtimeFile, { onProgress: (downloaded) => { state.runtime = downloaded; @@ -342,33 +371,56 @@ const make = Effect.gen(function* () { Effect.forkScoped, ); - const remove = Effect.fn("LocalSpeechSynthesis.remove")(function* (modelId: string) { - const model = yield* findModel(modelId); - yield* Effect.acquireUseRelease( + // Claimed without yielding, so a download, removal, or link cannot interleave. + const exclusive = (effect: Effect.Effect) => + Effect.acquireUseRelease( Effect.suspend(() => { - if (transfer || removing) return new LocalSynthesisInstallError({ reason: "busy" }); - removing = true; + if (transfer || changing) return new LocalSynthesisInstallError({ reason: "busy" }); + changing = true; return Effect.void; }), - () => - permit.withPermits(1)( - Effect.gen(function* () { - if (worker?.modelId === modelId) yield* unloadWorker; - yield* store.remove(model.file).pipe(Effect.mapError(installFailed)); - const remaining = yield* Effect.filter(LOCAL_SYNTHESIS_MODELS, (entry) => - store.isReady(entry.file), - ); - if (remaining.length === 0) - yield* fs - .remove(runtimeDirectory, { recursive: true, force: true }) - .pipe(Effect.mapError(installFailed)); - }), - ), + () => effect, () => Effect.sync(() => { - removing = false; + changing = false; }), ); + + const link = Effect.fn("LocalSpeechSynthesis.link")(function* (source: string) { + if (!runtimeFile) + return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); + const linked = yield* exclusive( + store + .link( + LOCAL_SYNTHESIS_MODELS.map((model) => model.file), + source, + ) + .pipe(Effect.mapError(installFailed)), + ); + const model = LOCAL_SYNTHESIS_MODELS.find((entry) => linked.includes(entry.file.id)); + if (!model) return yield* new LocalSynthesisInstallError({ reason: "not-found" }); + // The model is in place; an install now fetches only the runtime. + if (!(yield* runtimeReady)) return yield* download(model.id); + return yield* catalog; + }); + + const remove = Effect.fn("LocalSpeechSynthesis.remove")(function* (modelId: string) { + const model = yield* findModel(modelId); + yield* exclusive( + permit.withPermits(1)( + Effect.gen(function* () { + if (worker?.modelId === modelId) yield* unloadWorker; + yield* store.remove(model.file).pipe(Effect.mapError(installFailed)); + const remaining = yield* Effect.filter(LOCAL_SYNTHESIS_MODELS, (entry) => + store.isReady(entry.file), + ); + if (remaining.length === 0) + yield* fs + .remove(runtimeDirectory, { recursive: true, force: true }) + .pipe(Effect.mapError(installFailed)); + }), + ), + ); return yield* catalog; }); @@ -464,7 +516,7 @@ const make = Effect.gen(function* () { Stream.withSpan("LocalSpeechSynthesis.stream"), ); - return LocalSpeechSynthesis.of({ catalog, download, cancel, remove, stream }); + return LocalSpeechSynthesis.of({ catalog, download, cancel, link, remove, stream }); }); export const layer = Layer.effect(LocalSpeechSynthesis, make); diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 4efdcd314c099..bf888ac640d35 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -261,10 +261,32 @@ effectIt.effect( return Effect.fail(new CloudSpeechError({ provider, reason: "rejected-key" })); }, }); + const linkSynthesis = vi.fn(); + const local = Layer.mock(LocalSpeechSynthesis.LocalSpeechSynthesis)({ + catalog: Effect.succeed({ + ...EMPTY_SPEECH_SYNTHESIS_CATALOG, + models: [ + { + id: "fixture-voice", + name: "Fixture voice", + voices: [], + install: { + state: "installed", + size: 1, + linkedFrom: "/home/someone/models/voice.gguf", + }, + }, + ], + }), + link: (source) => { + linkSynthesis(source); + return Effect.succeed(EMPTY_SPEECH_SYNTHESIS_CATALOG); + }, + }); const { handler, dispose } = HttpRouter.toWebHandler( HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( Layer.provide(speechHttpApiLayer), - Layer.provide(Layer.mock(LocalSpeechSynthesis.LocalSpeechSynthesis)({})), + Layer.provide(local), Layer.provide(principal(AuthOrchestrationOperateScope, AuthSettingsWriteScope)), Layer.provide( Layer.mock(SpeechService.SpeechService)({ @@ -355,21 +377,26 @@ effectIt.effect( ); expect(transcribe).toHaveBeenLastCalledWith("openrouter", "acme/transcribe-1"); // Naming a path on the environment needs filesystem access, not only settings access. - const link = yield* Effect.promise(() => - handler( - new Request("http://localhost/api/voice/models/link", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ path: "/models" }), - }), - context, - ), - ); - expect(link.status).toBe(403); - const listed = yield* Effect.promise(() => - handler(new Request("http://localhost/api/voice/models"), context), - ); - expect(yield* Effect.promise(() => listed.text())).not.toContain("/home/someone"); + for (const path of ["models/link", "synthesis/local/models/link"]) { + const link = yield* Effect.promise(() => + handler( + new Request(`http://localhost/api/voice/${path}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ path: "/models" }), + }), + context, + ), + ); + expect(link.status).toBe(403); + } + expect(linkSynthesis).not.toHaveBeenCalled(); + for (const path of ["models", "synthesis/local/models"]) { + const listed = yield* Effect.promise(() => + handler(new Request(`http://localhost/api/voice/${path}`), context), + ); + expect(yield* Effect.promise(() => listed.text())).not.toContain("/home/someone"); + } }), ); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 2bf15a83485a5..6a096f2e95413 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -8,6 +8,7 @@ import { EnvironmentAuthenticatedPrincipal, EnvironmentHttpApi, type EnvironmentSpeechModels, + type SpeechSynthesisCatalog, EnvironmentVoiceBodyLimit, SPEECH_MAX_OPTIONS_BYTES, } from "@t3tools/contracts"; @@ -67,6 +68,20 @@ const withoutHostPaths = Effect.fnUntraced(function* (result: EnvironmentSpeechM return { models: result.models.map(({ linkedFrom: _, ...model }) => model) }; }); +// Untraced: it runs inside each handler's own span. +const withoutCatalogHostPaths = Effect.fnUntraced(function* (catalog: SpeechSynthesisCatalog) { + const session = yield* EnvironmentAuthenticatedPrincipal; + if (session.scopes.has(AuthFilesystemReadScope)) return catalog; + return { + ...catalog, + models: catalog.models.map(({ install, ...model }) => { + if (!install) return model; + const { linkedFrom: _, ...visible } = install; + return { ...model, install: visible }; + }), + }; +}); + export const speechHttpApiLayer = HttpApiBuilder.group( EnvironmentHttpApi, "voice", @@ -85,7 +100,7 @@ export const speechHttpApiLayer = HttpApiBuilder.group( if (error.reason === "failed") return yield* failEnvironmentInternal("internal_error", error); return yield* failEnvironmentInvalidRequest( - error.reason === "unknown-model" + error.reason === "unknown-model" || error.reason === "not-found" ? "invalid_command" : error.reason === "busy" ? "speech_busy" @@ -107,7 +122,8 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "synthesisModels", Effect.fn("environment.voice.synthesisModels")(function* (args) { yield* guard(args.endpoint.name); - if (args.params.provider === "local") return yield* local.catalog; + if (args.params.provider === "local") + return yield* local.catalog.pipe(Effect.flatMap(withoutCatalogHostPaths)); return yield* cloud.synthesisModels(args.params.provider).pipe( Effect.catchTags({ SpeechSynthesisError: (error) => @@ -139,21 +155,36 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "downloadSynthesisModel", Effect.fn("environment.voice.downloadSynthesisModel")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* local.download(args.payload.modelId).pipe(mapInstallError); + return yield* local + .download(args.payload.modelId) + .pipe(mapInstallError, Effect.flatMap(withoutCatalogHostPaths)); }), ) .handle( "cancelSynthesisModel", Effect.fn("environment.voice.cancelSynthesisModel")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* local.cancel(args.payload.modelId); + return yield* local + .cancel(args.payload.modelId) + .pipe(Effect.flatMap(withoutCatalogHostPaths)); }), ) .handle( "removeSynthesisModel", Effect.fn("environment.voice.removeSynthesisModel")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* local.remove(args.payload.modelId).pipe(mapInstallError); + return yield* local + .remove(args.payload.modelId) + .pipe(mapInstallError, Effect.flatMap(withoutCatalogHostPaths)); + }), + ) + .handle( + "linkSynthesisModels", + Effect.fn("environment.voice.linkSynthesisModels")(function* (args) { + yield* guard(args.endpoint.name, AuthSettingsWriteScope); + // The request names a path on this machine and the result reveals what is there. + yield* requireEnvironmentScope(AuthFilesystemReadScope); + return yield* local.link(args.payload.path).pipe(mapInstallError); }), ) .handle( diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index c1a0563baac55..9b4e02cf4b8e8 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -5,11 +5,13 @@ import { downloadSpeechSynthesisModel, getCloudSpeechKeys, getSpeechSynthesisModels, + linkSpeechSynthesisModels, removeSpeechSynthesisModel, setCloudSpeechKey, } from "@t3tools/client-runtime/voice-input"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { + AuthFilesystemReadScope, AuthSettingsWriteScope, READ_ALOUD_LABELS, EMPTY_SPEECH_SYNTHESIS_CATALOG, @@ -136,8 +138,10 @@ function LocalSpeechModel({ onChanged: () => void; }) { const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); + const canReadFiles = useEnvironmentScope(prepared.environmentId, AuthFilesystemReadScope); const [requesting, setRequesting] = useState(false); const [error, setError] = useState(""); + const [existingPath, setExistingPath] = useState(""); const install = model.install; const downloading = install?.state === "downloading" || install?.state === "verifying"; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Poll the environment's download progress while it runs. @@ -147,7 +151,7 @@ function LocalSpeechModel({ return () => window.clearTimeout(timer); }, [downloading, requesting, refreshing, onChanged]); if (!install) return null; - const run = async (action: "download" | "cancel" | "remove") => { + const run = async (action: "download" | "cancel" | "remove" | "link") => { setRequesting(true); setError(""); try { @@ -156,19 +160,27 @@ function LocalSpeechModel({ ? downloadSpeechSynthesisModel(prepared, model.id) : action === "cancel" ? cancelSpeechSynthesisModelDownload(prepared, model.id) - : removeSpeechSynthesisModel(prepared, model.id), + : action === "link" + ? linkSpeechSynthesisModels(prepared, existingPath) + : removeSpeechSynthesisModel(prepared, model.id), ); + if (action === "link") setExistingPath(""); } catch { setError( action === "download" ? "Could not download the model. Check the environment's connection and disk space." - : "Could not change the model. Try again.", + : action === "link" + ? `No ${model.name} file was found at that path.` + : "Could not change the model. Try again.", ); } setRequesting(false); onChanged(); }; - const progress = install.downloaded === undefined ? 0 : (install.downloaded / install.size) * 100; + const progress = + install.downloaded === undefined || install.size === 0 + ? 0 + : Math.min(100, (install.downloaded / install.size) * 100); return ( + Using your file at {install.linkedFrom} + + )} {downloading && ( void run("remove")} > - Remove + {install.linkedFrom ? "Stop using" : "Remove"} ) : ( + + )} + ); } diff --git a/docs/user/composer.md b/docs/user/composer.md index 8297e4bbf43ca..2a5222791535d 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -208,7 +208,8 @@ voice, then use the preview to try it. **Local model** reads replies in English with Supertonic 3 on your selected environment, so the text never leaves it. Download it once from the same settings page (330–360 MB). -It uses the GPU through Metal on Apple silicon Macs and Vulkan on Windows and Linux. Intel Macs and +Like dictation models, it reuses a copy already in the Hugging Face cache, and on web or desktop +you can paste the path of a copy elsewhere and choose **Use existing**. It uses the GPU through Metal on Apple silicon Macs and Vulkan on Windows and Linux. Intel Macs and machines without a GPU run it on the CPU, which takes a few seconds longer to start speaking. Local models run on macOS, Windows, and Linux with glibc 2.28 or newer. diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts index 7f6c8c714332e..5b72cf0c07413 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -381,6 +381,17 @@ export const cancelSpeechSynthesisModelDownload = (prepared: PreparedConnection, run: ({ client, headers }) => client.cancelSynthesisModel({ headers, payload: { modelId } }), }); +export const linkSpeechSynthesisModels = (prepared: PreparedConnection, path: string) => + request({ + group: "voice", + prepared, + method: "POST", + path: (urls) => urls.linkSynthesisModels(), + // Hashing the model, then fetching the runtime, takes longer than an ordinary request. + timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS, + run: ({ client, headers }) => client.linkSynthesisModels({ headers, payload: { path } }), + }); + export const removeSpeechSynthesisModel = (prepared: PreparedConnection, modelId: string) => request({ group: "voice", diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index 416bae47c8764..76e5946bb355f 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -44,6 +44,7 @@ export { cancelSpeechSynthesisModelDownload, downloadSpeechSynthesisModel, getSpeechSynthesisModels, + linkSpeechSynthesisModels, removeSpeechSynthesisModel, startSpeechSynthesis, } from "./environment.ts"; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 290ccb23fe076..5747f2f5c5ba9 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -886,6 +886,14 @@ export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice") error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], }).middleware(EnvironmentAuthenticatedAuth), ) + .add( + HttpApiEndpoint.post("linkSynthesisModels", "/api/voice/synthesis/local/models/link", { + headers: OptionalBearerHeaders, + payload: EnvironmentSpeechModelLinkRequest, + success: SpeechSynthesisCatalog, + error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], + }).middleware(EnvironmentAuthenticatedAuth), + ) .add( HttpApiEndpoint.post("removeSynthesisModel", "/api/voice/synthesis/local/models/remove", { headers: OptionalBearerHeaders, diff --git a/packages/contracts/src/readAloud.ts b/packages/contracts/src/readAloud.ts index 32a9b0983ff0c..6374eceda86bc 100644 --- a/packages/contracts/src/readAloud.ts +++ b/packages/contracts/src/readAloud.ts @@ -75,6 +75,8 @@ export const SpeechSynthesisModelInstall = Schema.Struct({ /** Bytes to download, including the speech runtime when this environment lacks it. */ size: Schema.Finite, downloaded: Schema.optionalKey(Schema.Finite), + /** The environment's own file an installed model uses; only filesystem readers see it. */ + linkedFrom: Schema.optionalKey(Schema.String), }); export type SpeechSynthesisModelInstall = typeof SpeechSynthesisModelInstall.Type; export const SpeechSynthesisModelRequest = Schema.Struct({ From 5ec77d18a12cde370f2e31a502c9f902e931db2b Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 10:06:36 -0600 Subject: [PATCH 25/33] fix(read-aloud): headings, list items, and table rows are spoken as separate sentences Speech engines read newlines as spaces, so markdown blocks ran together. Each block now ends in punctuation, as other read-aloud tools do. Co-authored-by: Cursor --- .../src/features/read-aloud/playback.test.ts | 2 +- packages/shared/src/readAloud.test.ts | 16 +++++- packages/shared/src/readAloud.ts | 54 +++++++++++-------- 3 files changed, 48 insertions(+), 24 deletions(-) diff --git a/apps/mobile/src/features/read-aloud/playback.test.ts b/apps/mobile/src/features/read-aloud/playback.test.ts index 68a37cf84201b..b525464283196 100644 --- a/apps/mobile/src/features/read-aloud/playback.test.ts +++ b/apps/mobile/src/features/read-aloud/playback.test.ts @@ -71,7 +71,7 @@ it("falls back from a removed system voice and completes playback", async () => voice: "removed-voice", }); expect(Speech.speak).toHaveBeenLastCalledWith( - "reply", + "reply.", expect.not.objectContaining({ voice: "removed-voice" }), ); expect(readAloudController.getSnapshot().status).toBe("idle"); diff --git a/packages/shared/src/readAloud.test.ts b/packages/shared/src/readAloud.test.ts index ab999a7861fbb..e05e00774bfba 100644 --- a/packages/shared/src/readAloud.test.ts +++ b/packages/shared/src/readAloud.test.ts @@ -5,12 +5,24 @@ it("reads visible prose and identifiers without link targets or fenced code", () const text = "# Findings\n\nUse **readAloud** and `message.id`. [Details](https://example.com/private).\n\n```ts\nsecret();\n```\n\nDone."; expect(readAloudText(text, true)).toBe( - "Findings\nUse readAloud and message.id. Details.\n\nDone.", + "Findings.\nUse readAloud and message.id. Details.\nDone.", ); expect(readAloudText(text, false)).toContain("secret();"); expect(readAloudText("![image](https://example.com/image)\n\n", true)).toBe(""); expect(readAloudText("Hello \nworld.\n\n> First.\n>\n> Second.", true)).toBe( - "Hello\nworld.\nFirst.\nSecond.", + "Hello.\nworld.\nFirst.\nSecond.", + ); +}); + +it("ends every heading, list item, and table row as its own sentence", () => { + const text = [ + "## Next steps", + "1. Run the tests\n2. Push the branch:\n - check CI", + "| File | Change |\n| --- | --- |\n| a.ts | Adds `x` |", + "See (the docs)", + ].join("\n\n"); + expect(readAloudText(text, true)).toBe( + "Next steps.\nRun the tests.\nPush the branch:\ncheck CI.\nFile, Change.\na.ts, Adds x.\nSee (the docs).", ); }); diff --git a/packages/shared/src/readAloud.ts b/packages/shared/src/readAloud.ts index adcdb38f319ce..d54004d6abe57 100644 --- a/packages/shared/src/readAloud.ts +++ b/packages/shared/src/readAloud.ts @@ -5,31 +5,43 @@ import remarkGfm from "remark-gfm"; const parser = unified().use(remarkParse).use(remarkGfm); +// Already ends a sentence, allowing closing quotes or brackets after the punctuation. +const SENTENCE_END = /[.!?…:;。!?:;]["'”’)\]]*$/u; + +/** + * Plain text with one sentence per line. Speech engines read newlines as spaces, so every + * heading, paragraph, list item, and table row ends in punctuation to keep its pause. + */ export function readAloudText(markdown: string, skipCodeBlocks: boolean) { - const root = parser.parse(markdown); - const visit = (node: Root | RootContent): string => { - if (node.type === "break") return "\n"; - if (node.type === "code") return skipCodeBlocks ? "" : node.value; - if ( - node.type === "html" || - node.type === "definition" || - node.type === "image" || - node.type === "imageReference" - ) - return ""; - if ("children" in node) { - const separator = ["root", "list", "listItem", "blockquote", "table", "tableRow"].includes( - node.type, - ) - ? "\n" - : ""; - return node.children.map(visit).join(separator); + const sentences: string[] = []; + const speak = (text: string) => { + for (const line of text.split("\n")) { + const sentence = line.replace(/\s+/g, " ").trim(); + if (sentence) sentences.push(SENTENCE_END.test(sentence) ? sentence : `${sentence}.`); } + }; + const inline = (node: RootContent): string => { + if (node.type === "break") return "\n"; + if (node.type === "html" || node.type === "image" || node.type === "imageReference") return ""; + if ("children" in node) return node.children.map(inline).join(""); return "value" in node ? node.value : ""; }; - return visit(root) - .replace(/\n{3,}/g, "\n\n") - .trim(); + const block = (node: Root | RootContent) => { + if (node.type === "paragraph" || node.type === "heading") speak(inline(node)); + else if (node.type === "tableRow") + speak( + node.children + .map((cell) => inline(cell).trim()) + .filter(Boolean) + .join(", "), + ); + else if (node.type === "code") { + if (!skipCodeBlocks) speak(node.value); + } else if (node.type !== "html" && node.type !== "definition" && "children" in node) + for (const child of node.children) block(child); + }; + block(parser.parse(markdown)); + return sentences.join("\n"); } export function splitReadAloudText(text: string, limit = 3500) { From 220e1db2e4c6195e2c427b4c695a3b25e2298745 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 10:06:36 -0600 Subject: [PATCH 26/33] feat(read-aloud): choose between Supertonic 3 and Pocket TTS local models The local catalog lists each model with its languages and size, like dictation. Pocket TTS is small and fast without a GPU; its voices ship as files beside the model, so installs, links, and removals now cover every file a model needs. Co-authored-by: Cursor --- .../src/features/read-aloud/playback.ts | 11 +- .../src/speech/LocalSpeechSynthesis.test.ts | 16 +- .../server/src/speech/LocalSpeechSynthesis.ts | 191 ++++++++++++++---- .../src/speech/SpeechModelStore.test.ts | 14 +- apps/server/src/speech/SpeechModelStore.ts | 9 +- .../settings/ReadAloudSettingsSection.tsx | 175 ++++++++++------ apps/web/src/speech/readAloud.ts | 7 +- docs/user/composer.md | 13 +- packages/contracts/src/readAloud.ts | 8 + 9 files changed, 320 insertions(+), 124 deletions(-) diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts index 56b2361687566..cc6e50376f11d 100644 --- a/apps/mobile/src/features/read-aloud/playback.ts +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -7,7 +7,11 @@ import { createAudioPlayer } from "expo-audio"; import * as Speech from "expo-speech"; import * as Option from "effect/Option"; import { AppState, Platform } from "react-native"; -import type { ReadAloudSettings, SpeechSynthesisCatalog } from "@t3tools/contracts"; +import { + speechSpeedAppliedByProvider, + type ReadAloudSettings, + type SpeechSynthesisCatalog, +} from "@t3tools/contracts"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentSession } from "../../state/session"; import { createAudioPlaybackSession, disposeAudioPlayer } from "../../lib/audioSession"; @@ -125,10 +129,11 @@ export const readAloudController = createReadAloudController(async (text, settin const catalog = await pendingCatalog; signal.throwIfAborted(); if (catalog.error) throw new Error(catalog.error); + const model = settings.model || catalog.defaultModel; const url = await runSpeech( startSpeechSynthesis(prepared, settings.provider, { text, - model: settings.model || catalog.defaultModel, + model, voice: settings.voice, speed: settings.speed, language: settings.language, @@ -137,7 +142,7 @@ export const readAloudController = createReadAloudController(async (text, settin ); signal.throwIfAborted(); const player = createAudioPlayer(url, { updateInterval: 500 }); - if (!catalog.speedAppliedByProvider) player.setPlaybackRate(settings.speed); + if (!speechSpeedAppliedByProvider(catalog, model)) player.setPlaybackRate(settings.speed); const stopWatching = watchForeground(settings); const session = createAudioPlaybackSession( { diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts index 548f9ecf76f83..3d1538ff0128d 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.test.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -59,14 +59,20 @@ const withService = ( it.effect("counts only the files an install still needs in its download size", () => withService( - { isReady: (file) => Effect.succeed(file.id !== "pingdotgg/audio.cpp") }, + { + isReady: (file) => + Effect.succeed( + file.id !== "pingdotgg/audio.cpp" && !file.filename.endsWith("-alba.safetensors"), + ), + }, (service) => Effect.gen(function* () { + const runtime = audioCppRuntime("darwin", "arm64")!.size; const { models } = yield* service.catalog; - expect(models[0]?.install).toEqual({ - state: "downloadable", - size: audioCppRuntime("darwin", "arm64")!.size, - }); + expect(models.map((model) => [model.id, model.install])).toEqual([ + ["supertonic-3", { state: "downloadable", size: runtime }], + ["pocket-tts-english", { state: "downloadable", size: runtime + 6_194_424 }], + ]); }), { runtime: false }, ), diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 289f84ffcb1de..8ba39f3c55b22 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -27,30 +27,115 @@ import * as ServerConfig from "../config.ts"; import * as SpeechModelStore from "./SpeechModelStore.ts"; import { loadLocalSynthesisModel, type LocalSynthesisModel } from "./localSynthesisWorker.ts"; +/** A preset the model names itself, or one it reads from its own file. */ +type LocalVoice = { readonly id: string; readonly file?: SpeechModelStore.ModelFile }; + type LocalModel = { readonly id: string; readonly name: string; + readonly description: string; readonly file: SpeechModelStore.ModelFile; - readonly voices: readonly string[]; + /** Whether the model honors the speed option; clients speed up playback for the rest. */ + readonly appliesSpeed: boolean; + readonly voices: readonly LocalVoice[]; }; +const AUDIO_CPP_GGUF = "audio-cpp/audio.cpp-gguf"; +const POCKET_REVISION = "7a103b33f04120535bdfe97b5f65b79d3c90d708"; +// Named per model, since every Pocket TTS language ships voice files with the same names. +const pocketVoice = (name: string, size: number, sha256: string): LocalVoice => ({ + id: name[0]!.toUpperCase() + name.slice(1), + file: { + id: AUDIO_CPP_GGUF, + revision: POCKET_REVISION, + filename: `pocket-tts-english-${name}.safetensors`, + url: `https://huggingface.co/${AUDIO_CPP_GGUF}/resolve/${POCKET_REVISION}/PocketTTS-GGUF/english/embeddings/${name}.safetensors`, + size, + sha256, + }, +}); + // Families that phonemize with eSpeak-ng (Kokoro, Kitten, Piper) need a GPL library that // upstream does not ship, so only self-contained models belong here. const LOCAL_SYNTHESIS_MODELS: readonly LocalModel[] = [ { id: "supertonic-3", name: "Supertonic 3", + description: "31 languages. Fastest with a GPU.", file: { - id: "audio-cpp/audio.cpp-gguf", + id: AUDIO_CPP_GGUF, revision: "ca0b203eb1bb87f333a7cfbad2d5f6672b4ccba7", filename: "Supertonic-3-GGUF/supertonic-3-f16.gguf", size: 312_785_732, sha256: "7a44c47d1f387e4fb163e2eed9615b58470c77e26ac8b2b1a6be49dfb8670899", }, - voices: ["F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5"], + appliesSpeed: true, + voices: ["F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5"].map((id) => ({ id })), + }, + { + id: "pocket-tts-english", + name: "Pocket TTS", + description: "English only. Small, and fast without a GPU.", + file: { + id: AUDIO_CPP_GGUF, + revision: POCKET_REVISION, + filename: "PocketTTS-GGUF/english/pocket-tts-english-q8_0.gguf", + size: 127_867_968, + sha256: "3f71cf6a51f93c2f2e554e98970a3f49fb9a98d0c64bed5a815e65be3d2ff588", + }, + appliesSpeed: false, + voices: [ + pocketVoice( + "alba", + 6_194_424, + "69c32db63ca56843d994f81f343f62e0bf2d73f7e4c9bc73e44bb1110b1d8845", + ), + pocketVoice( + "anna", + 7_816_440, + "5ea82f78db006c9fd34e32ddd5aae82674b5b32646097977436458d00af80dfa", + ), + pocketVoice( + "eve", + 6_538_488, + "ea9c2faf862a6c9d2cb61910fdf02842ae56940382cc8c1000fdb1b43269692b", + ), + pocketVoice( + "jane", + 7_374_072, + "37386227ca8ec5bf1b8e516c13d132ce5ff5437a304fe90129a1c62f41d9a008", + ), + pocketVoice( + "charles", + 6_194_424, + "299edc20182eeccfbf94e308626f259da4fbf339daa8d5905218f2b1774639b8", + ), + pocketVoice( + "george", + 6_243_576, + "0c1c6c57c55a98d81254b33728150c7776f40647fe95258d1a6c1a02780b5d02", + ), + pocketVoice( + "michael", + 7_275_768, + "8937f724ac4719b9aa51ea0ba1f18f9de0af7a663ad6263558266c1a53c9722d", + ), + pocketVoice( + "paul", + 6_980_856, + "ed7a019168f94dfe77009f1b0de59387abc6fbb0db954d38ce722ecb77da61aa", + ), + ], }, ]; +const modelFiles = (model: LocalModel) => [ + model.file, + ...model.voices.flatMap((voice) => (voice.file ? [voice.file] : [])), +]; +const totalSize = (files: readonly SpeechModelStore.ModelFile[]) => + files.reduce((size, file) => size + file.size, 0); + const IDLE_UNLOAD_MS = 10 * 60_000; export class LocalSynthesisInstallError extends Schema.TaggedError()( @@ -233,25 +318,33 @@ const make = Effect.gen(function* () { const models = yield* Effect.forEach(LOCAL_SYNTHESIS_MODELS, (model) => Effect.gen(function* () { const active = transfer?.modelId === model.id ? transfer : undefined; - const modelReady = yield* store.isReady(model.file); - const linkedFrom = ready && modelReady ? yield* store.linkedFrom(model.file) : undefined; + const files = modelFiles(model); + const missing = yield* Effect.filter(files, (file) => + store.isReady(file).pipe(Effect.map((fileReady) => !fileReady)), + ); + const installed = ready && missing.length === 0; + const linkedFrom = installed ? yield* store.linkedFrom(model.file) : undefined; const install = active ? { state: active.verifying ? ("verifying" as const) : ("downloading" as const), size: active.size, downloaded: active.runtime + active.model, } - : ready && modelReady + : installed ? { state: "installed" as const, - size: model.file.size, + size: totalSize(files), ...(linkedFrom && { linkedFrom }), } - : { - state: "downloadable" as const, - size: (modelReady ? 0 : model.file.size) + runtimeSize, - }; - return { id: model.id, name: model.name, voices: model.voices, install }; + : { state: "downloadable" as const, size: totalSize(missing) + runtimeSize }; + return { + id: model.id, + name: model.name, + description: model.description, + voices: model.voices.map((voice) => voice.id), + install, + ...(model.appliesSpeed ? {} : { speedAppliedByProvider: false }), + }; }), ); return { @@ -283,7 +376,7 @@ const make = Effect.gen(function* () { if (!transfer) { const state: Transfer = { modelId, - size: model.file.size, + size: totalSize(modelFiles(model)), runtime: 0, model: 0, verifying: false, @@ -292,9 +385,11 @@ const make = Effect.gen(function* () { const install = Effect.gen(function* () { // Read after claiming: no removal or link can start while this transfer exists. const needsRuntime = !(yield* runtimeReady); - state.size = - (needsRuntime ? runtimeFile.size : 0) + - ((yield* store.isReady(model.file)) ? 0 : model.file.size); + const files = modelFiles(model); + const missing = yield* Effect.filter(files, (file) => + store.isReady(file).pipe(Effect.map((fileReady) => !fileReady)), + ); + state.size = (needsRuntime ? runtimeFile.size : 0) + totalSize(missing); if (needsRuntime) { const archivePath = yield* store.download(runtimeFile, { onProgress: (downloaded) => { @@ -311,15 +406,21 @@ const make = Effect.gen(function* () { state.runtime = runtimeFile.size; } state.verifying = false; - yield* store.download(model.file, { - onProgress: (downloaded) => { - state.model = downloaded; - state.verifying = false; - }, - onVerificationStart: () => { - state.verifying = true; - }, - }); + // Files already in place still go through `download`, which verifies them. + let finished = 0; + for (const file of files) { + const counted = missing.includes(file); + yield* store.download(file, { + onProgress: (downloaded) => { + if (counted) state.model = finished + downloaded; + state.verifying = false; + }, + onVerificationStart: () => { + state.verifying = true; + }, + }); + if (counted) finished += file.size; + } }); // Owned by the service, so a dropped request does not abandon a large download. state.fiber = yield* install.pipe( @@ -389,19 +490,28 @@ const make = Effect.gen(function* () { const link = Effect.fn("LocalSpeechSynthesis.link")(function* (source: string) { if (!runtimeFile) return yield* new LocalSynthesisInstallError({ reason: "unsupported-platform" }); + const linkedBefore = yield* Effect.forEach(LOCAL_SYNTHESIS_MODELS, (model) => + store.isReady(model.file), + ); const linked = yield* exclusive( store - .link( - LOCAL_SYNTHESIS_MODELS.map((model) => model.file), - source, - ) + .link(LOCAL_SYNTHESIS_MODELS.flatMap(modelFiles), source) .pipe(Effect.mapError(installFailed)), ); - const model = LOCAL_SYNTHESIS_MODELS.find((entry) => linked.includes(entry.file.id)); + const linkedAfter = yield* Effect.forEach(LOCAL_SYNTHESIS_MODELS, (model) => + store.isReady(model.file), + ); + const model = linked.length + ? (LOCAL_SYNTHESIS_MODELS.find((_, index) => linkedAfter[index] && !linkedBefore[index]) ?? + LOCAL_SYNTHESIS_MODELS.find((_, index) => linkedAfter[index])) + : undefined; if (!model) return yield* new LocalSynthesisInstallError({ reason: "not-found" }); - // The model is in place; an install now fetches only the runtime. - if (!(yield* runtimeReady)) return yield* download(model.id); - return yield* catalog; + const missing = yield* Effect.filter(modelFiles(model), (file) => + store.isReady(file).pipe(Effect.map((fileReady) => !fileReady)), + ); + if ((yield* runtimeReady) && missing.length === 0) return yield* catalog; + // The model file is in place; an install fetches only the runtime and voices it lacks. + return yield* download(model.id); }); const remove = Effect.fn("LocalSpeechSynthesis.remove")(function* (modelId: string) { @@ -410,7 +520,9 @@ const make = Effect.gen(function* () { permit.withPermits(1)( Effect.gen(function* () { if (worker?.modelId === modelId) yield* unloadWorker; - yield* store.remove(model.file).pipe(Effect.mapError(installFailed)); + yield* Effect.forEach(modelFiles(model), (file) => store.remove(file)).pipe( + Effect.mapError(installFailed), + ); const remaining = yield* Effect.filter(LOCAL_SYNTHESIS_MODELS, (entry) => store.isReady(entry.file), ); @@ -443,7 +555,10 @@ const make = Effect.gen(function* () { if (!definition) return yield* failure("model-unavailable"); if (!(yield* runtimeReady)) return yield* failure("missing-model"); const modelPath = yield* store.installedPath(definition.file); - if (!modelPath) return yield* failure("missing-model"); + const voice = + definition.voices.find((entry) => entry.id === request.voice) ?? definition.voices[0]!; + const voicePath = voice.file && (yield* store.installedPath(voice.file)); + if (!modelPath || (voice.file && !voicePath)) return yield* failure("missing-model"); // Held until the stream ends, after any cancelled synthesis has stopped. // Interruptible, so a request abandoned while waiting stops waiting. yield* Effect.acquireRelease( @@ -486,10 +601,8 @@ const make = Effect.gen(function* () { text: request.text, ...(language ? { language } : {}), options: { - voice_id: definition.voices.includes(request.voice) - ? request.voice - : definition.voices[0]!, - speed: String(request.speed), + ...(voicePath ? { voice_embedding_file: voicePath } : { voice_id: voice.id }), + ...(definition.appliesSpeed ? { speed: String(request.speed) } : {}), }, }, (bytes) => Queue.offerUnsafe(queue, bytes), diff --git a/apps/server/src/speech/SpeechModelStore.test.ts b/apps/server/src/speech/SpeechModelStore.test.ts index 0f6e5105d29cd..a9a0fed1b5d6b 100644 --- a/apps/server/src/speech/SpeechModelStore.test.ts +++ b/apps/server/src/speech/SpeechModelStore.test.ts @@ -198,11 +198,23 @@ it.effect("links a verified model file from another folder and never deletes it" const existing = path.join(nested, "renamed-by-the-other-app.gguf"); yield* h.fs.writeFile(impostor, new Uint8Array(bytes.length)); yield* h.fs.writeFile(existing, bytes); + // A second file from the same repository, such as a voice beside its model. + const voiceBytes = bytes.subarray(0, 32); + const voice = { + ...h.model, + filename: "voice.safetensors", + size: voiceBytes.length, + sha256: Hex.encode( + yield* (yield* Digest.Digest).digest(Digest.sha256, voiceBytes).pipe(Effect.orDie), + ), + }; + yield* h.fs.writeFile(path.join(nested, "voice.safetensors"), voiceBytes); expect(yield* h.store.link([h.model], impostor)).toEqual([]); expect(yield* h.store.linkedFrom(h.model)).toBeUndefined(); - expect(yield* h.store.link([h.model], elsewhere)).toEqual([h.model.id]); + expect(yield* h.store.link([h.model, voice], elsewhere)).toEqual([h.model.id, voice.id]); + expect(yield* h.store.installedPath(voice)).toBeDefined(); expect(yield* h.store.linkedFrom(h.model)).toBe(existing); expect(yield* h.store.installedPath(h.model)).toBe(h.stale); expect(h.requests).toHaveLength(0); diff --git a/apps/server/src/speech/SpeechModelStore.ts b/apps/server/src/speech/SpeechModelStore.ts index f1e4affc1c7e6..e18c4315cc8e7 100644 --- a/apps/server/src/speech/SpeechModelStore.ts +++ b/apps/server/src/speech/SpeechModelStore.ts @@ -249,10 +249,11 @@ const make = Effect.gen(function* () { ), ); yield* fs.makeDirectory(directory, { recursive: true }); - const linked: string[] = []; + // By file, since several files can come from one repository. + const linked = new Set(); for (const { file, size } of yield* filesUnder(root)) { for (const model of models) { - if (model.size !== size || linked.includes(model.id)) continue; + if (model.size !== size || linked.has(model)) continue; const finalPath = modelPath(model); // Pointing at T3 Code's own model folder must not replace a file with a link to itself. if ((yield* realPath(file)) === (yield* realPath(finalPath))) continue; @@ -282,10 +283,10 @@ const make = Effect.gen(function* () { yield* fs .writeFileString(`${finalPath}.verified`, marker, { mode: 0o600 }) .pipe(Effect.ignore); - linked.push(model.id); + linked.add(model); } } - return linked; + return [...linked].map((model) => model.id); }, ); diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 9b4e02cf4b8e8..74b2a2022e498 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -25,7 +25,7 @@ import { useEnvironments } from "../../state/environments"; import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; import { readAloudController } from "../../speech/readAloud"; -import { DownloadIcon, XIcon } from "lucide-react"; +import { CheckIcon, DownloadIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Switch } from "../ui/switch"; @@ -128,20 +128,22 @@ const formatSize = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`; function LocalSpeechModel({ prepared, model, + selected, refreshing, + onSelect, onChanged, }: { prepared: PreparedConnection; model: SpeechSynthesisCatalog["models"][number]; + selected: boolean; /** A catalog request is in flight; polling waits for it rather than aborting it. */ refreshing: boolean; + onSelect: () => void; onChanged: () => void; }) { const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); - const canReadFiles = useEnvironmentScope(prepared.environmentId, AuthFilesystemReadScope); const [requesting, setRequesting] = useState(false); const [error, setError] = useState(""); - const [existingPath, setExistingPath] = useState(""); const install = model.install; const downloading = install?.state === "downloading" || install?.state === "verifying"; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Poll the environment's download progress while it runs. @@ -151,7 +153,7 @@ function LocalSpeechModel({ return () => window.clearTimeout(timer); }, [downloading, requesting, refreshing, onChanged]); if (!install) return null; - const run = async (action: "download" | "cancel" | "remove" | "link") => { + const run = async (action: "download" | "cancel" | "remove") => { setRequesting(true); setError(""); try { @@ -160,18 +162,14 @@ function LocalSpeechModel({ ? downloadSpeechSynthesisModel(prepared, model.id) : action === "cancel" ? cancelSpeechSynthesisModelDownload(prepared, model.id) - : action === "link" - ? linkSpeechSynthesisModels(prepared, existingPath) - : removeSpeechSynthesisModel(prepared, model.id), + : removeSpeechSynthesisModel(prepared, model.id), ); - if (action === "link") setExistingPath(""); + if (action === "download") onSelect(); } catch { setError( action === "download" ? "Could not download the model. Check the environment's connection and disk space." - : action === "link" - ? `No ${model.name} file was found at that path.` - : "Could not change the model. Try again.", + : "Could not change the model. Try again.", ); } setRequesting(false); @@ -186,9 +184,10 @@ function LocalSpeechModel({ title={model.name} description={ <> + {model.description}{" "} {install.state === "installed" - ? "Installed on the selected environment. Replies are read without leaving it." - : `Runs on the selected environment after a ${formatSize(install.size)} download.`} + ? `Installed on the selected environment (${formatSize(install.size)}).` + : `${formatSize(install.size)} download.`} {install.linkedFrom && ( Using your file at {install.linkedFrom} @@ -231,19 +230,31 @@ function LocalSpeechModel({ ) : install.state === "installed" ? ( - +

+ {selected ? ( + + ) : ( + + )} + +
) : ( - - )} +
{ + event.preventDefault(); + setLinking(true); + setError(""); + void runEnvironmentSpeech(linkSpeechSynthesisModels(prepared, path)) + .then( + () => setPath(""), + () => setError("No speech model file was found at that path."), + ) + .finally(() => { + setLinking(false); + onChanged(); + }); + }} + > +
+ setPath(event.target.value)} + /> +
+ +
); } @@ -308,7 +350,8 @@ export function ReadAloudSettingsSection() { ? catalogState.error || catalog.error || "" : ""; const model = settings.model || catalog.defaultModel; - const localModel = catalog.models.find((entry) => entry.id === model && entry.install); + const localModels = + settings.provider === "local" ? catalog.models.filter((entry) => entry.install) : []; const refreshCatalog = () => setCatalogVersion((value) => value + 1); const [systemVoices, setSystemVoices] = useState([]); const state = useSyncExternalStore( @@ -463,21 +506,27 @@ export function ReadAloudSettingsSection() { onSaved={() => setCatalogVersion((value) => value + 1)} /> )} - {settings.provider === "local" && prepared && localModel && ( - + {prepared && + localModels.map((entry) => ( + change({ model: entry.id, voice: "" })} + onChanged={refreshCatalog} + /> + ))} + {prepared && localModels.some((entry) => entry.install?.state === "downloadable") && ( + )} {remote && error && (

{error}

)} - {remote && catalog.supportsModelSelection && ( + {remote && !localModels.length && catalog.supportsModelSelection && ( void = () => {}; const finished = new Promise((resolve, reject) => { done = resolve; diff --git a/docs/user/composer.md b/docs/user/composer.md index 2a5222791535d..6f435b51611f2 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -206,12 +206,13 @@ System voices run on your device. OpenAI, Grok TTS, and OpenRouter send the repl through your selected environment and use API billing. They share the API keys saved for dictation. Choose a model and voice, then use the preview to try it. -**Local model** reads replies in English with Supertonic 3 on your selected environment, -so the text never leaves it. Download it once from the same settings page (330–360 MB). -Like dictation models, it reuses a copy already in the Hugging Face cache, and on web or desktop -you can paste the path of a copy elsewhere and choose **Use existing**. It uses the GPU through Metal on Apple silicon Macs and Vulkan on Windows and Linux. Intel Macs and -machines without a GPU run it on the CPU, which takes a few seconds longer to start speaking. Local -models run on macOS, Windows, and Linux with glibc 2.28 or newer. +**Local model** reads replies on your selected environment, so the text never leaves it. +Download a model once from the same settings page. Supertonic 3 (330–360 MB) speaks 31 +languages and is fastest with a GPU. Pocket TTS (about 200 MB) speaks English and stays fast +on machines without one. Like dictation models, they reuse a copy already in the Hugging Face +cache, and on web or desktop you can paste the path of a copy elsewhere and choose **Use +existing**. Local models use the GPU through Metal on Apple silicon Macs and Vulkan on Windows +and Linux, and run on macOS, Windows, and Linux with glibc 2.28 or newer. On mobile, **Background playback** allows speech to continue while the app is in the background. diff --git a/packages/contracts/src/readAloud.ts b/packages/contracts/src/readAloud.ts index 6374eceda86bc..fb84fefcd6c9f 100644 --- a/packages/contracts/src/readAloud.ts +++ b/packages/contracts/src/readAloud.ts @@ -93,14 +93,22 @@ export const SpeechSynthesisCatalog = Schema.Struct({ Schema.Struct({ id: Schema.String, name: Schema.String, + description: Schema.optionalKey(Schema.String), voices: Schema.Array(Schema.String), /** Present for models that run on the environment and must be downloaded first. */ install: Schema.optionalKey(SpeechSynthesisModelInstall), + /** Overrides the catalog's `speedAppliedByProvider` for this model. */ + speedAppliedByProvider: Schema.optionalKey(Schema.Boolean), }), ), }); export type SpeechSynthesisCatalog = typeof SpeechSynthesisCatalog.Type; +/** Whether synthesis already honors the speed setting; otherwise players speed up playback. */ +export const speechSpeedAppliedByProvider = (catalog: SpeechSynthesisCatalog, model: string) => + catalog.models.find((entry) => entry.id === model)?.speedAppliedByProvider ?? + catalog.speedAppliedByProvider; + export const EMPTY_SPEECH_SYNTHESIS_CATALOG: SpeechSynthesisCatalog = { defaultModel: "", apiKeyProvider: null, From 089bc9550b21bbc25351d99cd90b86591e1d44d5 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 15:00:32 -0600 Subject: [PATCH 27/33] feat(read-aloud): Kokoro is the default local voice, with af_heart Kokoro streams through the audio.cpp t3-2026.11.17 runtimes, which link eSpeak-ng and hand out chunks from models that generate in one pass. Its eSpeak data downloads and is removed with the model, and unpacks under the T3 home. Co-authored-by: Cursor --- .../src/speech/LocalSpeechSynthesis.test.ts | 3 +- .../server/src/speech/LocalSpeechSynthesis.ts | 94 +++++++++++++++++-- .../server/src/speech/localSynthesisWorker.ts | 4 +- docs/user/composer.md | 7 +- packages/audio-cpp/src/bindings.ts | 23 +++-- packages/audio-cpp/src/index.ts | 7 +- packages/audio-cpp/src/runtime.ts | 34 ++++--- 7 files changed, 135 insertions(+), 37 deletions(-) diff --git a/apps/server/src/speech/LocalSpeechSynthesis.test.ts b/apps/server/src/speech/LocalSpeechSynthesis.test.ts index 3d1538ff0128d..e63285a17a7e0 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.test.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.test.ts @@ -1,6 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; -import { AUDIO_CPP_VERSION, audioCppRuntime } from "@t3tools/audio-cpp"; +import { AUDIO_CPP_ESPEAK_DATA, AUDIO_CPP_VERSION, audioCppRuntime } from "@t3tools/audio-cpp"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; @@ -70,6 +70,7 @@ it.effect("counts only the files an install still needs in its download size", ( const runtime = audioCppRuntime("darwin", "arm64")!.size; const { models } = yield* service.catalog; expect(models.map((model) => [model.id, model.install])).toEqual([ + ["kokoro-82m", { state: "downloadable", size: runtime + AUDIO_CPP_ESPEAK_DATA.size }], ["supertonic-3", { state: "downloadable", size: runtime }], ["pocket-tts-english", { state: "downloadable", size: runtime + 6_194_424 }], ]); diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 8ba39f3c55b22..80e4e512923e2 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -5,7 +5,12 @@ import { type SpeechSynthesisCatalog, type SpeechSynthesisRequest, } from "@t3tools/contracts"; -import { AUDIO_CPP_VERSION, audioCppRuntime, type AudioCppRuntime } from "@t3tools/audio-cpp"; +import { + AUDIO_CPP_ESPEAK_DATA, + AUDIO_CPP_VERSION, + audioCppRuntime, + type AudioCppRuntime, +} from "@t3tools/audio-cpp"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; @@ -38,26 +43,87 @@ type LocalModel = { /** Whether the model honors the speed option; clients speed up playback for the rest. */ readonly appliesSpeed: boolean; readonly voices: readonly LocalVoice[]; + /** eSpeak-ng data the model phonemizes with, installed and removed with it. */ + readonly espeakData?: SpeechModelStore.ModelFile; }; const AUDIO_CPP_GGUF = "audio-cpp/audio.cpp-gguf"; -const POCKET_REVISION = "7a103b33f04120535bdfe97b5f65b79d3c90d708"; +const GGUF_REVISION = "7a103b33f04120535bdfe97b5f65b79d3c90d708"; // Named per model, since every Pocket TTS language ships voice files with the same names. const pocketVoice = (name: string, size: number, sha256: string): LocalVoice => ({ id: name[0]!.toUpperCase() + name.slice(1), file: { id: AUDIO_CPP_GGUF, - revision: POCKET_REVISION, + revision: GGUF_REVISION, filename: `pocket-tts-english-${name}.safetensors`, - url: `https://huggingface.co/${AUDIO_CPP_GGUF}/resolve/${POCKET_REVISION}/PocketTTS-GGUF/english/embeddings/${name}.safetensors`, + url: `https://huggingface.co/${AUDIO_CPP_GGUF}/resolve/${GGUF_REVISION}/PocketTTS-GGUF/english/embeddings/${name}.safetensors`, size, sha256, }, }); -// Families that phonemize with eSpeak-ng (Kokoro, Kitten, Piper) need a GPL library that -// upstream does not ship, so only self-contained models belong here. +// Japanese and Chinese Kokoro voices need the multilingual package's dictionaries. +const KOKORO_VOICES = [ + ...[ + "heart", + "alloy", + "aoede", + "bella", + "jessica", + "kore", + "nicole", + "nova", + "river", + "sarah", + "sky", + ].map((name) => `af_${name}`), + ...["adam", "echo", "eric", "fenrir", "liam", "michael", "onyx", "puck", "santa"].map( + (name) => `am_${name}`, + ), + "bf_alice", + "bf_emma", + "bf_isabella", + "bf_lily", + "bm_daniel", + "bm_fable", + "bm_george", + "bm_lewis", + "ef_dora", + "em_alex", + "em_santa", + "ff_siwis", + "hf_alpha", + "hf_beta", + "hm_omega", + "hm_psi", + "if_sara", + "im_nicola", + "pf_dora", + "pm_alex", + "pm_santa", +]; + +// The first model is the default, and each model's first voice is its default. const LOCAL_SYNTHESIS_MODELS: readonly LocalModel[] = [ + { + id: "kokoro-82m", + name: "Kokoro", + description: "Natural English voices, plus Spanish, French, Hindi, Italian, and Portuguese.", + file: { + id: AUDIO_CPP_GGUF, + revision: GGUF_REVISION, + filename: "Kokoro-82M-GGUF/kokoro-82m-q8_0.gguf", + size: 189_550_976, + sha256: "9a4ca6176460cdc8c7845b804c0bbe85a4791ee3ffff568a3fdadbb708c63f47", + }, + appliesSpeed: true, + voices: KOKORO_VOICES.map((id) => ({ id })), + espeakData: { + id: "pingdotgg/audio.cpp", + revision: AUDIO_CPP_VERSION, + ...AUDIO_CPP_ESPEAK_DATA, + }, + }, { id: "supertonic-3", name: "Supertonic 3", @@ -78,7 +144,7 @@ const LOCAL_SYNTHESIS_MODELS: readonly LocalModel[] = [ description: "English only. Small, and fast without a GPU.", file: { id: AUDIO_CPP_GGUF, - revision: POCKET_REVISION, + revision: GGUF_REVISION, filename: "PocketTTS-GGUF/english/pocket-tts-english-q8_0.gguf", size: 127_867_968, sha256: "3f71cf6a51f93c2f2e554e98970a3f49fb9a98d0c64bed5a815e65be3d2ff588", @@ -132,6 +198,7 @@ const LOCAL_SYNTHESIS_MODELS: readonly LocalModel[] = [ const modelFiles = (model: LocalModel) => [ model.file, ...model.voices.flatMap((voice) => (voice.file ? [voice.file] : [])), + ...(model.espeakData ? [model.espeakData] : []), ]; const totalSize = (files: readonly SpeechModelStore.ModelFile[]) => files.reduce((size, file) => size + file.size, 0); @@ -245,6 +312,8 @@ const make = Effect.gen(function* () { `audio-cpp-${AUDIO_CPP_VERSION}-${platform}-${architecture}`, ); const libraryPath = runtime && path.join(runtimeDirectory, runtime.library); + // audio.cpp unpacks eSpeak's data package here on first use. + const espeakCache = path.join(config.stateDir, "speech", "cache"); // Written last, so a directory without it is an interrupted extraction. const completeMarker = path.join(runtimeDirectory, ".t3-complete"); @@ -523,6 +592,10 @@ const make = Effect.gen(function* () { yield* Effect.forEach(modelFiles(model), (file) => store.remove(file)).pipe( Effect.mapError(installFailed), ); + if (model.espeakData) + yield* fs + .remove(espeakCache, { recursive: true, force: true }) + .pipe(Effect.mapError(installFailed)); const remaining = yield* Effect.filter(LOCAL_SYNTHESIS_MODELS, (entry) => store.isReady(entry.file), ); @@ -558,7 +631,9 @@ const make = Effect.gen(function* () { const voice = definition.voices.find((entry) => entry.id === request.voice) ?? definition.voices[0]!; const voicePath = voice.file && (yield* store.installedPath(voice.file)); - if (!modelPath || (voice.file && !voicePath)) return yield* failure("missing-model"); + const espeakPath = definition.espeakData && (yield* store.installedPath(definition.espeakData)); + if (!modelPath || (voice.file && !voicePath) || (definition.espeakData && !espeakPath)) + return yield* failure("missing-model"); // Held until the stream ends, after any cancelled synthesis has stopped. // Interruptible, so a request abandoned while waiting stops waiting. yield* Effect.acquireRelease( @@ -578,6 +653,9 @@ const make = Effect.gen(function* () { libraryPath, backend: runtime.backend, modelPath, + ...(espeakPath && { + env: { AUDIOCPP_ESPEAK_DATA: espeakPath, AUDIOCPP_ESPEAK_CACHE: espeakCache }, + }), threads: Math.max(1, Math.min(8, NodeOS.availableParallelism() - 1)), signal: lifetime.signal, }), diff --git a/apps/server/src/speech/localSynthesisWorker.ts b/apps/server/src/speech/localSynthesisWorker.ts index fbeeca694f235..32ffe35c961d4 100644 --- a/apps/server/src/speech/localSynthesisWorker.ts +++ b/apps/server/src/speech/localSynthesisWorker.ts @@ -106,6 +106,8 @@ export async function loadLocalSynthesisModel(options: { /** Falls back to the CPU when the backend has no device here. */ readonly backend: string; readonly modelPath: string; + /** Extra environment for the worker, such as where a model's eSpeak data lives. */ + readonly env?: Readonly>; readonly threads: number; readonly signal: AbortSignal; }) { @@ -113,7 +115,7 @@ export async function loadLocalSynthesisModel(options: { const child = NodeChildProcess.spawn(process.execPath, workerArgs(), { stdio: ["ignore", "ignore", "inherit", "ipc"], serialization: "advanced", - env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }, + env: { ...process.env, ...options.env, ELECTRON_RUN_AS_NODE: "1" }, }); let alive = true; let pending: ReturnType> | undefined; diff --git a/docs/user/composer.md b/docs/user/composer.md index 6f435b51611f2..e225ed93dc841 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -207,9 +207,10 @@ through your selected environment and use API billing. They share the API keys s voice, then use the preview to try it. **Local model** reads replies on your selected environment, so the text never leaves it. -Download a model once from the same settings page. Supertonic 3 (330–360 MB) speaks 31 -languages and is fastest with a GPU. Pocket TTS (about 200 MB) speaks English and stays fast -on machines without one. Like dictation models, they reuse a copy already in the Hugging Face +Download a model once from the same settings page. Kokoro (about 220 MB) is the default, with +natural English voices plus Spanish, French, Hindi, Italian, and Portuguese. Supertonic 3 +(330–360 MB) speaks 31 languages and is fastest with a GPU. Pocket TTS (about 200 MB) speaks +English and stays fast on machines without one. Like dictation models, they reuse a copy already in the Hugging Face cache, and on web or desktop you can paste the path of a copy elsewhere and choose **Use existing**. Local models use the GPU through Metal on Apple silicon Macs and Vulkan on Windows and Linux, and run on macOS, Windows, and Linux with glibc 2.28 or newer. diff --git a/packages/audio-cpp/src/bindings.ts b/packages/audio-cpp/src/bindings.ts index 11ebebe25b4b6..421facee35534 100644 --- a/packages/audio-cpp/src/bindings.ts +++ b/packages/audio-cpp/src/bindings.ts @@ -91,6 +91,14 @@ export function bindAudioCpp(koffi: typeof Koffi, libraryPath: string): AudioCpp streamReset: lib.func("audiocpp_stream_reset", "int", [Session]), eventFree: lib.func("audiocpp_event_free", "void", [Event]), eventAsResult: lib.func("audiocpp_event_as_result", Result, [Event]), + namedAudioCount: lib.func("audiocpp_result_named_audio_count", "size_t", [Result]), + resultAudio: lib.func("audiocpp_result_audio", "int", [ + Result, + out("void *"), + out("size_t"), + out("int"), + out("int"), + ]), namedAudio: lib.func("audiocpp_result_named_audio", "int", [ Result, "size_t", @@ -206,21 +214,16 @@ export function bindAudioCpp(koffi: typeof Koffi, libraryPath: string): AudioCpp return undefined; } try { - const id: [string] = [""]; const samples: [unknown] = [null]; const frames: [number | bigint] = [0]; const sampleRate: [number] = [0]; const channels: [number] = [0]; + const result = native.eventAsResult(event[0]); + // Chunked families name each piece; families that generate in one pass do not. check( - native.namedAudio( - native.eventAsResult(event[0]), - 0, - id, - samples, - frames, - sampleRate, - channels, - ), + Number(native.namedAudioCount(result)) > 0 + ? native.namedAudio(result, 0, [""], samples, frames, sampleRate, channels) + : native.resultAudio(result, samples, frames, sampleRate, channels), "audio read", ); const length = Number(frames[0]) * channels[0]; diff --git a/packages/audio-cpp/src/index.ts b/packages/audio-cpp/src/index.ts index 4b4865067f3ff..a02ca0aff2862 100644 --- a/packages/audio-cpp/src/index.ts +++ b/packages/audio-cpp/src/index.ts @@ -5,4 +5,9 @@ export { type AudioCppModel, type AudioCppSynthesisRequest, } from "./bindings.ts"; -export { AUDIO_CPP_VERSION, audioCppRuntime, type AudioCppRuntime } from "./runtime.ts"; +export { + AUDIO_CPP_ESPEAK_DATA, + AUDIO_CPP_VERSION, + audioCppRuntime, + type AudioCppRuntime, +} from "./runtime.ts"; diff --git a/packages/audio-cpp/src/runtime.ts b/packages/audio-cpp/src/runtime.ts index fa3aaca3fa0d2..281a5bc1f6b90 100644 --- a/packages/audio-cpp/src/runtime.ts +++ b/packages/audio-cpp/src/runtime.ts @@ -1,5 +1,5 @@ /** A release of github.com/pingdotgg/audio.cpp, whose `T3 release` workflow builds these libraries. */ -export const AUDIO_CPP_VERSION = "t3-2026.11.16"; +export const AUDIO_CPP_VERSION = "t3-2026.11.17"; export type AudioCppRuntime = { readonly filename: string; @@ -39,49 +39,57 @@ const runtime = ( const RUNTIMES: Readonly> = { "darwin-arm64": runtime( "macos-arm64-metal.tar.gz", - 15_050_495, - "81ee4b878e26c8c7b3eb12f6c50c94e2db3e77916e2eadb180957e97838271e2", + 15_293_898, + "4f06e1d834e2e7a43fb9f257d561e946196a9e2459a8b4648cf36e24a0e5ac14", "libs/libaudiocpp.0.1.0.dylib", "metal", ), "darwin-x64": runtime( "macos-x64-cpu.tar.gz", - 16_205_261, - "94465d3a325d776198821f7216a52caa6db1f4f11fb20b5490f2789f7e7e54a6", + 16_460_460, + "02066f1ee9a7cad1a601d65cc6be3349ad570d9b9268c65e17b7cf88b706f10b", "libs/libaudiocpp.0.1.0.dylib", "cpu", ), "linux-x64": runtime( "linux-x64-vulkan.tar.gz", - 46_480_819, - "d6774bc02102fa554db246e2dbf30c452cbec7dfe7d33844b89c399d758d8d01", + 46_783_748, + "3b6ce18303f203eabc82997a2af14e6052f5aad2ea326e444973200a5fd908ca", "libs/libaudiocpp.so.0.1.0", "vulkan", "2.28", ), "linux-arm64": runtime( "linux-arm64-vulkan.tar.gz", - 40_185_132, - "6b03aebe87eb85f433faf3a0cd4e54ed7d45dde2654cf98ae8ac0eebfa2163a3", + 40_477_068, + "39c59b4ef06fe1ac8fd49fbdf14d3392515949d719ce1ebda5134a73a5c4fd10", "libs/libaudiocpp.so.0.1.0", "vulkan", "2.28", ), "win32-arm64": runtime( "windows-arm64-vulkan.zip", - 34_518_475, - "576729077a80984c24a5b54c5ca237b388e5d0d8b90b394f8463314fd38b1bfc", + 34_757_900, + "2e3692e2eab320d58056e38492d8fa2dc8e0de9699e156d783addae3c789c50c", "libs/audiocpp.dll", "vulkan", ), "win32-x64": runtime( "windows-x64-vulkan.zip", - 34_389_747, - "91780513f8c374e4736c27850a988f4205526488388698e24eaa322682c16471", + 34_618_677, + "25b3516d94d0f56b284689b3bf358b3f90e4f1a8ec8398c41ef5fa3806abbb1c", "libs/audiocpp.dll", "vulkan", ), }; +/** eSpeak-ng's phoneme tables and dictionaries for Kokoro; every library links eSpeak itself. */ +export const AUDIO_CPP_ESPEAK_DATA = { + filename: `audio-${AUDIO_CPP_VERSION}-espeak-ng-data.bin`, + url: `https://github.com/pingdotgg/audio.cpp/releases/download/${AUDIO_CPP_VERSION}/audio-${AUDIO_CPP_VERSION}-espeak-ng-data.bin`, + size: 18_383_744, + sha256: "59e581e5d0074112285592be38288da1e5e1f158b61ae236c99abbd6ed09e7c0", +}; + export const audioCppRuntime = (platform: string, architecture: string) => RUNTIMES[`${platform}-${architecture}`]; From 776125140bc38050a399ca5181b3991fe0a39f16 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 17 Nov 2026 16:03:10 -0600 Subject: [PATCH 28/33] feat(read-aloud): ElevenLabs voices and transcription, and mark the recommended local model ElevenLabs joins the cloud speech providers with one shared key: read-aloud streams its voices, listed by name, and dictation transcribes with Scribe. The default local model, Kokoro, shows a Recommended badge on web and mobile. Co-authored-by: Cursor --- .../features/settings/ReadAloudSection.tsx | 48 +++-- apps/server/src/serverSettings.test.ts | 16 +- .../sourceControlHostSecrets.test.ts | 7 +- apps/server/src/speech/CloudSpeech.test.ts | 191 ++++++++++-------- apps/server/src/speech/CloudSpeech.ts | 132 +++++++++++- apps/server/src/speech/synthesis.test.ts | 86 ++++++++ .../settings/ReadAloudSettingsSection.tsx | 49 +++-- .../settings/SpeechProviderIcon.tsx | 4 +- docs/user/composer.md | 2 +- docs/user/voice-input.md | 4 +- .../client-runtime/src/providerClients.ts | 7 + packages/contracts/src/readAloud.ts | 6 +- packages/contracts/src/settings.ts | 8 +- packages/contracts/src/speech.ts | 5 +- 14 files changed, 426 insertions(+), 139 deletions(-) diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index 6ffba1f1d9dee..a3c67cef63b3b 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -158,7 +158,10 @@ export function ReadAloudSection() { const voiceChoices = settings.provider === "system" ? voices.map((voice) => ({ id: voice.identifier, name: voice.name })) - : (selectedModel?.voices ?? []).map((voice) => ({ id: voice, name: voice })); + : (selectedModel?.voices ?? []).map((voice) => ({ + id: voice, + name: selectedModel?.voiceNames?.[voice] ?? voice, + })); return ( <> {environments.map((environment) => ( - {(["local", "openai", "xai", "openrouter"] as const).map((provider) => ( - { - change({ - provider: provider as SpeechSynthesisProvider, - environmentId: environment.environmentId, - model: "", - voice: "", - }); - setSheet(null); - }} - /> - ))} + {(["local", "openai", "xai", "openrouter", "elevenlabs"] as const).map( + (provider) => ( + { + change({ + provider: provider as SpeechSynthesisProvider, + environmentId: environment.environmentId, + model: "", + voice: "", + }); + setSheet(null); + }} + /> + ), + )} ))} @@ -379,6 +384,9 @@ export function ReadAloudSection() { { change({ model: model.id, voice: "" }); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 873649cb168f5..dd52c6258dad6 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1765,7 +1765,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" const hub = UsageLimitSourceId.make("hub"); const router = ProviderInstanceId.make("openrouter"); const withUsage = yield* serverSettings.updateSettings({ - cloudSpeechCredentials: { openai: usageReference, xai: "literal-fixture" }, + cloudSpeechCredentials: { + openai: usageReference, + xai: "literal-fixture", + elevenlabs: usageReference, + }, textGenerators: { [router]: { kind: "openaiCompatible", @@ -1823,6 +1827,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" openai: SECRET_REDACTED, xai: SECRET_REDACTED, openrouter: "", + elevenlabs: SECRET_REDACTED, }); assert.equal(legacy.sourceControlHosts.bitbucket?.accessToken, SECRET_REDACTED); assert.equal(legacy.usageLimitSources[hub]?.managementKey, SECRET_REDACTED); @@ -1853,6 +1858,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" openai: usageReference, xai: "literal-fixture", openrouter: "", + elevenlabs: usageReference, }); assert.deepEqual(echoed.easDeviceHosts[0]?.accessToken, easReference); assert.deepEqual(echoed.simlockDeviceHosts[0]?.agentToken, simlockReference); @@ -1938,7 +1944,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" "ghe.acme.test": work, }); assert.equal(removed.usageLimitSources[hub]?.managementKey, ""); - assert.deepEqual(removed.cloudSpeechCredentials, { openai: "", xai: work, openrouter: "" }); + assert.deepEqual(removed.cloudSpeechCredentials, { + openai: "", + xai: work, + openrouter: "", + elevenlabs: "", + }); assert.equal(removed.easDeviceHosts[0]?.accessToken, ""); assert.deepEqual(Object.keys(removed.secretProviders), ["work"]); }).pipe(Effect.provide(layerServerSettingsWithSecrets())), @@ -1951,6 +1962,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" "cloudSpeechCredentials.openai", "cloudSpeechCredentials.xai", "cloudSpeechCredentials.openrouter", + "cloudSpeechCredentials.elevenlabs", "easDeviceHosts.[].accessToken", "simlockDeviceHosts.[].agentToken", "usageLimitSources.*.managementKey", diff --git a/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts b/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts index 9f73b2512841c..3acd0ae2b7e8d 100644 --- a/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts +++ b/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts @@ -176,7 +176,12 @@ it.effect("reads a collected reference again once it is invalidated", () => resolver, Effect.succeed({ sourceControlHosts: hosts, - cloudSpeechCredentials: { openai: source("voice#key"), xai: "", openrouter: "" }, + cloudSpeechCredentials: { + openai: source("voice#key"), + xai: "", + openrouter: "", + elevenlabs: "", + }, usageLimitSources, textGenerators: {}, easDeviceHosts, diff --git a/apps/server/src/speech/CloudSpeech.test.ts b/apps/server/src/speech/CloudSpeech.test.ts index a42313c9bdcd5..cae8a92c71a07 100644 --- a/apps/server/src/speech/CloudSpeech.test.ts +++ b/apps/server/src/speech/CloudSpeech.test.ts @@ -12,91 +12,116 @@ import { expect, vi } from "vite-plus/test"; import * as ServerSettings from "../serverSettings.ts"; import * as CloudSpeech from "./CloudSpeech.ts"; -it.effect.each(["openai", "xai"] as const)("sends only to %s using its own saved key", (provider) => - Effect.gen(function* () { - const reference = { - provider: SecretProviderId.make("work"), - reference: "op://Work/Voice/key", - }; - let resolved: string | undefined; - let cached: string | undefined; - const read = vi.fn(() => Effect.sync(() => [(cached ??= resolved)])); - const upstream = vi.fn(async () => Response.json({ text: "hello" })); - const service = yield* CloudSpeech.CloudSpeech.pipe( - Effect.provide( - CloudSpeech.layer.pipe( - Layer.provide(NodeServices.layer), - Layer.provide(FetchHttpClient.layer), - Layer.provide(ServerSettings.ServerSettingsService.layerTest()), - Layer.provide( - Layer.mock(SecretResolver.SecretResolver)({ - read, - label: () => Effect.succeed("Work"), - invalidate: () => - Effect.sync(() => { - cached = undefined; - }), - }), +// ElevenLabs takes its key in its own header; the others take a bearer token. +const sentKey = (init: RequestInit | undefined) => { + const headers = new Headers(init?.headers); + return headers.get("xi-api-key") ?? headers.get("authorization")?.replace(/^Bearer /, ""); +}; + +it.effect.each(["openai", "xai", "elevenlabs"] as const)( + "sends only to %s using its own saved key", + (provider) => + Effect.gen(function* () { + const reference = { + provider: SecretProviderId.make("work"), + reference: "op://Work/Voice/key", + }; + let resolved: string | undefined; + let cached: string | undefined; + const read = vi.fn(() => Effect.sync(() => [(cached ??= resolved)])); + const upstream = vi.fn(async () => Response.json({ text: "hello" })); + const service = yield* CloudSpeech.CloudSpeech.pipe( + Effect.provide( + CloudSpeech.layer.pipe( + Layer.provide(NodeServices.layer), + Layer.provide(FetchHttpClient.layer), + Layer.provide(ServerSettings.ServerSettingsService.layerTest()), + Layer.provide( + Layer.mock(SecretResolver.SecretResolver)({ + read, + label: () => Effect.succeed("Work"), + invalidate: () => + Effect.sync(() => { + cached = undefined; + }), + }), + ), ), ), - ), - ); - const transcribe = (pcm = new Uint8Array(new Float32Array([0, 0.5]).buffer)) => - service - .transcribe(provider, pcm, { - ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, - speechLanguage: "en", - speechCustomWords: [{ term: "T3 Code", aliases: [] }], - }) - .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)); - yield* service.setKey(provider === "openai" ? "xai" : "openai", Redacted.make("other")); - expect((yield* Effect.flip(transcribe()))._tag).toBe("CloudSpeechError"); - yield* service.setKey(provider, Redacted.make("chosen")); - expect(yield* service.configured).toEqual({ openai: true, xai: true, openrouter: false }); - yield* Effect.flip(transcribe(new Uint8Array(3))); - expect(upstream).not.toHaveBeenCalled(); - expect(yield* transcribe()).toBe("hello"); - const [url, init] = upstream.mock.calls[0]!; - expect(String(url)).toBe( - { - openai: "https://api.openai.com/v1/audio/transcriptions", - xai: "https://api.x.ai/v1/stt", - }[provider], - ); - expect(init?.redirect).toBe("error"); - expect(new Headers(init?.headers).get("authorization")).toBe("Bearer chosen"); - const form = init?.body as FormData; - expect(form.get("model")).toBe( - provider === "openai" ? "gpt-transcribe" : "grok-voice-transcribe-2.0", - ); - expect(form.getAll(provider === "openai" ? "keywords[]" : "keyterm")).toEqual(["T3 Code"]); - expect(form.get(provider === "openai" ? "languages[]" : "language")).toBe("en"); - expect([...form.keys()].at(-1)).toBe("file"); - const wav = new DataView(yield* Effect.promise(() => (form.get("file") as Blob).arrayBuffer())); - expect(wav.getUint32(24, true)).toBe(16_000); - expect(wav.getInt16(46, true)).toBe(16384); - upstream.mockResolvedValueOnce(new Response("sensitive upstream diagnostic", { status: 401 })); - expect(yield* Effect.flip(transcribe())).toMatchObject({ provider, reason: "rejected-key" }); - yield* service.setKey(provider, null); - expect((yield* service.configured)[provider]).toBe(false); - yield* Effect.flip(transcribe()); - expect(upstream).toHaveBeenCalledTimes(2); - yield* service.setKey(provider, reference); - expect((yield* service.configured)[provider]).toBe(true); - expect(read).not.toHaveBeenCalled(); - resolved = "resolved-fixture"; - expect(yield* transcribe()).toBe("hello"); - expect(read).toHaveBeenCalledWith([reference]); - expect(new Headers(upstream.mock.calls[2]?.[1]?.headers).get("authorization")).toBe( - "Bearer resolved-fixture", - ); - resolved = undefined; - expect(yield* Effect.flip(transcribe())).toMatchObject({ - provider, - reason: "unreadable-key", - }); - expect(upstream).toHaveBeenCalledTimes(3); - }), + ); + const transcribe = (pcm = new Uint8Array(new Float32Array([0, 0.5]).buffer)) => + service + .transcribe(provider, pcm, { + ...DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS, + speechLanguage: "en", + speechCustomWords: [{ term: "T3 Code", aliases: [] }], + }) + .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)); + yield* service.setKey(provider === "openai" ? "xai" : "openai", Redacted.make("other")); + expect((yield* Effect.flip(transcribe()))._tag).toBe("CloudSpeechError"); + yield* service.setKey(provider, Redacted.make("chosen")); + expect(yield* service.configured).toEqual({ + openai: true, + xai: provider !== "elevenlabs", + openrouter: false, + elevenlabs: provider === "elevenlabs", + }); + yield* Effect.flip(transcribe(new Uint8Array(3))); + expect(upstream).not.toHaveBeenCalled(); + expect(yield* transcribe()).toBe("hello"); + const [url, init] = upstream.mock.calls[0]!; + expect(String(url)).toBe( + { + openai: "https://api.openai.com/v1/audio/transcriptions", + xai: "https://api.x.ai/v1/stt", + elevenlabs: "https://api.elevenlabs.io/v1/speech-to-text", + }[provider], + ); + expect(init?.redirect).toBe("error"); + expect(sentKey(init)).toBe("chosen"); + if (provider === "elevenlabs") + expect(new Headers(init?.headers).has("authorization")).toBe(false); + const form = init?.body as FormData; + const fields = { + openai: { model: "model", keyterms: "keywords[]", language: "languages[]" }, + xai: { model: "model", keyterms: "keyterm", language: "language" }, + elevenlabs: { model: "model_id", keyterms: "keyterms", language: "language_code" }, + }[provider]; + expect(form.get(fields.model)).toBe( + { openai: "gpt-transcribe", xai: "grok-voice-transcribe-2.0", elevenlabs: "scribe_v3" }[ + provider + ], + ); + expect(form.getAll(fields.keyterms)).toEqual(["T3 Code"]); + expect(form.get(fields.language)).toBe("en"); + expect([...form.keys()].at(-1)).toBe("file"); + const wav = new DataView( + yield* Effect.promise(() => (form.get("file") as Blob).arrayBuffer()), + ); + expect(wav.getUint32(24, true)).toBe(16_000); + expect(wav.getInt16(46, true)).toBe(16384); + upstream.mockResolvedValueOnce( + new Response("sensitive upstream diagnostic", { status: 401 }), + ); + expect(yield* Effect.flip(transcribe())).toMatchObject({ provider, reason: "rejected-key" }); + yield* service.setKey(provider, null); + expect((yield* service.configured)[provider]).toBe(false); + yield* Effect.flip(transcribe()); + expect(upstream).toHaveBeenCalledTimes(2); + yield* service.setKey(provider, reference); + expect((yield* service.configured)[provider]).toBe(true); + expect(read).not.toHaveBeenCalled(); + resolved = "resolved-fixture"; + expect(yield* transcribe()).toBe("hello"); + expect(read).toHaveBeenCalledWith([reference]); + expect(sentKey(upstream.mock.calls[2]?.[1])).toBe("resolved-fixture"); + resolved = undefined; + expect(yield* Effect.flip(transcribe())).toMatchObject({ + provider, + reason: "unreadable-key", + }); + expect(upstream).toHaveBeenCalledTimes(3); + }), ); it.effect.each([ diff --git a/apps/server/src/speech/CloudSpeech.ts b/apps/server/src/speech/CloudSpeech.ts index af893c95d872a..91a2d5bd6e806 100644 --- a/apps/server/src/speech/CloudSpeech.ts +++ b/apps/server/src/speech/CloudSpeech.ts @@ -89,11 +89,41 @@ const decodeOpenRouterSynthesisCatalog = Schema.decodeUnknownEffect( ), ); +const decodeElevenLabsModels = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Array( + Schema.Struct({ + model_id: Schema.String, + name: Schema.optionalKey(Schema.String), + can_do_text_to_speech: Schema.optionalKey(Schema.Boolean), + }), + ), + ), +); + +const decodeElevenLabsVoices = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + voices: Schema.Array(Schema.Struct({ voice_id: Schema.String, name: Schema.String })), + }), + ), +); + const endpoints = { openai: { url: "https://api.openai.com/v1/audio/transcriptions", model: "gpt-transcribe" }, xai: { url: "https://api.x.ai/v1/stt", model: "grok-voice-transcribe-2.0" }, openrouter: { url: "https://openrouter.ai/api/v1/audio/transcriptions" }, + elevenlabs: { url: "https://api.elevenlabs.io/v1/speech-to-text", model: "scribe_v3" }, }; +const ELEVENLABS_API = "https://api.elevenlabs.io"; +const ELEVENLABS_DEFAULT_MODEL = "eleven_multilingual_v2"; +// George, a premade voice every account has, as in ElevenLabs' own examples. +const ELEVENLABS_DEFAULT_VOICE = "JBFqnCBsd6RMkjVDRZzb"; +// ElevenLabs authenticates with its own header rather than a bearer token. +const authorize = (provider: CloudSpeechProvider, key: string) => + provider === "elevenlabs" + ? HttpClientRequest.setHeader("xi-api-key", key) + : HttpClientRequest.bearerToken(Redacted.make(key)); const OPENROUTER_CATALOG_URL = "https://openrouter.ai/api/v1/models?output_modalities=transcription&zdr=true"; const isApiKey = Schema.is(CloudSpeechApiKey); @@ -196,6 +226,23 @@ function wave(samples: Float32Array) { return buffer; } +function elevenLabsAudioBody( + audio: ArrayBuffer, + language: string, + options: SpeechTranscriptionOptions, +) { + const form = new FormData(); + form.set("model_id", endpoints.elevenlabs.model); + if (language !== "auto") form.set("language_code", language); + // Scribe accepts key terms of up to 50 characters and five words. + for (const { term } of options.speechCustomWords) { + if (term.length <= 50 && term.split(/\s+/).length <= 5) form.append("keyterms", term); + } + form.set("tag_audio_events", "false"); + form.set("file", new Blob([audio], { type: "audio/wav" }), "dictation.wav"); + return HttpClientRequest.bodyFormData(form); +} + function audioBody( provider: "openai" | "xai", audio: ArrayBuffer, @@ -280,10 +327,11 @@ export const layer = Layer.effect( return key; }); const configured = credentials.pipe( - Effect.map(({ openai, xai, openrouter }) => ({ + Effect.map(({ openai, xai, openrouter, elevenlabs }) => ({ openai: Boolean(openai), xai: Boolean(xai), openrouter: Boolean(openrouter), + elevenlabs: Boolean(elevenlabs), })), ); const execute = (request: HttpClientRequest.HttpClientRequest) => @@ -321,19 +369,58 @@ export const layer = Layer.effect( const loadSynthesisModels = Effect.fn("CloudSpeech.synthesisModels")( function* (provider: CloudSpeechProvider) { if (provider === "openai") return { models: openAiSpeechModels }; - if (provider === "xai") { - const source = (yield* credentials).xai; + if (provider === "xai" || provider === "elevenlabs") { + const source = (yield* credentials)[provider]; const key = yield* resolveKey( source, (reason, cause) => new SpeechSynthesisError({ provider, reason, cause }), ); - const current = (yield* credentials).xai; + const current = (yield* credentials)[provider]; if (!source || !current || !sameCredential(source, current)) return yield* new SpeechSynthesisError({ provider, reason: "key-changed" }); const unavailable = (cause?: unknown) => isSynthesisError(cause) ? cause : new SpeechSynthesisError({ provider, reason: "unavailable", cause }); + const get = Effect.fn("CloudSpeech.catalogRequest")(function* (url: string) { + const response = yield* execute( + HttpClientRequest.get(url).pipe(authorize(provider, key)), + ).pipe(Effect.mapError(unavailable)); + if (response.status !== 200) + return yield* new SpeechSynthesisError({ + provider, + reason: synthesisErrorReason(response.status), + }); + return new TextDecoder().decode( + yield* readSynthesisBody(response, provider, 1024 * 1024), + ); + }); + if (provider === "elevenlabs") { + const [models, { voices }] = yield* Effect.all([ + get(`${ELEVENLABS_API}/v1/models`).pipe( + Effect.flatMap(decodeElevenLabsModels), + Effect.mapError(unavailable), + ), + get(`${ELEVENLABS_API}/v2/voices?page_size=100`).pipe( + Effect.flatMap(decodeElevenLabsVoices), + Effect.mapError(unavailable), + ), + ]); + const voiceIds = voices.map((voice) => voice.voice_id); + const voiceNames = Object.fromEntries( + voices.map((voice) => [voice.voice_id, voice.name]), + ); + return { + models: models + .filter((model) => model.can_do_text_to_speech !== false) + .map((model) => ({ + id: model.model_id, + name: model.name || model.model_id, + voices: voiceIds, + voiceNames, + })), + }; + } const response = yield* execute( HttpClientRequest.get("https://api.x.ai/v1/tts/voices").pipe( HttpClientRequest.bearerToken(Redacted.make(key)), @@ -473,6 +560,31 @@ export const layer = Layer.effect( }, errorReason: synthesisErrorReason, }, + elevenlabs: { + catalog: { + defaultModel: ELEVENLABS_DEFAULT_MODEL, + apiKeyProvider: "elevenlabs", + supportsModelSelection: true, + supportsVoiceSelection: true, + // Eleven v4 has no speed setting, so players speed up every model alike. + speedAppliedByProvider: false, + }, + models: loadSynthesisModels("elevenlabs"), + request: (input) => + Effect.succeed( + HttpClientRequest.post( + `${ELEVENLABS_API}/v1/text-to-speech/${encodeURIComponent( + input.voice || ELEVENLABS_DEFAULT_VOICE, + )}/stream?output_format=mp3_44100_64`, + ).pipe( + HttpClientRequest.bodyJsonUnsafe({ + text: input.text, + model_id: input.model || ELEVENLABS_DEFAULT_MODEL, + }), + ), + ), + errorReason: synthesisErrorReason, + }, } satisfies Record; const synthesisModels = Effect.fn("CloudSpeech.synthesisCatalog")(function* ( provider: CloudSpeechProvider, @@ -508,9 +620,9 @@ export const layer = Layer.effect( const current = (yield* credentials)[provider]; if (!current || !source || !sameCredential(source, current)) return yield* new SpeechSynthesisError({ provider, reason: "key-changed" }); - const response = yield* execute( - synthesisRequest.pipe(HttpClientRequest.bearerToken(Redacted.make(key))), - ).pipe(Effect.mapError(unavailable)); + const response = yield* execute(synthesisRequest.pipe(authorize(provider, key))).pipe( + Effect.mapError(unavailable), + ); if (response.status < 200 || response.status >= 300) return yield* new SpeechSynthesisError({ provider, @@ -589,10 +701,12 @@ export const layer = Layer.effect( ); const audio = wave(samples); const request = HttpClientRequest.post(endpoints[provider].url).pipe( - HttpClientRequest.bearerToken(Redacted.make(key)), + authorize(provider, key), provider === "openrouter" ? openRouterBody(model!, audio, language) - : audioBody(provider, audio, language, options), + : provider === "elevenlabs" + ? elevenLabsAudioBody(audio, language, options) + : audioBody(provider, audio, language, options), ); const unavailable = () => new CloudSpeechError({ provider, reason: "unavailable" }); // A catalog fetch or vault lookup may have outlived the credential it started with. diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index 4ba0d2d541bbc..a331afd36b577 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -97,6 +97,92 @@ it.each([ }, ); +it.effect("lists ElevenLabs voices by name and sends its key only in its own header", () => + Effect.gen(function* () { + const upstream = vi.fn(async (url) => + String(url).includes("/v2/voices") + ? Response.json({ voices: [{ voice_id: "voice-123", name: "Rachel" }] }) + : String(url).endsWith("/v1/models") + ? Response.json([ + { + model_id: "eleven_multilingual_v2", + name: "Multilingual v2", + can_do_text_to_speech: true, + }, + { + model_id: "eleven_english_sts_v2", + name: "Speech to speech", + can_do_text_to_speech: false, + }, + ]) + : new Response(new Uint8Array([73, 68, 51, 1]), { + headers: { "content-type": "audio/mpeg" }, + }), + ); + yield* Effect.gen(function* () { + const service = yield* CloudSpeech.CloudSpeech; + const synthesize = (request: Parameters[1]) => + service.stream("elevenlabs", request).pipe( + Stream.runCollect, + Effect.map((chunks) => Uint8Array.from(chunks.flatMap((chunk) => [...chunk]))), + ); + const request = { + text: "Read this reply.", + model: "", + voice: "", + speed: 1.25, + language: "en", + }; + expect(yield* Effect.flip(synthesize(request))).toMatchObject({ reason: "missing-key" }); + expect(upstream).not.toHaveBeenCalled(); + yield* service.setKey("elevenlabs", Redacted.make("speech-key")); + expect(yield* service.synthesisModels("elevenlabs")).toMatchObject({ + apiKeyProvider: "elevenlabs", + defaultModel: "eleven_multilingual_v2", + speedAppliedByProvider: false, + models: [ + { + id: "eleven_multilingual_v2", + name: "Multilingual v2", + voices: ["voice-123"], + voiceNames: { "voice-123": "Rachel" }, + }, + ], + }); + expect([...(yield* synthesize(request))]).toEqual([73, 68, 51, 1]); + expect([ + ...(yield* synthesize({ ...request, voice: "voice-123", model: "eleven_v3" })), + ]).toEqual([73, 68, 51, 1]); + for (const [url, init] of upstream.mock.calls) { + expect(String(url).startsWith("https://api.elevenlabs.io/")).toBe(true); + expect(new Headers(init?.headers).get("xi-api-key")).toBe("speech-key"); + expect(new Headers(init?.headers).has("authorization")).toBe(false); + } + const [defaultUrl, defaultInit] = upstream.mock.calls.at(-2)!; + expect(String(defaultUrl)).toBe( + "https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_44100_64", + ); + expect(JSON.parse(String(defaultInit?.body))).toEqual({ + text: "Read this reply.", + model_id: "eleven_multilingual_v2", + }); + const [chosenUrl, chosenInit] = upstream.mock.calls.at(-1)!; + expect(String(chosenUrl)).toContain("/v1/text-to-speech/voice-123/stream"); + expect(JSON.parse(String(chosenInit?.body)).model_id).toBe("eleven_v3"); + }).pipe( + Effect.provide( + CloudSpeech.layer.pipe( + Layer.provide(NodeServices.layer), + Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()), + Layer.provide(FetchHttpClient.layer), + Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})), + ), + ), + Effect.provideService(FetchHttpClient.Fetch, upstream), + ); + }), +); + it.effect.each(["openai", "xai", "openrouter"] as const)( "synthesizes with %s without leaking keys to another destination", (provider) => diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 74b2a2022e498..6d38dbea0bb38 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -25,7 +25,8 @@ import { useEnvironments } from "../../state/environments"; import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; import { readAloudController } from "../../speech/readAloud"; -import { CheckIcon, DownloadIcon, XIcon } from "lucide-react"; +import { CheckIcon, DownloadIcon, StarIcon, XIcon } from "lucide-react"; +import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Switch } from "../ui/switch"; @@ -129,6 +130,7 @@ function LocalSpeechModel({ prepared, model, selected, + recommended, refreshing, onSelect, onChanged, @@ -136,6 +138,7 @@ function LocalSpeechModel({ prepared: PreparedConnection; model: SpeechSynthesisCatalog["models"][number]; selected: boolean; + recommended: boolean; /** A catalog request is in flight; polling waits for it rather than aborting it. */ refreshing: boolean; onSelect: () => void; @@ -181,7 +184,17 @@ function LocalSpeechModel({ : Math.min(100, (install.downloaded / install.size) * 100); return ( + {model.name} + {recommended && ( + + + Recommended + + )} + + } description={ <> {model.description}{" "} @@ -396,12 +409,13 @@ export function ReadAloudSettingsSection() { ); return () => abort.abort(); }, [prepared, remote, settings.provider, catalogKey, catalogVersion]); + const modelEntry = catalog.models.find((entry) => entry.id === model); const voices = settings.provider === "system" ? systemVoices.map((voice) => ({ id: voice.voiceURI, name: voice.name })) - : (catalog.models.find((entry) => entry.id === model)?.voices ?? []).map((voice) => ({ + : (modelEntry?.voices ?? []).map((voice) => ({ id: voice, - name: voice, + name: modelEntry?.voiceNames?.[voice] ?? voice, })); const source = remote ? `${settings.provider}:${settings.environmentId}` : settings.provider; const selectedEnvironment = environments.find( @@ -474,18 +488,20 @@ export function ReadAloudSettingsSection() { {environments.map((environment) => ( Via {environment.label} - {(["local", "openai", "xai", "openrouter"] as const).map((provider) => ( - - - - {READ_ALOUD_LABELS[provider]} - - - ))} + {(["local", "openai", "xai", "openrouter", "elevenlabs"] as const).map( + (provider) => ( + + + + {READ_ALOUD_LABELS[provider]} + + + ), + )} ))} {remote && !selectedEnvironment && ( @@ -513,6 +529,7 @@ export function ReadAloudSettingsSection() { prepared={prepared} model={entry} selected={entry.id === model} + recommended={entry.id === catalog.defaultModel} refreshing={catalogState.version !== catalogVersion} onSelect={() => change({ model: entry.id, voice: "" })} onChanged={refreshCatalog} diff --git a/apps/web/src/components/settings/SpeechProviderIcon.tsx b/apps/web/src/components/settings/SpeechProviderIcon.tsx index 5220eb8631022..99eee76939444 100644 --- a/apps/web/src/components/settings/SpeechProviderIcon.tsx +++ b/apps/web/src/components/settings/SpeechProviderIcon.tsx @@ -1,4 +1,4 @@ -import { openRouterIcon } from "@t3tools/client-runtime/provider-clients"; +import { elevenLabsIcon, openRouterIcon } from "@t3tools/client-runtime/provider-clients"; import { CLOUD_SPEECH_LABELS, READ_ALOUD_LABELS, @@ -20,6 +20,8 @@ export function SpeechProviderIcon({ if (provider === "local") return ; if (provider === "openrouter") return ; + if (provider === "elevenlabs") + return ; return ( (value === "chatgpt" ? ("off" as const) : value), encode: (value) => value, @@ -95,6 +97,8 @@ export const SpeechSynthesisCatalog = Schema.Struct({ name: Schema.String, description: Schema.optionalKey(Schema.String), voices: Schema.Array(Schema.String), + /** Display names for voices whose ids are opaque. */ + voiceNames: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), /** Present for models that run on the environment and must be downloaded first. */ install: Schema.optionalKey(SpeechSynthesisModelInstall), /** Overrides the catalog's `speedAppliedByProvider` for this model. */ diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index f44b50b58be5f..a2c732b9a8398 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -392,7 +392,7 @@ export const VoiceTranscriptionDestination = Schema.Union([ Schema.Struct({ kind: Schema.Literal("cloud"), environmentId: EnvironmentId, - provider: Schema.Literals(["openai", "xai"]), + provider: Schema.Literals(["openai", "xai", "elevenlabs"]), }), Schema.Struct({ kind: Schema.Literal("cloud"), @@ -1357,6 +1357,7 @@ export const CloudSpeechCredentials = Schema.Struct({ openai: CloudSpeechCredential, xai: CloudSpeechCredential, openrouter: CloudSpeechCredential, + elevenlabs: CloudSpeechCredential, }); export const ServerSettings = Schema.Struct({ @@ -1393,7 +1394,9 @@ export const ServerSettings = Schema.Struct({ enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), cloudSpeechCredentials: CloudSpeechCredentials.pipe( - Schema.withDecodingDefault(Effect.succeed({ openai: "", xai: "", openrouter: "" })), + Schema.withDecodingDefault( + Effect.succeed({ openai: "", xai: "", openrouter: "", elevenlabs: "" }), + ), ), speechModelId: Schema.String.pipe( Schema.withDecodingDefault(Effect.succeed("handy-computer/parakeet-unified-en-0.6b-gguf")), @@ -1855,6 +1858,7 @@ export const ServerSettingsPatch = Schema.Struct({ openai: Schema.optionalKey(SettingsSecretValue), xai: Schema.optionalKey(SettingsSecretValue), openrouter: Schema.optionalKey(SettingsSecretValue), + elevenlabs: Schema.optionalKey(SettingsSecretValue), }), ), speechModelId: Schema.optionalKey(Schema.String), diff --git a/packages/contracts/src/speech.ts b/packages/contracts/src/speech.ts index ff3362f67fc0c..06da7202153ab 100644 --- a/packages/contracts/src/speech.ts +++ b/packages/contracts/src/speech.ts @@ -8,23 +8,26 @@ export const CloudSpeechApiKey = TrimmedNonEmptyString.check( Schema.isPattern(/^(?![a-z][a-z\d+.-]*:\/\/)[!-~]+$/i), ); -export const CloudSpeechProvider = Schema.Literals(["openai", "xai", "openrouter"]); +export const CloudSpeechProvider = Schema.Literals(["openai", "xai", "openrouter", "elevenlabs"]); export type CloudSpeechProvider = typeof CloudSpeechProvider.Type; export const CLOUD_SPEECH_LABELS = { openai: "OpenAI", xai: "Grok Voice Transcribe", openrouter: "OpenRouter", + elevenlabs: "ElevenLabs", } as const; export const CLOUD_SPEECH_PROVIDER_NAMES = { openai: "OpenAI", xai: "xAI", openrouter: "OpenRouter", + elevenlabs: "ElevenLabs", } as const; /** Servers that predate OpenRouter report only the first two providers. */ export const CloudSpeechKeys = Schema.Struct({ openai: Schema.Boolean, xai: Schema.Boolean, openrouter: Schema.optionalKey(Schema.Boolean), + elevenlabs: Schema.optionalKey(Schema.Boolean), }); export type CloudSpeechKeys = typeof CloudSpeechKeys.Type; From d05d1c52dc9a48bee62ebbd7e39fd3a2d4979fb5 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 18 Nov 2026 01:06:38 -0600 Subject: [PATCH 29/33] fix(read-aloud): settings match dictation's destination menu and model list Local models are chosen by environment and listed in one Models row, and cloud providers sit under Cloud via the environment, as in Transcribe with. Co-authored-by: Cursor --- .../features/settings/ReadAloudSection.tsx | 81 +++-- .../settings/ReadAloudSettingsSection.tsx | 329 ++++++++++-------- 2 files changed, 238 insertions(+), 172 deletions(-) diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index a3c67cef63b3b..f18b4040c8813 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -6,12 +6,12 @@ import * as Speech from "expo-speech"; import { ScrollView, TextInput, View } from "react-native"; import { AuthSettingsWriteScope, + CloudSpeechProvider, DEFAULT_READ_ALOUD_SETTINGS, READ_ALOUD_LABELS, EMPTY_SPEECH_SYNTHESIS_CATALOG, type ReadAloudSettings, type SpeechSynthesisCatalog, - type SpeechSynthesisProvider, } from "@t3tools/contracts"; import { cancelSpeechSynthesisModelDownload, @@ -162,6 +162,9 @@ export function ReadAloudSection() { id: voice, name: selectedModel?.voiceNames?.[voice] ?? voice, })); + const providerEnvironment = environments.find( + (environment) => environment.environmentId === settings.environmentId, + ); return ( <> { setSheet("source"); }} @@ -352,29 +361,53 @@ export function ReadAloudSection() { /> ))} + {environments.length > 0 && ( + + {environments.map((environment) => ( + { + change({ + provider: "local", + environmentId: environment.environmentId, + model: "", + voice: "", + }); + setSheet(null); + }} + /> + ))} + + )} {environments.map((environment) => ( - - {(["local", "openai", "xai", "openrouter", "elevenlabs"] as const).map( - (provider) => ( - { - change({ - provider: provider as SpeechSynthesisProvider, - environmentId: environment.environmentId, - model: "", - voice: "", - }); - setSheet(null); - }} - /> - ), - )} + + {CloudSpeechProvider.literals.map((provider) => ( + { + change({ + provider, + environmentId: environment.environmentId, + model: "", + voice: "", + }); + setSheet(null); + }} + /> + ))} ))} diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 6d38dbea0bb38..94ee9ce1aecf8 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -11,11 +11,11 @@ import { } from "@t3tools/client-runtime/voice-input"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { + CloudSpeechProvider, AuthFilesystemReadScope, AuthSettingsWriteScope, READ_ALOUD_LABELS, EMPTY_SPEECH_SYNTHESIS_CATALOG, - type CloudSpeechProvider, type ReadAloudSettings, type SpeechSynthesisCatalog, type SpeechSynthesisProvider, @@ -25,7 +25,15 @@ import { useEnvironments } from "../../state/environments"; import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; import { readAloudController } from "../../speech/readAloud"; -import { CheckIcon, DownloadIcon, StarIcon, XIcon } from "lucide-react"; +import { + CheckIcon, + DownloadIcon, + MonitorIcon, + StarIcon, + Trash2Icon, + UnlinkIcon, + XIcon, +} from "lucide-react"; import { Badge } from "../ui/badge"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -183,104 +191,104 @@ function LocalSpeechModel({ ? 0 : Math.min(100, (install.downloaded / install.size) * 100); return ( - - {model.name} - {recommended && ( - - - Recommended - - )} - - } - description={ - <> - {model.description}{" "} - {install.state === "installed" - ? `Installed on the selected environment (${formatSize(install.size)}).` - : `${formatSize(install.size)} download.`} +
+
+
+
+ {model.name} + {recommended && ( + + + Recommended + + )} +
+

+ {model.description} {formatSize(install.size)} + {install.state === "installed" ? "." : " download."} +

{install.linkedFrom && ( - +

Using your file at {install.linkedFrom} - +

)} {downloading && ( - - +
- - - +
+

{install.state === "verifying" ? "Verifying download…" : `${Math.round(progress)}% downloaded`} - - +

+
)} - {error && {error}} - - } - control={ - downloading ? ( - - ) : install.state === "installed" ? ( -
- {selected ? ( - - ) : ( - - )} + {error && ( +

+ {error} +

+ )} +
+
+ {downloading ? ( + + ) : install.state === "downloadable" ? ( + ) : selected ? ( + + ) : ( + + )} + {install.state === "installed" && ( + -
- ) : ( - - ) - } - /> + )} +
+
+ ); } @@ -299,47 +307,41 @@ function LocalSpeechModelLink({ const [error, setError] = useState(""); if (!canManage || !canReadFiles) return null; return ( - - Already downloaded one of these models elsewhere on this environment? Paste the file or - folder path to use it in place. - {error && {error}} - - } +
{ + event.preventDefault(); + setLinking(true); + setError(""); + void runEnvironmentSpeech(linkSpeechSynthesisModels(prepared, path)) + .then( + () => setPath(""), + () => setError("No speech model file was found at that path."), + ) + .finally(() => { + setLinking(false); + onChanged(); + }); + }} > - { - event.preventDefault(); - setLinking(true); - setError(""); - void runEnvironmentSpeech(linkSpeechSynthesisModels(prepared, path)) - .then( - () => setPath(""), - () => setError("No speech model file was found at that path."), - ) - .finally(() => { - setLinking(false); - onChanged(); - }); - }} - > -
- setPath(event.target.value)} - /> -
- -
-
+
+ setPath(event.target.value)} + /> + {error && ( +

+ {error} +

+ )} +
+ + ); } @@ -456,13 +458,19 @@ export function ReadAloudSettingsSection() { > - + {settings.provider === "local" ? ( + + ) : ( + + )} - {READ_ALOUD_LABELS[settings.provider]} - {remote && ( + {settings.provider === "local" + ? (selectedEnvironment?.label ?? "Chosen environment (unavailable)") + : READ_ALOUD_LABELS[settings.provider]} + {remote && settings.provider !== "local" && ( - {" "} - via {selectedEnvironment?.label ?? "unavailable environment"} + {" via "} + {selectedEnvironment?.label ?? "unavailable environment"} )} @@ -485,23 +493,37 @@ export function ReadAloudSettingsSection() { + {environments.length > 0 && ( + + On an environment + {environments.map((environment) => ( + + + + {environment.label} + + + ))} + + )} {environments.map((environment) => ( - Via {environment.label} - {(["local", "openai", "xai", "openrouter", "elevenlabs"] as const).map( - (provider) => ( - - - - {READ_ALOUD_LABELS[provider]} - - - ), - )} + Cloud via {environment.label} + {CloudSpeechProvider.literals.map((provider) => ( + + + + {READ_ALOUD_LABELS[provider]} + + + ))} ))} {remote && !selectedEnvironment && ( @@ -522,21 +544,32 @@ export function ReadAloudSettingsSection() { onSaved={() => setCatalogVersion((value) => value + 1)} /> )} - {prepared && - localModels.map((entry) => ( - change({ model: entry.id, voice: "" })} - onChanged={refreshCatalog} - /> - ))} - {prepared && localModels.some((entry) => entry.install?.state === "downloadable") && ( - + {prepared && localModels.length > 0 && ( + +
+ {localModels.map((entry) => ( + change({ model: entry.id, voice: "" })} + onChanged={refreshCatalog} + /> + ))} +
+ +
)} {remote && error && (

From f38e01ee0ccc63722c4f592c21a348007e6ed43a Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 18 Nov 2026 02:07:16 -0600 Subject: [PATCH 30/33] fix(read-aloud): hosted providers are set up in a key dialog, like dictation's Choosing OpenAI, Grok TTS, OpenRouter, or ElevenLabs opens a dialog that saves the shared key and only then switches read aloud; a key button reopens it. Missing keys and catalog failures show in the provider row, and model and voice controls appear only once the provider's catalog has loaded. Co-authored-by: Cursor --- .../features/settings/ReadAloudSection.tsx | 19 +- .../CloudVoiceConfiguration.browser.test.tsx | 66 ++-- .../settings/CloudVoiceConfiguration.tsx | 2 +- .../settings/ReadAloudKeyDialog.tsx | 263 +++++++++++++ .../settings/ReadAloudSettingsSection.tsx | 372 +++++++++--------- 5 files changed, 498 insertions(+), 224 deletions(-) create mode 100644 apps/web/src/components/settings/ReadAloudKeyDialog.tsx diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index f18b4040c8813..ced9f7e8dae52 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -186,14 +186,17 @@ export function ReadAloudSection() { /> {settings.provider !== "off" && ( <> - {settings.provider !== "system" && catalog.supportsModelSelection && ( - setSheet("model")} - /> - )} - {(settings.provider === "system" || catalog.supportsVoiceSelection) && ( + {settings.provider !== "system" && + catalog.supportsModelSelection && + catalog.models.length > 0 && ( + setSheet("model")} + /> + )} + {(settings.provider === "system" || + (catalog.supportsVoiceSelection && catalog.models.length > 0)) && ( { - let resolveKeys: (response: Response) => void = () => {}; - const keys = new Promise((resolve) => { - resolveKeys = resolve; +it("confirms a read-aloud provider in its key dialog, after the key lookup", async () => { + let finishLookup: () => void = () => {}; + const lookup = new Promise((resolve) => { + finishLookup = resolve; }); + const writes: unknown[] = []; const previous = getClientSettings().readAloud; - await updateClientSettings({ - readAloud: { ...DEFAULT_READ_ALOUD_SETTINGS, provider: "xai", environmentId: id }, - }); + await updateClientSettings({ readAloud: DEFAULT_READ_ALOUD_SETTINGS }); try { await withVoicePanel( - (url) => { - if (url.pathname === "/api/voice/cloud/keys") return keys; + (url, request, init) => { + if (url.pathname === "/api/voice/cloud/keys") + return lookup.then(() => Response.json({ openai: false, xai: false, openrouter: false })); if (url.pathname === "/api/voice/cloud/xai/key") - return Promise.resolve(new Response(null, { status: 204 })); + return new Request(request, init).json().then((body) => { + writes.push(body); + return new Response(null, { status: 204 }); + }); if (url.pathname === "/api/voice/synthesis/xai/models") return Promise.resolve( Response.json({ @@ -300,18 +303,28 @@ it("waits for the read-aloud key lookup before allowing a save", async () => { return null; }, async (screen) => { - await screen.getByRole("textbox", { name: "Read-aloud API key" }).fill("test-speech-key"); - const save = screen.getByRole("button", { name: "Save", exact: true }); - await expect.element(save).toBeDisabled(); + const provider = screen.getByRole("combobox", { name: "Read-aloud provider" }); + const dialog = page.getByRole("dialog"); + await provider.click(); + await page.getByRole("option", { name: "Grok TTS via Laptop" }).click(); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect.element(dialog).not.toBeInTheDocument(); + await expect.element(provider).toHaveTextContent("Off"); + await provider.click(); + await page.getByRole("option", { name: "Grok TTS via Laptop" }).click(); + await expect.element(dialog.getByText(/Checking for an API key/)).toBeVisible(); + await expect + .element(dialog.getByLabelText("xAI API key", { exact: true })) + .not.toBeInTheDocument(); + finishLookup(); + await dialog.getByLabelText("xAI API key", { exact: true }).fill("test-speech-key"); + await dialog.getByRole("button", { name: "Save and enable" }).click(); + await expect.element(dialog).not.toBeInTheDocument(); + expect(writes).toEqual([{ key: "test-speech-key" }]); + await expect.element(provider).toHaveTextContent("Grok TTS via Laptop"); await expect .element(screen.getByRole("combobox", { name: "Read-aloud model" })) .toHaveTextContent("Server default"); - resolveKeys(Response.json({ openai: false, xai: false, openrouter: false })); - await expect.element(save).toBeEnabled(); - await save.click(); - await expect - .element(screen.getByRole("button", { name: "Remove", exact: true })) - .toBeVisible(); }, ); } finally { @@ -319,7 +332,7 @@ it("waits for the read-aloud key lookup before allowing a save", async () => { } }); -it("shows a catalog transport failure when model controls are unavailable", async () => { +it("shows a catalog transport failure instead of empty model controls", async () => { const previous = getClientSettings().readAloud; await updateClientSettings({ readAloud: { ...DEFAULT_READ_ALOUD_SETTINGS, provider: "xai", environmentId: id }, @@ -332,10 +345,15 @@ it("shows a catalog transport failure when model controls are unavailable", asyn : null, async (screen) => { await expect - .element(screen.getByRole("alert")) - .toHaveTextContent( - "Could not load speech models. Check the selected environment and provider configuration.", - ); + .element( + screen.getByText( + "Could not load speech models. Check the selected environment and provider configuration.", + ), + ) + .toBeVisible(); + await expect + .element(screen.getByRole("combobox", { name: "Read-aloud model" })) + .not.toBeInTheDocument(); }, ); } finally { diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 95dcee4cffb45..aa1736965ac54 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -67,7 +67,7 @@ import { SecretInput } from "./SecretInput"; import { SecretSourceSelect } from "./SecretSourceInput"; // Per dialog instance, not an Atom.family: key presence must be read fresh each time it opens. -function useCloudRead( +export function useCloudRead( prepared: PreparedConnection | null, read: (prepared: PreparedConnection) => Effect.Effect, ) { diff --git a/apps/web/src/components/settings/ReadAloudKeyDialog.tsx b/apps/web/src/components/settings/ReadAloudKeyDialog.tsx new file mode 100644 index 0000000000000..8a7707a391077 --- /dev/null +++ b/apps/web/src/components/settings/ReadAloudKeyDialog.tsx @@ -0,0 +1,263 @@ +import { + configuredSecretSources, + secretRequestReference, +} from "@t3tools/client-runtime/secret-request"; +import { getCloudSpeechKeys, setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; +import { + AuthOrchestrationOperateScope, + AuthSettingsWriteScope, + CloudSpeechApiKey, + CLOUD_SPEECH_PROVIDER_NAMES, + READ_ALOUD_LABELS, + isSecretReference, + type CloudSpeechProvider, + type SecretProviderId, + type SettingsSecretValue, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { AsyncResult } from "effect/reactivity"; +import { useId, useState } from "react"; +import { isSecretsFeatureEnabled } from "../../env"; +import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; +import type { EnvironmentPresentation } from "../../state/environments"; +import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; +import { Button } from "../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../ui/dialog"; +import { Input } from "../ui/input"; +import { Label } from "../ui/label"; +import { useCloudRead } from "./CloudVoiceConfiguration"; +import { SecretInput } from "./SecretInput"; +import { SecretSourceSelect } from "./SecretSourceInput"; + +const isApiKey = Schema.is(CloudSpeechApiKey); + +/** Confirms a hosted read-aloud provider, saving the environment's shared key when it has none. */ +export function ReadAloudKeyDialog({ + environment, + provider, + active, + onEnable, + close, +}: { + environment: Pick; + provider: CloudSpeechProvider; + /** Read-aloud already uses this provider here, so the dialog only manages its key. */ + active: boolean; + onEnable: () => void; + close: () => void; +}) { + const id = environment.environmentId; + const name = READ_ALOUD_LABELS[provider]; + const company = CLOUD_SPEECH_PROVIDER_NAMES[provider]; + const formId = useId(); + const prepared = Option.getOrNull(usePreparedConnection(id)); + const canUse = useEnvironmentScope(id, AuthOrchestrationOperateScope); + const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const [presence, refresh] = useCloudRead(canUse ? prepared : null, getCloudSpeechKeys); + const [remove, setRemove] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; + const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; + const sources = + isSecretsFeatureEnabled && environment.serverConfig?.secretReferences + ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}) + : []; + const reference = + isSecretReference(existing) && sources.some((s) => s.id === existing.provider) + ? existing + : null; + const [sourceId, setSourceId] = useState(reference?.provider ?? null); + const [draft, setDraft] = useState(reference?.reference ?? ""); + const source = sources.find((s) => s.id === sourceId); + const credential = + sourceId !== null + ? source && secretRequestReference(source, draft) + : isApiKey(draft.trim()) + ? draft.trim() + : undefined; + const connected = canUse && prepared !== null; + const editingKey = canManage && saved !== undefined && (active || !saved); + + const saveKey = async (value: SettingsSecretValue | null, thenEnable: boolean) => { + if (!connected || !canManage || busy) return; + setError(""); + setBusy(true); + try { + await runEnvironmentSpeech(setCloudSpeechKey(prepared, provider, value)); + refresh(); + if (thenEnable) onEnable(); + close(); + } catch { + setError("Couldn’t save this change. Check your connection and try again."); + } + setBusy(false); + }; + + return ( +

{ + if (!open && !busy) close(); + }} + > + + + + {remove + ? `Remove the ${company} key?` + : active + ? `Manage ${company} key` + : `Read replies aloud with ${name}?`} + + + {remove + ? `Everyone using ${company} for dictation or read aloud on ${environment.label} will lose access.` + : `Replies you play are sent to ${company} through ${environment.label}, which bills its API key. The key is shared with dictation.`} + + + {!remove && ( + + {!connected ? ( +

Connect to {environment.label} to continue.

+ ) : AsyncResult.isFailure(presence) && saved === undefined ? ( + + ) : saved === undefined ? ( +

Checking for an API key…

+ ) : editingKey ? ( +
{ + event.preventDefault(); + if (credential !== undefined) void saveKey(credential, !active); + }} + > + +
+ {sources.length > 0 && ( + { + setSourceId(next); + setDraft(""); + setError(""); + }} + /> + )} +
+ {sourceId !== null ? ( + setDraft(event.target.value)} + /> + ) : ( + setDraft(event.target.value)} + /> + )} +
+
+

+ {draft.trim() && !credential + ? (source?.invalidReferenceMessage ?? + "Enter an API key, not a URL or secret reference.") + : active + ? "Updating the key keeps read aloud on." + : `Anyone with access to ${environment.label} can bill this key.`} +

+
+ ) : !saved ? ( +

Ask an administrator on {environment.label} to add an API key.

+ ) : ( +

+ Uses the API key saved on {environment.label}. This choice applies only to this + device. +

+ )} +
+ )} + {error && ( +

+ {error} +

+ )} + + {connected && canManage && saved && active && !remove && ( +
+ +
+ )} + + {connected && + (remove ? ( + + ) : editingKey ? ( + + ) : saved && !active ? ( + + ) : null)} +
+
+
+ ); +} diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 94ee9ce1aecf8..8ab05f11be32e 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -1,5 +1,6 @@ import { useEffect, useState, useSyncExternalStore } from "react"; import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; import { cancelSpeechSynthesisModelDownload, downloadSpeechSynthesisModel, @@ -7,14 +8,15 @@ import { getSpeechSynthesisModels, linkSpeechSynthesisModels, removeSpeechSynthesisModel, - setCloudSpeechKey, } from "@t3tools/client-runtime/voice-input"; import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { CloudSpeechProvider, AuthFilesystemReadScope, AuthSettingsWriteScope, + CLOUD_SPEECH_PROVIDER_NAMES, READ_ALOUD_LABELS, + type EnvironmentId, EMPTY_SPEECH_SYNTHESIS_CATALOG, type ReadAloudSettings, type SpeechSynthesisCatalog, @@ -28,6 +30,7 @@ import { readAloudController } from "../../speech/readAloud"; import { CheckIcon, DownloadIcon, + KeyRoundIcon, MonitorIcon, StarIcon, Trash2Icon, @@ -48,90 +51,11 @@ import { SelectGroupLabel, } from "../ui/select"; import { SettingsRow, SettingsSearchTarget, SettingsSection } from "./settingsLayout"; -import { SecretInput } from "./SecretInput"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { useCloudRead } from "./CloudVoiceConfiguration"; +import { ReadAloudKeyDialog } from "./ReadAloudKeyDialog"; import { SpeechProviderIcon } from "./SpeechProviderIcon"; -function ReadAloudKey({ - prepared, - provider, - onSaved, -}: { - prepared: PreparedConnection; - provider: CloudSpeechProvider; - onSaved: () => void; -}) { - const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); - const [configured, setConfigured] = useState(null); - const [draft, setDraft] = useState(""); - const [error, setError] = useState(""); - const [busy, setBusy] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read credential presence from the selected environment without exposing its secret. - useEffect(() => { - const controller = new AbortController(); - void runEnvironmentSpeech(getCloudSpeechKeys(prepared), { signal: controller.signal }).then( - (keys) => setConfigured(Boolean(keys[provider])), - () => setConfigured(false), - ); - return () => controller.abort(); - }, [prepared, provider]); - const save = async (remove: boolean) => { - setBusy(true); - setError(""); - try { - await runEnvironmentSpeech( - setCloudSpeechKey(prepared, provider, remove ? null : draft.trim()), - ); - setDraft(""); - setConfigured(!remove); - onSaved(); - } catch { - setError("Could not save the API key. Check your connection and permissions."); - } - setBusy(false); - }; - return ( - - {configured - ? "Uses the key already saved for dictation on this environment." - : "Stored on the selected environment and shared with dictation."} - {error && {error}} - - } - control={ -
- setDraft(event.target.value)} - /> - - {configured && ( - - )} -
- } - /> - ); -} - const formatSize = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`; function LocalSpeechModel({ @@ -351,6 +275,11 @@ export function ReadAloudSettingsSection() { const prepared = Option.getOrNull(usePreparedConnection(settings.environmentId)); const [catalogVersion, setCatalogVersion] = useState(0); + // A hosted provider is confirmed in its key dialog before read aloud switches to it. + const [pendingCloud, setPendingCloud] = useState<{ + readonly provider: CloudSpeechProvider; + readonly environmentId: EnvironmentId; + } | null>(null); const catalogKey = JSON.stringify([settings.environmentId, settings.provider]); const [catalogState, setCatalogState] = useState<{ key: string; @@ -420,6 +349,14 @@ export function ReadAloudSettingsSection() { name: modelEntry?.voiceNames?.[voice] ?? voice, })); const source = remote ? `${settings.provider}:${settings.environmentId}` : settings.provider; + const cloudProvider = + remote && settings.provider !== "local" ? (settings.provider as CloudSpeechProvider) : null; + const [keys] = useCloudRead(cloudProvider ? prepared : null, getCloudSpeechKeys); + const keyMissing = + cloudProvider !== null && AsyncResult.isSuccess(keys) && keys.value?.[cloudProvider] === false; + const pendingEnvironment = environments.find( + (entry) => entry.environmentId === pendingCloud?.environmentId, + ); const selectedEnvironment = environments.find( (entry) => entry.environmentId === settings.environmentId, ); @@ -428,122 +365,179 @@ export function ReadAloudSettingsSection() { + {selectedEnvironment?.label ?? "This environment"} has no{" "} + {CLOUD_SPEECH_PROVIDER_NAMES[cloudProvider]} API key. Add one with the key button. + + ) : remote && error ? ( + {error} + ) : ( + "Read completed replies with the play button beside Copy. Hosted providers receive the response text through the selected environment; a local model runs on it." + ) + } control={ - { + if (!value) return; + if (value === "off" || value === "system") + change({ provider: value, environmentId: null, model: "", voice: "" }); + else { + const [provider, ...rest] = value.split(":"); + const environment = environments.find( + (entry) => entry.environmentId === rest.join(":"), + ); + if (!environment) return; + if (provider === "local") + change({ + provider: "local", + environmentId: environment.environmentId, + model: "", + voice: "", + }); + else + setPendingCloud({ + provider: provider as CloudSpeechProvider, + environmentId: environment.environmentId, + }); + } + }} > - - - {settings.provider === "local" ? ( - - ) : ( - - )} - - {settings.provider === "local" - ? (selectedEnvironment?.label ?? "Chosen environment (unavailable)") - : READ_ALOUD_LABELS[settings.provider]} - {remote && settings.provider !== "local" && ( - - {" via "} - {selectedEnvironment?.label ?? "unavailable environment"} - + + + + {settings.provider === "local" ? ( + + ) : ( + )} + + {settings.provider === "local" + ? (selectedEnvironment?.label ?? "Chosen environment (unavailable)") + : READ_ALOUD_LABELS[settings.provider]} + {remote && settings.provider !== "local" && ( + + {" via "} + {selectedEnvironment?.label ?? "unavailable environment"} + + )} + - - - - - - - - Off - - - - On this device - +
+ + + - - System voices + + Off - - {environments.length > 0 && ( - On an environment - {environments.map((environment) => ( - - - - {environment.label} - - - ))} + On this device + + + + System voices + + - )} - {environments.map((environment) => ( - - Cloud via {environment.label} - {CloudSpeechProvider.literals.map((provider) => ( - 0 && ( + + On an environment + {environments.map((environment) => ( + + + + {environment.label} + + + ))} + + )} + {environments.map((environment) => ( + + Cloud via {environment.label} + {CloudSpeechProvider.literals.map((provider) => ( + + + + {READ_ALOUD_LABELS[provider]} + + + ))} + + ))} + {remote && !selectedEnvironment && ( + Chosen environment (unavailable) + )} + + + {cloudProvider && selectedEnvironment && ( + + + setPendingCloud({ + provider: cloudProvider, + environmentId: selectedEnvironment.environmentId, + }) + } > - - - {READ_ALOUD_LABELS[provider]} - - - ))} - - ))} - {remote && !selectedEnvironment && ( - Chosen environment (unavailable) - )} - - + + + } + /> + Manage key + + )} + } />
+ {pendingCloud && pendingEnvironment && ( + + change({ + provider: pendingCloud.provider, + environmentId: pendingCloud.environmentId, + model: "", + voice: "", + }) + } + close={() => { + setPendingCloud(null); + refreshCatalog(); + }} + /> + )} {settings.provider === "off" ? null : ( <> - {remote && prepared && catalog.apiKeyProvider && ( - setCatalogVersion((value) => value + 1)} - /> - )} {prepared && localModels.length > 0 && ( )} - {remote && error && ( -

- {error} -

- )} - {remote && !localModels.length && catalog.supportsModelSelection && ( + {cloudProvider && catalog.supportsModelSelection && catalog.models.length > 0 && ( )} - {(settings.provider === "system" || catalog.supportsVoiceSelection) && ( + {(settings.provider === "system" || + (catalog.supportsVoiceSelection && catalog.models.length > 0)) && ( Date: Wed, 18 Nov 2026 03:33:45 -0600 Subject: [PATCH 31/33] fix(read-aloud): stop the preview on leaving settings and start Kokoro sooner Closing settings now stops a playing preview on web and mobile. Read-aloud buttons ask the environment to load its local model while replies are on screen, at most every four minutes per model, so the first click no longer waits for the load. The worker also synthesizes a short opening sentence on its own, which brings Kokoro's first audio from about 2s to about 0.8s on a loaded model. Co-authored-by: Cursor --- .../features/read-aloud/ReadAloudButton.tsx | 6 +- .../src/features/read-aloud/playback.ts | 15 ++- .../features/settings/ReadAloudSection.tsx | 7 ++ .../server/src/speech/LocalSpeechSynthesis.ts | 106 ++++++++++++------ apps/server/src/speech/http.ts | 7 ++ .../server/src/speech/localSynthesisWorker.ts | 39 ++++--- apps/server/src/speech/synthesis.test.ts | 11 +- apps/server/src/speech/synthesisAudio.ts | 8 ++ .../src/components/chat/ReadAloudButton.tsx | 6 +- .../settings/ReadAloudSettingsSection.tsx | 7 ++ apps/web/src/speech/readAloud.ts | 13 ++- packages/client-runtime/src/readAloud.test.ts | 39 ++++++- packages/client-runtime/src/readAloud.ts | 27 ++++- .../src/voice-input/environment.ts | 11 ++ .../client-runtime/src/voice-input/index.ts | 1 + packages/contracts/src/environmentHttp.ts | 8 ++ packages/contracts/src/readAloud.ts | 4 + 17 files changed, 251 insertions(+), 64 deletions(-) diff --git a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx index f6084e8191ce9..065aa1e8f466d 100644 --- a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx +++ b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx @@ -1,4 +1,4 @@ -import { useSyncExternalStore } from "react"; +import { useEffect, useSyncExternalStore } from "react"; import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { DEFAULT_READ_ALOUD_SETTINGS } from "@t3tools/contracts"; @@ -6,7 +6,7 @@ import { Pressable } from "react-native"; import { mobilePreferencesAtom } from "../../state/preferences"; import { SymbolView } from "../../components/ui/AppSymbol"; import * as Dialog from "../../components/ui/Dialog"; -import { readAloudController } from "./playback"; +import { readAloudController, warmReadAloud } from "./playback"; export function ReadAloudButton({ id, @@ -27,6 +27,8 @@ export function ReadAloudButton({ readAloudController.subscribe, readAloudController.getSnapshot, ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Loading the environment's local model while replies are on screen hides its startup from the first click. + useEffect(() => warmReadAloud(settings), [settings]); if (settings.provider === "off") return null; const active = state.id === id; const stoppable = active && (state.status === "playing" || state.status === "loading"); diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts index cc6e50376f11d..3d2b68150e46d 100644 --- a/apps/mobile/src/features/read-aloud/playback.ts +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -1,6 +1,11 @@ -import { createReadAloudController, type SpeechPlayback } from "@t3tools/client-runtime/read-aloud"; +import { + createReadAloudController, + createReadAloudWarmup, + type SpeechPlayback, +} from "@t3tools/client-runtime/read-aloud"; import { getSpeechSynthesisModels, + prepareSpeechSynthesis, startSpeechSynthesis, } from "@t3tools/client-runtime/voice-input"; import { createAudioPlayer } from "expo-audio"; @@ -103,6 +108,14 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba const catalogs = new WeakMap>(); +export const warmReadAloud = createReadAloudWarmup(async (environmentId, model) => { + const prepared = Option.getOrNull( + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(environmentId)), + ); + if (!prepared) throw new Error("The read-aloud environment is not connected."); + await runSpeech(prepareSpeechSynthesis(prepared, model)); +}); + export const readAloudController = createReadAloudController(async (text, settings, signal) => { if (settings.provider === "system") { const voices = diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index ced9f7e8dae52..57191ed3e566a 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -44,6 +44,13 @@ export function ReadAloudSection() { const { environments } = useEnvironments(); const [sheet, setSheet] = useState<"source" | "model" | "voice" | null>(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- The preview belongs to this screen, so leaving it stops the sample. + useEffect( + () => () => { + if (readAloudController.getSnapshot().id === "preview") readAloudController.stop(); + }, + [], + ); const [catalogVersion, setCatalogVersion] = useState(0); const catalogKey = JSON.stringify([settings.environmentId, settings.provider]); const [catalogState, setCatalogState] = useState<{ diff --git a/apps/server/src/speech/LocalSpeechSynthesis.ts b/apps/server/src/speech/LocalSpeechSynthesis.ts index 80e4e512923e2..557b0e26ac29b 100644 --- a/apps/server/src/speech/LocalSpeechSynthesis.ts +++ b/apps/server/src/speech/LocalSpeechSynthesis.ts @@ -228,6 +228,8 @@ export class LocalSpeechSynthesis extends Context.Service< modelId: string, ) => Effect.Effect; readonly cancel: (modelId: string) => Effect.Effect; + /** Loads an installed model ahead of playback, so the first reply starts sooner. */ + readonly prepare: (modelId: string) => Effect.Effect; /** Uses model files already on this machine, from a file or a folder to search. */ readonly link: ( source: string, @@ -616,24 +618,81 @@ const make = Effect.gen(function* () { ...(cause === undefined ? {} : { cause }), }); + const findDefinition = (modelId: string) => + LOCAL_SYNTHESIS_MODELS.find((model) => model.id === (modelId || LOCAL_SYNTHESIS_MODELS[0]!.id)); + + // The verified model and eSpeak files, or undefined while any is missing. + const loadablePaths = Effect.fnUntraced(function* (definition: LocalModel) { + if (!(yield* runtimeReady)) return undefined; + const modelPath = yield* store.installedPath(definition.file); + const espeakPath = definition.espeakData && (yield* store.installedPath(definition.espeakData)); + if (!modelPath || (definition.espeakData && !espeakPath)) return undefined; + return { modelPath, espeakPath }; + }); + + // Callers hold the permit, so one model loads at a time and synthesis waits for it. + const ensureWorker = Effect.fnUntraced(function* ( + definition: LocalModel, + paths: { readonly modelPath: string; readonly espeakPath: string | undefined }, + ) { + if (!runtime || !libraryPath) return yield* failure("unavailable"); + if (worker?.model.alive && worker.modelId === definition.id) return worker.model; + yield* unloadWorker; + // Uninterruptible, so a stream stopped mid-load still records the process it started. + const loaded = yield* Effect.tryPromise({ + try: () => + loadLocalSynthesisModel({ + libraryPath, + backend: runtime.backend, + modelPath: paths.modelPath, + ...(paths.espeakPath && { + env: { AUDIOCPP_ESPEAK_DATA: paths.espeakPath, AUDIOCPP_ESPEAK_CACHE: espeakCache }, + }), + threads: Math.max(1, Math.min(8, NodeOS.availableParallelism() - 1)), + signal: lifetime.signal, + }), + catch: (cause) => failure("unavailable", cause), + }).pipe( + Effect.tap((model) => + Effect.sync(() => { + worker = { modelId: definition.id, model }; + }), + ), + Effect.uninterruptible, + ); + yield* Effect.logInfo("Loaded the local speech model.", { backend: loaded.backend }); + return loaded; + }); + + const prepare = Effect.fn("LocalSpeechSynthesis.prepare")(function* (modelId: string) { + const definition = findDefinition(modelId); + if (!definition || (worker?.model.alive && worker.modelId === definition.id)) return; + const paths = yield* loadablePaths(definition); + if (!paths) return; + yield* permit + .withPermits(1)(ensureWorker(definition, paths)) + .pipe( + Effect.andThen(Effect.sync(() => Queue.offerUnsafe(idleDeadlines, undefined))), + Effect.catchTags({ + SpeechSynthesisError: (error) => + Effect.logWarning("Local speech model failed to load.", error), + }), + ); + }); + // Untraced: it runs inside the stream's own span. const speak = Effect.fnUntraced(function* ( request: SpeechSynthesisRequest, queue: Queue.Queue, ) { if (!runtime || !libraryPath) return yield* failure("unavailable"); - const definition = LOCAL_SYNTHESIS_MODELS.find( - (model) => model.id === (request.model || LOCAL_SYNTHESIS_MODELS[0]!.id), - ); + const definition = findDefinition(request.model); if (!definition) return yield* failure("model-unavailable"); - if (!(yield* runtimeReady)) return yield* failure("missing-model"); - const modelPath = yield* store.installedPath(definition.file); + const paths = yield* loadablePaths(definition); const voice = definition.voices.find((entry) => entry.id === request.voice) ?? definition.voices[0]!; const voicePath = voice.file && (yield* store.installedPath(voice.file)); - const espeakPath = definition.espeakData && (yield* store.installedPath(definition.espeakData)); - if (!modelPath || (voice.file && !voicePath) || (definition.espeakData && !espeakPath)) - return yield* failure("missing-model"); + if (!paths || (voice.file && !voicePath)) return yield* failure("missing-model"); // Held until the stream ends, after any cancelled synthesis has stopped. // Interruptible, so a request abandoned while waiting stops waiting. yield* Effect.acquireRelease( @@ -644,34 +703,7 @@ const make = Effect.gen(function* () { ), { interruptible: true }, ); - if (!worker?.model.alive || worker.modelId !== definition.id) { - yield* unloadWorker; - // Uninterruptible, so a stream stopped mid-load still records the process it started. - const loaded = yield* Effect.tryPromise({ - try: () => - loadLocalSynthesisModel({ - libraryPath, - backend: runtime.backend, - modelPath, - ...(espeakPath && { - env: { AUDIOCPP_ESPEAK_DATA: espeakPath, AUDIOCPP_ESPEAK_CACHE: espeakCache }, - }), - threads: Math.max(1, Math.min(8, NodeOS.availableParallelism() - 1)), - signal: lifetime.signal, - }), - catch: (cause) => failure("unavailable", cause), - }).pipe( - Effect.tap((model) => - Effect.sync(() => { - worker = { modelId: definition.id, model }; - }), - ), - Effect.uninterruptible, - ); - yield* Effect.logInfo("Loaded the local speech model.", { backend: loaded.backend }); - } - if (!worker) return yield* failure("unavailable"); - const { model } = worker; + const model = yield* ensureWorker(definition, paths); const language = localSynthesisLanguage(request.language, model.languages); const spoken = model .stream( @@ -707,7 +739,7 @@ const make = Effect.gen(function* () { Stream.withSpan("LocalSpeechSynthesis.stream"), ); - return LocalSpeechSynthesis.of({ catalog, download, cancel, link, remove, stream }); + return LocalSpeechSynthesis.of({ catalog, download, cancel, link, remove, prepare, stream }); }); export const layer = Layer.effect(LocalSpeechSynthesis, make); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 6a096f2e95413..94288273e7136 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -151,6 +151,13 @@ export const speechHttpApiLayer = HttpApiBuilder.group( return { token }; }), ) + .handle( + "prepareSynthesisModel", + Effect.fn("environment.voice.prepareSynthesisModel")(function* (args) { + yield* guard(args.endpoint.name); + yield* local.prepare(args.payload.model); + }), + ) .handle( "downloadSynthesisModel", Effect.fn("environment.voice.downloadSynthesisModel")(function* (args) { diff --git a/apps/server/src/speech/localSynthesisWorker.ts b/apps/server/src/speech/localSynthesisWorker.ts index 32ffe35c961d4..ab5dc80e3616e 100644 --- a/apps/server/src/speech/localSynthesisWorker.ts +++ b/apps/server/src/speech/localSynthesisWorker.ts @@ -2,7 +2,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeSea from "node:sea"; import { bindAudioCpp, type AudioCppSynthesisRequest } from "@t3tools/audio-cpp"; -import { ENCODE_SLICE_SAMPLES, mp3Kbps, pcm16Mono } from "./synthesisAudio.ts"; +import { ENCODE_SLICE_SAMPLES, leadingSentence, mp3Kbps, pcm16Mono } from "./synthesisAudio.ts"; // Inlined like the dictation worker, so packaged builds need no separate worker artifact. const entry = ` @@ -13,6 +13,7 @@ const entry = ` const bindAudioCpp = ${bindAudioCpp.toString()}; const pcm16Mono = ${pcm16Mono.toString()}; const mp3Kbps = ${mp3Kbps.toString()}; + const leadingSentence = ${leadingSentence.toString()}; const packageJson = (name) => { const path = findPackageJSON(name, baseUrl); if (!path) throw new Error("The " + name + " package is unavailable."); @@ -48,25 +49,29 @@ const entry = ` reply({ ok: true, backend: model.backend, languages: model.languages }); } else if (message.kind === "synthesize") { cancelled = false; - const stream = model.stream(message.request); - try { - let encoder; - while (!cancelled) { - const audio = stream.next(); - if (!audio) break; - encoder ??= new lame.Mp3Encoder(1, audio.sampleRate, mp3Kbps(audio.sampleRate)); - const pcm = pcm16Mono(audio.samples, audio.channels); - // Encoding a text chunk takes longer than synthesizing it, so send it slice by slice. - for (let start = 0; start < pcm.length && !cancelled; start += ${ENCODE_SLICE_SAMPLES}) { - chunk(encoder.encodeBuffer(pcm.subarray(start, start + ${ENCODE_SLICE_SAMPLES}))); - // Lets IPC deliver the slice, and a cancel arrive, before the next one. - await new Promise((resolve) => setImmediate(resolve)); + // One encoder across both parts keeps the MP3 a single seamless stream. + let encoder; + for (const text of leadingSentence(message.request.text)) { + if (cancelled) break; + const stream = model.stream({ ...message.request, text }); + try { + while (!cancelled) { + const audio = stream.next(); + if (!audio) break; + encoder ??= new lame.Mp3Encoder(1, audio.sampleRate, mp3Kbps(audio.sampleRate)); + const pcm = pcm16Mono(audio.samples, audio.channels); + // Encoding a text chunk takes longer than synthesizing it, so send it slice by slice. + for (let start = 0; start < pcm.length && !cancelled; start += ${ENCODE_SLICE_SAMPLES}) { + chunk(encoder.encodeBuffer(pcm.subarray(start, start + ${ENCODE_SLICE_SAMPLES}))); + // Lets IPC deliver the slice, and a cancel arrive, before the next one. + await new Promise((resolve) => setImmediate(resolve)); + } } + } finally { + stream.close(); } - if (encoder && !cancelled) chunk(encoder.flush()); - } finally { - stream.close(); } + if (encoder && !cancelled) chunk(encoder.flush()); reply({ ok: true }); } } catch (error) { diff --git a/apps/server/src/speech/synthesis.test.ts b/apps/server/src/speech/synthesis.test.ts index a331afd36b577..28a213039c031 100644 --- a/apps/server/src/speech/synthesis.test.ts +++ b/apps/server/src/speech/synthesis.test.ts @@ -12,7 +12,7 @@ import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretReso import * as ServerSettings from "../serverSettings.ts"; import * as CloudSpeech from "./CloudSpeech.ts"; import { localSynthesisLanguage, localSynthesisRuntime } from "./LocalSpeechSynthesis.ts"; -import { encodeMp3, pcm16Mono } from "./synthesisAudio.ts"; +import { encodeMp3, leadingSentence, pcm16Mono } from "./synthesisAudio.ts"; it("encodes model samples as clipped mono 16-bit PCM", () => { const pcm = pcm16Mono(Float32Array.of(0, 1, -1, 2, -2, Number.NaN, 0.5), 1); @@ -20,6 +20,15 @@ it("encodes model samples as clipped mono 16-bit PCM", () => { expect([...pcm16Mono(Float32Array.of(1, -1, 0.5, 0.5), 2)]).toEqual([0, 16383]); }); +const longLine = `${"word ".repeat(40)}end.`; +it.each([ + ["Fixed it.\nThe cause was a race.\nDone.", ["Fixed it.", "The cause was a race.\nDone."]], + ["Only one sentence.", ["Only one sentence."]], + [`${longLine}\nNext.`, [`${longLine}\nNext.`]], +])("synthesizes a short opening sentence on its own: %j", (text, parts) => { + expect(leadingSentence(text)).toEqual(parts); +}); + // An MPEG audio frame header's version bits and sample-rate index give the encoded rate. function mp3SampleRate(bytes: Uint8Array) { expect(bytes[0]).toBe(0xff); diff --git a/apps/server/src/speech/synthesisAudio.ts b/apps/server/src/speech/synthesisAudio.ts index 9dd6fa5022856..7675a15afd278 100644 --- a/apps/server/src/speech/synthesisAudio.ts +++ b/apps/server/src/speech/synthesisAudio.ts @@ -11,6 +11,14 @@ export const MAX_SYNTHESIS_BYTES = 32 * 1024 * 1024; export function mp3Kbps(sampleRate: number) { return sampleRate > 32000 ? 64 : 48; } +/** + * Splits off a short opening sentence (read-aloud text has one per line), so its audio arrives + * before the model reaches the rest. Self-contained so the synthesis worker can inline it. + */ +export function leadingSentence(text: string) { + const end = text.indexOf("\n"); + return end < 0 || end > 160 ? [text] : [text.slice(0, end), text.slice(end + 1)]; +} const MP3_SAMPLE_RATES = [8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000]; // About half a second at 44.1 kHz, which encodes in about 15 ms. export const ENCODE_SLICE_SAMPLES = 1152 * 20; diff --git a/apps/web/src/components/chat/ReadAloudButton.tsx b/apps/web/src/components/chat/ReadAloudButton.tsx index 7af486b8a122a..1b492cc23980f 100644 --- a/apps/web/src/components/chat/ReadAloudButton.tsx +++ b/apps/web/src/components/chat/ReadAloudButton.tsx @@ -1,7 +1,7 @@ -import { useSyncExternalStore } from "react"; +import { useEffect, useSyncExternalStore } from "react"; import { PlayIcon, SquareIcon, Volume2Icon } from "lucide-react"; import { useClientSettings } from "../../hooks/useSettings"; -import { readAloudController } from "../../speech/readAloud"; +import { readAloudController, warmReadAloud } from "../../speech/readAloud"; import { Button } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { toastManager } from "../ui/toast"; @@ -12,6 +12,8 @@ export function ReadAloudButton({ id, text }: { id: string; text: string }) { readAloudController.subscribe, readAloudController.getSnapshot, ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Loading the environment's local model while replies are on screen hides its startup from the first click. + useEffect(() => warmReadAloud(settings), [settings]); if (settings.provider === "off") return null; const active = state.id === id; const stoppable = active && (state.status === "playing" || state.status === "loading"); diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index 8ab05f11be32e..a38f5f1deb14d 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -298,6 +298,13 @@ export function ReadAloudSettingsSection() { settings.provider === "local" ? catalog.models.filter((entry) => entry.install) : []; const refreshCatalog = () => setCatalogVersion((value) => value + 1); const [systemVoices, setSystemVoices] = useState([]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- The preview belongs to this page, so closing settings stops it. + useEffect( + () => () => { + if (readAloudController.getSnapshot().id === "read-aloud-preview") readAloudController.stop(); + }, + [], + ); const state = useSyncExternalStore( readAloudController.subscribe, readAloudController.getSnapshot, diff --git a/apps/web/src/speech/readAloud.ts b/apps/web/src/speech/readAloud.ts index b266da37fa76a..2c1bb658328b5 100644 --- a/apps/web/src/speech/readAloud.ts +++ b/apps/web/src/speech/readAloud.ts @@ -1,7 +1,12 @@ import { speechSpeedAppliedByProvider, type SpeechSynthesisCatalog } from "@t3tools/contracts"; -import { createReadAloudController, type SpeechPlayback } from "@t3tools/client-runtime/read-aloud"; +import { + createReadAloudController, + createReadAloudWarmup, + type SpeechPlayback, +} from "@t3tools/client-runtime/read-aloud"; import { getSpeechSynthesisModels, + prepareSpeechSynthesis, startSpeechSynthesis, } from "@t3tools/client-runtime/voice-input"; import { readPreparedConnection } from "../state/session"; @@ -49,6 +54,12 @@ function systemPlayback( const catalogs = new WeakMap>(); +export const warmReadAloud = createReadAloudWarmup(async (environmentId, model) => { + const prepared = readPreparedConnection(environmentId); + if (!prepared) throw new Error("The read-aloud environment is not connected."); + await runEnvironmentSpeech(prepareSpeechSynthesis(prepared, model)); +}); + export const readAloudController = createReadAloudController(async (text, settings, signal) => { if (settings.provider === "system") return systemPlayback(text, settings.voice, settings.speed, settings.language); diff --git a/packages/client-runtime/src/readAloud.test.ts b/packages/client-runtime/src/readAloud.test.ts index f6ba188e66234..a4d7808a2ea32 100644 --- a/packages/client-runtime/src/readAloud.test.ts +++ b/packages/client-runtime/src/readAloud.test.ts @@ -1,6 +1,10 @@ import { expect, it, vi } from "vite-plus/test"; -import { DEFAULT_READ_ALOUD_SETTINGS } from "@t3tools/contracts"; -import { createReadAloudController, type SpeechPlayback } from "./readAloud.ts"; +import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId } from "@t3tools/contracts"; +import { + createReadAloudController, + createReadAloudWarmup, + type SpeechPlayback, +} from "./readAloud.ts"; function deferred
() { let resolve: (value: A) => void = () => {}; @@ -200,3 +204,34 @@ it("keeps a new pause while resume activates playback", async () => { unsubscribe(); } }); + +it("warms each local model once per interval, and again after a failed request", async () => { + let now = 0; + const failed = deferred(); + const warm = vi.fn(async (_environment: EnvironmentId, model: string) => { + if (model === "broken") { + failed.resolve(); + throw new Error("offline"); + } + }); + const warmup = createReadAloudWarmup(warm, () => now); + const environmentId = EnvironmentId.make("env"); + const local = { ...DEFAULT_READ_ALOUD_SETTINGS, provider: "local" as const, environmentId }; + warmup(local); + warmup(local); + warmup({ ...local, provider: "openai" }); + warmup({ ...local, environmentId: null }); + expect(warm.mock.calls).toEqual([[environmentId, local.model]]); + now = 4 * 60_000; + warmup(local); + warmup({ ...local, model: "broken" }); + await failed.promise; + await Promise.resolve(); + warmup({ ...local, model: "broken" }); + expect(warm.mock.calls.map(([, model]) => model)).toEqual([ + local.model, + local.model, + "broken", + "broken", + ]); +}); diff --git a/packages/client-runtime/src/readAloud.ts b/packages/client-runtime/src/readAloud.ts index 081ce9333ea43..024e8fbf14bd0 100644 --- a/packages/client-runtime/src/readAloud.ts +++ b/packages/client-runtime/src/readAloud.ts @@ -1,6 +1,31 @@ -import { SPEECH_SYNTHESIS_MAX_TEXT, type ReadAloudSettings } from "@t3tools/contracts"; +import { + SPEECH_SYNTHESIS_MAX_TEXT, + type EnvironmentId, + type ReadAloudSettings, +} from "@t3tools/contracts"; import { readAloudText, splitReadAloudText } from "@t3tools/shared/read-aloud"; +const WARM_INTERVAL_MS = 4 * 60_000; + +/** + * Asks an environment to load its local model before playback, at most once per interval for each + * environment and model. A failed request is retried the next time. + */ +export function createReadAloudWarmup( + warm: (environmentId: EnvironmentId, model: string) => Promise, + now: () => number = Date.now, +) { + const requested = new Map(); + return (settings: ReadAloudSettings) => { + if (settings.provider !== "local" || !settings.environmentId) return; + const key = JSON.stringify([settings.environmentId, settings.model]); + const last = requested.get(key); + if (last !== undefined && now() - last < WARM_INTERVAL_MS) return; + requested.set(key, now()); + void warm(settings.environmentId, settings.model).catch(() => requested.delete(key)); + }; +} + export type SpeechPlayback = { play: () => Promise; pause: () => void; diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts index 5b72cf0c07413..457e106fab2af 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -362,6 +362,17 @@ export const startSpeechSynthesis = ( ); }; +/** Loads the environment's local model ahead of playback; an empty model is its default. */ +export const prepareSpeechSynthesis = (prepared: PreparedConnection, model: string) => + request({ + group: "voice", + prepared, + method: "POST", + path: (urls) => urls.prepareSynthesisModel(), + timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS, + run: ({ client, headers }) => client.prepareSynthesisModel({ headers, payload: { model } }), + }); + export const downloadSpeechSynthesisModel = (prepared: PreparedConnection, modelId: string) => request({ group: "voice", diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index 76e5946bb355f..c4bcafb1681db 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -45,6 +45,7 @@ export { downloadSpeechSynthesisModel, getSpeechSynthesisModels, linkSpeechSynthesisModels, + prepareSpeechSynthesis, removeSpeechSynthesisModel, startSpeechSynthesis, } from "./environment.ts"; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 5747f2f5c5ba9..ecd3353d92f01 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -4,6 +4,7 @@ import { SpeechSynthesisCatalog, SpeechSynthesisError, SpeechSynthesisModelRequest, + SpeechSynthesisPrepareRequest, SpeechSynthesisStream, } from "./readAloud.ts"; import * as Context from "effect/Context"; @@ -870,6 +871,13 @@ export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice") ], }).middleware(EnvironmentAuthenticatedAuth), ) + .add( + HttpApiEndpoint.post("prepareSynthesisModel", "/api/voice/synthesis/local/prepare", { + headers: OptionalBearerHeaders, + payload: SpeechSynthesisPrepareRequest, + error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], + }).middleware(EnvironmentAuthenticatedAuth), + ) .add( HttpApiEndpoint.post("downloadSynthesisModel", "/api/voice/synthesis/local/models/download", { headers: OptionalBearerHeaders, diff --git a/packages/contracts/src/readAloud.ts b/packages/contracts/src/readAloud.ts index a55aeba8bf9c2..f9a0b32526ae8 100644 --- a/packages/contracts/src/readAloud.ts +++ b/packages/contracts/src/readAloud.ts @@ -81,6 +81,10 @@ export const SpeechSynthesisModelInstall = Schema.Struct({ linkedFrom: Schema.optionalKey(Schema.String), }); export type SpeechSynthesisModelInstall = typeof SpeechSynthesisModelInstall.Type; +/** An empty model loads the environment's default local model. */ +export const SpeechSynthesisPrepareRequest = Schema.Struct({ + model: Schema.String.check(Schema.isMaxLength(160)), +}); export const SpeechSynthesisModelRequest = Schema.Struct({ modelId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(160)), }); From e07133490aa99b5585e3aa4eb2088f35f0a65970 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Wed, 18 Nov 2026 15:35:50 -0600 Subject: [PATCH 32/33] fix(read-aloud): translate the read-aloud UI and address review findings Main now requires UI copy to go through translations, so the read-aloud settings, key dialog, and buttons on web and mobile use gt() and , with hand-written catalog entries for every locale. - Linking a Pocket voice file completes Pocket rather than whichever model is already installed: the model store now returns the files it linked, since file ids name shared repositories. - A cancelled download no longer selects the incomplete model, and one that finishes after the provider changes no longer writes the old settings back. - Mobile tracks a pending download per environment and model. - On mobile, losing audio focus while playback activates pauses the reply instead of failing it. Co-authored-by: Cursor --- .../features/read-aloud/ReadAloudButton.tsx | 10 +- .../src/features/read-aloud/playback.test.ts | 39 ++++ .../src/features/read-aloud/playback.ts | 9 +- .../features/settings/ReadAloudSection.tsx | 139 ++++++----- apps/mobile/src/i18n/translations/de.json | 47 +++- apps/mobile/src/i18n/translations/en.json | 47 +++- apps/mobile/src/i18n/translations/es.json | 47 +++- apps/mobile/src/i18n/translations/fr.json | 47 +++- apps/mobile/src/i18n/translations/ja.json | 47 +++- apps/mobile/src/i18n/translations/ko.json | 47 +++- apps/mobile/src/i18n/translations/pt-BR.json | 47 +++- apps/mobile/src/i18n/translations/ru.json | 47 +++- apps/mobile/src/i18n/translations/sv.json | 47 +++- apps/mobile/src/i18n/translations/zh.json | 47 +++- apps/mobile/src/lib/audioSession.ts | 8 +- apps/mobile/src/lib/useMediaVideoPlayback.ts | 2 +- .../src/speech/LocalSpeechSynthesis.test.ts | 25 +- .../server/src/speech/LocalSpeechSynthesis.ts | 15 +- .../src/speech/SpeechModelStore.test.ts | 4 +- apps/server/src/speech/SpeechModelStore.ts | 6 +- apps/server/src/speech/SpeechService.ts | 2 +- .../src/components/chat/ReadAloudButton.tsx | 12 +- .../settings/ReadAloudKeyDialog.tsx | 76 ++++-- .../settings/ReadAloudSettingsSection.tsx | 217 ++++++++++++------ .../src/components/settings/settingsSearch.ts | 6 +- apps/web/src/i18n/translations/de.json | 126 +++++++--- apps/web/src/i18n/translations/en.json | 124 +++++++--- apps/web/src/i18n/translations/es.json | 124 +++++++--- apps/web/src/i18n/translations/fr.json | 124 +++++++--- apps/web/src/i18n/translations/ja.json | 124 +++++++--- apps/web/src/i18n/translations/ko.json | 124 +++++++--- apps/web/src/i18n/translations/pt-BR.json | 124 +++++++--- apps/web/src/i18n/translations/ru.json | 124 +++++++--- apps/web/src/i18n/translations/sv.json | 124 +++++++--- apps/web/src/i18n/translations/zh.json | 128 ++++++++--- apps/web/src/speech/readAloud.ts | 3 +- packages/client-runtime/src/readAloud.ts | 8 +- 37 files changed, 1762 insertions(+), 535 deletions(-) diff --git a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx index 065aa1e8f466d..d745ef5853f17 100644 --- a/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx +++ b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx @@ -2,6 +2,7 @@ import { useEffect, useSyncExternalStore } from "react"; import { useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { DEFAULT_READ_ALOUD_SETTINGS } from "@t3tools/contracts"; +import { useGT } from "gt-react-native"; import { Pressable } from "react-native"; import { mobilePreferencesAtom } from "../../state/preferences"; import { SymbolView } from "../../components/ui/AppSymbol"; @@ -29,14 +30,15 @@ export function ReadAloudButton({ ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Loading the environment's local model while replies are on screen hides its startup from the first click. useEffect(() => warmReadAloud(settings), [settings]); + const gt = useGT(); if (settings.provider === "off") return null; const active = state.id === id; const stoppable = active && (state.status === "playing" || state.status === "loading"); const label = stoppable - ? "Stop reading" + ? gt("Stop reading") : active && state.status === "paused" - ? "Resume reading" - : "Read aloud"; + ? gt("Resume reading") + : gt("Read aloud"); return ( } }); +it("keeps a reply resumable when recording takes focus while playback activates", async () => { + const activating = Promise.withResolvers(); + const activated = Promise.withResolvers(); + vi.mocked(setAudioModeAsync).mockImplementationOnce(async () => { + activating.resolve(); + await activated.promise; + }); + vi.mocked(createAudioPlayer).mockReturnValue({ + play: vi.fn(), + pause: vi.fn(), + release: vi.fn(), + setPlaybackRate: vi.fn(), + setActiveForLockScreen: vi.fn(), + addListener: vi.fn(), + } as unknown as ReturnType); + const settled = Promise.withResolvers(); + const unsubscribe = readAloudController.subscribe(() => { + const { status } = readAloudController.getSnapshot(); + if (status === "playing" || status === "error") settled.resolve(status); + }); + void readAloudController.start("cloud", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "openai", + environmentId: EnvironmentId.make("host"), + }); + await activating.promise; + const recorder = acquireAudioSession("recording"); + try { + expect(readAloudController.getSnapshot().status).toBe("paused"); + activated.resolve(); + await readAloudController.resume(); + expect(await settled.promise).toBe("playing"); + } finally { + unsubscribe(); + readAloudController.stop(); + await releaseAudioSession(recorder); + } +}); + it("cancels Android default speech while the native engine initializes", async () => { using _os = vi.spyOn(Platform, "OS", "get").mockReturnValue("android"); const loading = Promise.withResolvers(); diff --git a/apps/mobile/src/features/read-aloud/playback.ts b/apps/mobile/src/features/read-aloud/playback.ts index 3d2b68150e46d..a79a4d904a330 100644 --- a/apps/mobile/src/features/read-aloud/playback.ts +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -1,3 +1,4 @@ +import { m } from "../../i18n/messages"; import { createReadAloudController, createReadAloudWarmup, @@ -91,8 +92,7 @@ function systemPlayback(text: string, settings: ReadAloudSettings): SpeechPlayba return { play: async () => { if (pauseInBackground(settings)) return; - await session.play(); - if (!session.requested) throw new Error("Finish recording before reading aloud."); + if (!(await session.play())) throw new Error("Finish recording before reading aloud."); }, pause: () => session.pause(), stop: () => { @@ -205,8 +205,7 @@ export const readAloudController = createReadAloudController(async (text, settin if (pauseInBackground(settings)) return; if (settings.backgroundPlayback) player.setActiveForLockScreen(true, { title: "T3 Code", artist: "Read aloud" }); - await session.play(); - if (!session.requested) throw new Error("Finish recording before reading aloud."); + if (!(await session.play())) throw new Error("Finish recording before reading aloud."); }, pause: () => session.pause(), stop: () => { @@ -217,4 +216,4 @@ export const readAloudController = createReadAloudController(async (text, settin }, finished, }; -}); +}, m); diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx index 57191ed3e566a..1455448e262ff 100644 --- a/apps/mobile/src/features/settings/ReadAloudSection.tsx +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -3,6 +3,7 @@ import { useAtomSet, useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import * as Option from "effect/Option"; import * as Speech from "expo-speech"; +import { useGT } from "gt-react-native"; import { ScrollView, TextInput, View } from "react-native"; import { AuthSettingsWriteScope, @@ -34,6 +35,7 @@ import { runSpeech } from "../voice-input/voiceDestination"; import { readAloudController } from "../read-aloud/playback"; export function ReadAloudSection() { + const gt = useGT(); const preferences = useAtomValue(mobilePreferencesAtom); const update = useAtomSet(updateMobilePreferencesAtom); const settings = AsyncResult.isSuccess(preferences) @@ -57,13 +59,17 @@ export function ReadAloudSection() { key: string; version: number; catalog: SpeechSynthesisCatalog; - error: string; - }>({ key: "", version: -1, catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, error: "" }); + failed: boolean; + }>({ key: "", version: -1, catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, failed: false }); const catalog = catalogState.key === catalogKey ? catalogState.catalog : EMPTY_SPEECH_SYNTHESIS_CATALOG; const catalogError = catalogState.key === catalogKey && catalogState.version === catalogVersion - ? catalogState.error || catalog.error || "" + ? catalogState.failed + ? gt( + "Could not load speech models. Check the environment connection and speech server setup.", + ) + : catalog.error || "" : ""; const model = settings.model || catalog.defaultModel; const [voices, setVoices] = useState([]); @@ -104,7 +110,12 @@ export function ReadAloudSection() { void runSpeech(getSpeechSynthesisModels(prepared, settings.provider), abort.signal).then( (value) => { if (!abort.signal.aborted) - setCatalogState({ key: catalogKey, version: catalogVersion, catalog: value, error: "" }); + setCatalogState({ + key: catalogKey, + version: catalogVersion, + catalog: value, + failed: false, + }); }, () => { if (!abort.signal.aborted) @@ -112,8 +123,7 @@ export function ReadAloudSection() { key: catalogKey, version: catalogVersion, catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, - error: - "Could not load speech models. Check the environment connection and speech server setup.", + failed: true, }); }, ); @@ -124,9 +134,11 @@ export function ReadAloudSection() { }, [prepared, settings.provider, catalogKey, catalogVersion]); const selectedModel = catalog.models.find((entry) => entry.id === model); const install = settings.provider === "local" ? selectedModel?.install : undefined; - const [installing, setInstalling] = useState(false); + // Keyed by environment and model, so switching models mid-download doesn't move the spinner. + const installKey = JSON.stringify([settings.environmentId, selectedModel?.id]); + const [installing, setInstalling] = useState(null); const downloading = - installing || install?.state === "downloading" || install?.state === "verifying"; + installing === installKey || install?.state === "downloading" || install?.state === "verifying"; // Waits for the catalog request in flight; refreshing again would abort it. const refreshing = catalogState.version !== catalogVersion; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Poll the environment's download progress while it runs. @@ -137,7 +149,8 @@ export function ReadAloudSection() { }, [downloading, refreshing]); const changeInstall = (action: "download" | "cancel" | "remove") => { if (!prepared || !selectedModel) return; - setInstalling(action === "download"); + const requestKey = installKey; + if (action === "download") setInstalling(requestKey); setError(""); void runSpeech( action === "download" @@ -151,12 +164,15 @@ export function ReadAloudSection() { () => setError( action === "download" - ? "Could not download the model. Check the environment's connection and disk space." - : "Could not change the model. Try again.", + ? gt( + "Could not download the model. Check the environment’s connection and disk space.", + ) + : gt("Could not change the model. Try again."), ), ) .finally(() => { - if (action === "download") setInstalling(false); + if (action === "download") + setInstalling((current) => (current === requestKey ? null : current)); setCatalogVersion((value) => value + 1); }); }; @@ -175,17 +191,24 @@ export function ReadAloudSection() { return ( <> { setSheet("source"); @@ -197,50 +220,52 @@ export function ReadAloudSection() { catalog.supportsModelSelection && catalog.models.length > 0 && ( setSheet("model")} /> )} {(settings.provider === "system" || (catalog.supportsVoiceSelection && catalog.models.length > 0)) && ( voice.id === settings.voice)?.name || settings.voice || - "Default" + gt("Default", { $context: "default voice" }) } onPress={() => setSheet("voice")} /> )} change({ speed: settings.speed >= 1.5 ? 0.75 : settings.speed + 0.25 }) } /> change({ backgroundPlayback })} /> change({ skipCodeBlocks })} /> state.id === "preview" && state.status !== "error" ? readAloudController.stop() : void readAloudController.start( "preview", - "This is T3 Code. Your agent's response is ready to read aloud.", + gt("This is T3 Code. Your agent’s response is ready to read aloud."), settings, ) } @@ -250,30 +275,32 @@ export function ReadAloudSection() { {install && prepared && selectedModel && ( {downloading ? ( changeInstall("cancel")} /> ) : install.state === "installed" ? ( changeInstall("remove")} /> ) : ( changeInstall("download")} /> @@ -282,12 +309,12 @@ export function ReadAloudSection() { )} {cloud && prepared && canManage && ( ) : saved === undefined ? ( -

Checking for an API key…

+

+ Checking for an API key… +

) : editingKey ? (
- +
{sources.length > 0 && ( { setSourceId(next); @@ -164,7 +180,7 @@ export function ReadAloudKeyDialog({ {draft.trim() && !credential ? (source?.invalidReferenceMessage ?? - "Enter an API key, not a URL or secret reference.") + gt("Enter an API key, not a URL or secret reference.")) : active - ? "Updating the key keeps read aloud on." - : `Anyone with access to ${environment.label} can bill this key.`} + ? gt("Updating the key keeps read aloud on.") + : gt("Anyone with access to {environment} can bill this key.", { + environment: environment.label, + })}

) : !saved ? ( -

Ask an administrator on {environment.label} to add an API key.

+

+ + Ask an administrator on {environment.label} to add an API key. + +

) : (

- Uses the API key saved on {environment.label}. This choice applies only to this - device. + + Uses the API key saved on {environment.label}. This choice applies only + to this device. +

)} @@ -222,12 +246,12 @@ export function ReadAloudKeyDialog({ disabled={busy} onClick={() => setRemove(true)} > - Remove key… + Remove key…
)} {connected && (remove ? ( @@ -238,11 +262,11 @@ export function ReadAloudKeyDialog({ disabled={busy} onClick={() => void saveKey(null, false)} > - Remove key + Remove key ) : editingKey ? ( ) : saved && !active ? ( ) : null)} diff --git a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx index a38f5f1deb14d..52522baf03dbb 100644 --- a/apps/web/src/components/settings/ReadAloudSettingsSection.tsx +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -1,4 +1,5 @@ import { useEffect, useState, useSyncExternalStore } from "react"; +import { T, useGT, Var } from "gt-react"; import * as Option from "effect/Option"; import { AsyncResult } from "effect/reactivity"; import { @@ -22,7 +23,11 @@ import { type SpeechSynthesisCatalog, type SpeechSynthesisProvider, } from "@t3tools/contracts"; -import { useClientSettings, updateClientSettings } from "../../hooks/useSettings"; +import { + getClientSettings, + useClientSettings, + updateClientSettings, +} from "../../hooks/useSettings"; import { useEnvironments } from "../../state/environments"; import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; @@ -65,6 +70,7 @@ function LocalSpeechModel({ recommended, refreshing, onSelect, + onDownloaded, onChanged, }: { prepared: PreparedConnection; @@ -74,8 +80,10 @@ function LocalSpeechModel({ /** A catalog request is in flight; polling waits for it rather than aborting it. */ refreshing: boolean; onSelect: () => void; + onDownloaded: () => void; onChanged: () => void; }) { + const gt = useGT(); const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); const [requesting, setRequesting] = useState(false); const [error, setError] = useState(""); @@ -92,19 +100,21 @@ function LocalSpeechModel({ setRequesting(true); setError(""); try { - await runEnvironmentSpeech( + const catalog = await runEnvironmentSpeech( action === "download" ? downloadSpeechSynthesisModel(prepared, model.id) : action === "cancel" ? cancelSpeechSynthesisModelDownload(prepared, model.id) : removeSpeechSynthesisModel(prepared, model.id), ); - if (action === "download") onSelect(); + // A cancelled download also resolves, with the model still downloadable. + const installed = catalog.models.find((entry) => entry.id === model.id)?.install?.state; + if (action === "download" && installed === "installed") onDownloaded(); } catch { setError( action === "download" - ? "Could not download the model. Check the environment's connection and disk space." - : "Could not change the model. Try again.", + ? gt("Could not download the model. Check the environment’s connection and disk space.") + : gt("Could not change the model. Try again."), ); } setRequesting(false); @@ -123,24 +133,28 @@ function LocalSpeechModel({ {recommended && ( - Recommended + {gt("Recommended")} )}

- {model.description} {formatSize(install.size)} - {install.state === "installed" ? "." : " download."} + {model.description}{" "} + {install.state === "installed" + ? gt("{size}.", { size: formatSize(install.size) }) + : gt("{size} download.", { size: formatSize(install.size) })}

{install.linkedFrom && (

- Using your file at {install.linkedFrom} + + Using your file at {install.linkedFrom} +

)} {downloading && (

{install.state === "verifying" - ? "Verifying download…" - : `${Math.round(progress)}% downloaded`} + ? gt("Verifying download…") + : gt("{percent}% downloaded", { percent: Math.round(progress) })}

)} @@ -169,7 +183,7 @@ function LocalSpeechModel({ ) : selected ? ( ) : ( )} {install.state === "installed" && ( @@ -202,8 +216,8 @@ function LocalSpeechModel({ disabled={!canManage || requesting} aria-label={ install.linkedFrom - ? `Stop using your ${model.name} file; the file stays on disk` - : `Delete ${model.name}` + ? gt("Stop using your {name} file; the file stays on disk", { name: model.name }) + : gt("Delete {name}", { name: model.name }) } onClick={() => void run("remove")} > @@ -224,6 +238,7 @@ function LocalSpeechModelLink({ prepared: PreparedConnection; onChanged: () => void; }) { + const gt = useGT(); const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); const canReadFiles = useEnvironmentScope(prepared.environmentId, AuthFilesystemReadScope); const [path, setPath] = useState(""); @@ -240,7 +255,7 @@ function LocalSpeechModelLink({ void runEnvironmentSpeech(linkSpeechSynthesisModels(prepared, path)) .then( () => setPath(""), - () => setError("No speech model file was found at that path."), + () => setError(gt("No speech model file was found at that path.")), ) .finally(() => { setLinking(false); @@ -251,8 +266,8 @@ function LocalSpeechModelLink({
setPath(event.target.value)} /> @@ -263,13 +278,14 @@ function LocalSpeechModelLink({ )}
); } export function ReadAloudSettingsSection() { + const gt = useGT(); const settings = useClientSettings((value) => value.readAloud); const { environments } = useEnvironments(); @@ -285,13 +301,17 @@ export function ReadAloudSettingsSection() { key: string; version: number; catalog: SpeechSynthesisCatalog; - error: string; - }>({ key: "", version: -1, catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, error: "" }); + failed: boolean; + }>({ key: "", version: -1, catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, failed: false }); const catalog = catalogState.key === catalogKey ? catalogState.catalog : EMPTY_SPEECH_SYNTHESIS_CATALOG; const error = catalogState.key === catalogKey && catalogState.version === catalogVersion - ? catalogState.error || catalog.error || "" + ? catalogState.failed + ? gt( + "Could not load speech models. Check the selected environment and provider configuration.", + ) + : catalog.error || "" : ""; const model = settings.model || catalog.defaultModel; const localModels = @@ -332,7 +352,12 @@ export function ReadAloudSettingsSection() { ).then( (result) => { if (!abort.signal.aborted) - setCatalogState({ key: catalogKey, version: catalogVersion, catalog: result, error: "" }); + setCatalogState({ + key: catalogKey, + version: catalogVersion, + catalog: result, + failed: false, + }); }, () => { if (!abort.signal.aborted) @@ -340,8 +365,7 @@ export function ReadAloudSettingsSection() { key: catalogKey, version: catalogVersion, catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, - error: - "Could not load speech models. Check the selected environment and provider configuration.", + failed: true, }); }, ); @@ -368,20 +392,28 @@ export function ReadAloudSettingsSection() { (entry) => entry.environmentId === settings.environmentId, ); return ( - + - {selectedEnvironment?.label ?? "This environment"} has no{" "} - {CLOUD_SPEECH_PROVIDER_NAMES[cloudProvider]} API key. Add one with the key button. + {selectedEnvironment + ? gt("{environment} has no {company} API key. Add one with the key button.", { + environment: selectedEnvironment.label, + company: CLOUD_SPEECH_PROVIDER_NAMES[cloudProvider], + }) + : gt("This environment has no {company} API key. Add one with the key button.", { + company: CLOUD_SPEECH_PROVIDER_NAMES[cloudProvider], + })} ) : remote && error ? ( {error} ) : ( - "Read completed replies with the play button beside Copy. Hosted providers receive the response text through the selected environment; a local model runs on it." + gt( + "Read completed replies with the play button beside Copy. Hosted providers receive the response text through the selected environment; a local model runs on it.", + ) ) } control={ @@ -415,7 +447,7 @@ export function ReadAloudSettingsSection() { > @@ -427,14 +459,16 @@ export function ReadAloudSettingsSection() { )} {settings.provider === "local" - ? (selectedEnvironment?.label ?? "Chosen environment (unavailable)") - : READ_ALOUD_LABELS[settings.provider]} - {remote && settings.provider !== "local" && ( - - {" via "} - {selectedEnvironment?.label ?? "unavailable environment"} - - )} + ? (selectedEnvironment?.label ?? gt("Chosen environment (unavailable)")) + : remote + ? gt("{provider} via {environment}", { + provider: READ_ALOUD_LABELS[settings.provider], + environment: + selectedEnvironment?.label ?? gt("unavailable environment"), + }) + : settings.provider === "system" + ? gt("System voices") + : gt("Off", { $context: "read aloud disabled" })} @@ -443,21 +477,25 @@ export function ReadAloudSettingsSection() { - Off + {gt("Off", { $context: "read aloud disabled" })} - On this device + + On this device + - System voices + {gt("System voices")} {environments.length > 0 && ( - On an environment + + On an environment + {environments.map((environment) => ( ( - Cloud via {environment.label} + + + Cloud via {environment.label} + + {CloudSpeechProvider.literals.map((provider) => ( @@ -489,7 +534,7 @@ export function ReadAloudSettingsSection() { ))} {remote && !selectedEnvironment && ( - Chosen environment (unavailable) + {gt("Chosen environment (unavailable)")} )} @@ -501,7 +546,7 @@ export function ReadAloudSettingsSection() { size="icon-sm" type="button" variant="ghost" - aria-label="Manage read-aloud key" + aria-label={gt("Manage read-aloud key")} onClick={() => setPendingCloud({ provider: cloudProvider, @@ -513,7 +558,9 @@ export function ReadAloudSettingsSection() { } /> - Manage key + + Manage key + )}
@@ -547,14 +594,16 @@ export function ReadAloudSettingsSection() { <> {prepared && localModels.length > 0 && (
{localModels.map((entry) => ( change({ model: entry.id, voice: "" })} + onDownloaded={() => { + // Settings may have moved on while the model downloaded. + const current = getClientSettings().readAloud; + if ( + current.provider === "local" && + current.environmentId === prepared.environmentId + ) + void updateClientSettings({ + readAloud: { ...current, model: entry.id, voice: "" }, + }); + }} onChanged={refreshCatalog} /> ))} @@ -574,8 +634,8 @@ export function ReadAloudSettingsSection() { )} {cloudProvider && catalog.supportsModelSelection && catalog.models.length > 0 && ( - + {catalog.models.find((entry) => entry.id === model)?.name || model || - "Choose a model"} + gt("Choose a model")} @@ -604,8 +664,8 @@ export function ReadAloudSettingsSection() { {(settings.provider === "system" || (catalog.supportsVoiceSelection && catalog.models.length > 0)) && ( - + - {voices.find((entry) => entry.id === settings.voice)?.name || "Default"} + {voices.find((entry) => entry.id === settings.voice)?.name || + gt("Default", { $context: "default voice" })} - Default + + {gt("Default", { $context: "default voice" })} + {voices.map((voice) => ( {voice.name} @@ -630,8 +693,8 @@ export function ReadAloudSettingsSection() { ) : ( change({ voice: event.target.value })} /> @@ -640,8 +703,8 @@ export function ReadAloudSettingsSection() { /> )} - + @@ -663,22 +726,24 @@ export function ReadAloudSettingsSection() { } /> change({ skipCodeBlocks })} /> } /> {state.id === "read-aloud-preview" && state.status !== "error" - ? "Stop preview" - : "Play preview"} + ? gt("Stop preview") + : gt("Play preview")} } /> diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index c2c1e25503908..b1976141718c3 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -581,9 +581,11 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "read-aloud", - title: "Read aloud", + title: msg("Read aloud"), to: "/settings/voice", - searchTerms: ["tts text to speech speak read aloud OpenAI Grok OpenRouter voice playback"], + searchTerms: [ + msg("tts text to speech speak read aloud OpenAI Grok OpenRouter ElevenLabs voice playback"), + ], }, { id: "voice-microphone", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 5aca70101b1f3..81c8665757e19 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} hat mit „Augen“ reagiert", "0c982111ac348e9f": "Du", "766ea446df1695f7": "Beantworte die Frage, um Nachrichten in der Warteschlange zu bearbeiten", + "6e4d05cd77caff7c": "Wiedergabe konnte nicht fortgesetzt werden.", + "b02cc7b7adaa2361": "Diese Antwort konnte nicht vorgelesen werden.", "257dc29de5b1f1f7": "Kontext, kein Code", "edb97296086ba31e": "{count, plural, one {{count} Datei} other {{count} Dateien}}", "556df31b330166ff": "Gib einen Namen für diese Ansicht ein.", @@ -3841,6 +3843,11 @@ "de5c52c3f47ff209": "Von T3 Code gesendet", "ded43a280aed9f20": "Thread öffnen", "7635dd64bbbe10ec": "Automatisierung öffnen", + "154bec57dbece73c": "Vorlesen beenden", + "e3c3d4bcfa9727b9": "Vorlesen fortsetzen", + "0eceb5780908eb6c": "Vorlesen", + "09a3f02127015c7d": "Vorlesen fehlgeschlagen", + "81923647f1ef9740": "Sprachausgabe abbrechen", "6327e4ffa0f2366d": "Pull Requests nicht verfügbar", "90062342f04966ff": "Aktualisiere den T3-Code-Server dieser Umgebung, um Pull Requests zu durchsuchen.", "5e7157db126f1641": "Issues nicht verfügbar", @@ -9144,6 +9151,91 @@ "5c0c973276a61fdb": "Berechtigung für Pull-Request-Routing konnte nicht gespeichert werden", "1bfcffe8411e2439": "Pull-Request-Routing für {environment}", "ae4761ddc038b102": "Rechner, denen du hier vertraust, können PR-Daten über den Versionskontrollzugriff des jeweils anderen lesen. Aktiviere es auf beiden Rechnern. „Lesen und handeln“ kann weitergehende Berechtigungen nutzen als der Rechner, dem sie gehören. Gilt nur für dieses Gerät.", + "65a238ad6bebf802": "Antworten mit {name} vorlesen?", + "bfbaa4965c146e7c": "Alle, die {company} auf {environment} zum Diktieren oder Vorlesen nutzen, verlieren den Zugriff.", + "b9e06e668bd9bff0": "Antworten, die Sie abspielen, werden über {environment} an {company} gesendet und über dessen API-Schlüssel abgerechnet. Der Schlüssel wird mit dem Diktat geteilt.", + "09f85302ef58020c": "Wenn Sie den Schlüssel aktualisieren, bleibt Vorlesen aktiviert.", + "6e58953ca9c7fad5": "Alle mit Zugriff auf {environment} können über diesen Schlüssel abrechnen.", + "cf0740520675dcb9": [ + "Verbinden Sie sich mit ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ", um fortzufahren." + ], + "b0900f4938210634": "API-Schlüssel", + "60609aae479dd41c": "Das Modell konnte nicht heruntergeladen werden. Prüfen Sie die Verbindung und den Speicherplatz der Umgebung.", + "1405f6ff92c1041a": "Das Modell konnte nicht geändert werden. Versuchen Sie es erneut.", + "c59720248f69d5aa": "Empfohlen", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "{size} Download.", + "c522c5460548c481": "Downloadfortschritt von {name}", + "58a4b7a47e362024": "Download wird verifiziert…", + "8ee326cccca4ffe0": "{percent} % heruntergeladen", + "f36b40c99b8c221f": "Download von {name} abbrechen", + "53b05fd56e4de55b": "Deine Datei {name} nicht mehr verwenden; die Datei bleibt auf der Festplatte", + "34901bb929deb832": "{name} löschen", + "69a7c539add37d29": "Unter diesem Pfad wurde keine Sprachmodelldatei gefunden.", + "b98b8459bc0fc482": "Pfad zu einer Modelldatei oder einem Modellordner, der bereits in dieser Umgebung liegt", + "9e6dabb14a4947e5": "Bereits anderswo heruntergeladen? Füge den Pfad der Modelldatei oder des Modellordners ein", + "b4b7580d21c53b5f": "Sprachmodelle konnten nicht geladen werden. Prüfen Sie die ausgewählte Umgebung und die Anbieterkonfiguration.", + "293d67c7b56e7b69": "Sprachanbieter", + "7bc4af4101c8997b": "{environment} hat keinen {company}-API-Schlüssel. Fügen Sie über die Schlüssel-Schaltfläche einen hinzu.", + "944dfe57d9653d32": "Diese Umgebung hat keinen {company}-API-Schlüssel. Fügen Sie über die Schlüssel-Schaltfläche einen hinzu.", + "1c3796a6ec44558f": "Lesen Sie fertige Antworten mit der Wiedergabe-Schaltfläche neben „Kopieren“ vor. Gehostete Anbieter erhalten den Antworttext über die ausgewählte Umgebung; ein lokales Modell läuft darauf.", + "ee6859d2ad7f5842": "Vorlese-Anbieter", + "710d3e4f0243014c": "Gewählte Umgebung (nicht verfügbar)", + "61088464d1b7174d": "nicht verfügbare Umgebung", + "52e8f8accdca2d32": "Systemstimmen", + "17076b27f1f3ada5": "Aus", + "0097b134ae6e9d9c": "Vorlese-Schlüssel verwalten", + "09bc28a37e6caf92": "Wird einmal in die ausgewählte Umgebung heruntergeladen, die Antworten vorliest, ohne dass der Text sie verlässt.", + "d33ab3b324ba0b36": "Vorlese-Modelle", + "3fb69cb2e760f23d": "Sprachmodell", + "2d2ee6c94580e79f": "Wählen Sie ein Sprachmodell aus dem Katalog des Anbieters.", + "44e370c9cc900c63": "Vorlese-Modell", + "9fa6e93a8218ad60": "Stimme", + "eae80365006fbe17": "Ohne Angabe wird die Standardstimme des Anbieters verwendet.", + "5a640ef031aed4a2": "Vorlese-Stimme", + "f7323911c24ed501": "Standard", + "b9c9fc9b61d7243e": "Standardstimme", + "c10f66d628754b10": "Geschwindigkeit", + "bff81cb00fc73544": "Wiedergabegeschwindigkeit.", + "936895b764543aea": "Vorlesegeschwindigkeit", + "2fc5076786a6b6ed": "Codeblöcke überspringen", + "0fed42221c860bd6": "Liest Fließtext und Inline-Bezeichner, ohne Codeblöcke vorzulesen.", + "951a30714876977f": "Codeblöcke beim Vorlesen überspringen", + "bec2c35646e0496a": "Vorschau", + "8ed4191b261076ff": "Spielt ein kurzes Beispiel mit dem ausgewählten Sprachanbieter ab.", + "4b009ef01c76df8e": "Das ist T3 Code. Die Antwort Ihres Agenten kann jetzt vorgelesen werden.", + "0dde517387ea2d57": "Vorschau beenden", + "88f2bec553b72827": "Vorschau abspielen", + "f7158c1af1da3afb": [ + "Deine Datei unter ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " wird verwendet" + ], + "bff944189ba9c100": "Herunterladen", + "b3976c9787134fd1": "Ausgewählt", + "f4c5cba0cd5dbb68": "Modell verwenden", + "0b5ab0399461fdbd": "Vorhandenes verwenden", + "26aafec418058787": "Auf diesem Gerät", + "23196cabaa71f1da": "In einer Umgebung", + "3ba49a214600d0ac": [ + "Cloud über ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Schlüssel verwalten", "02bca2d9c90e5f1e": "{value} s", "af22f973466903c3": "{value} Min.", "401ba3f2391d8742": "{value} Std.", @@ -11109,7 +11201,6 @@ "97c969a0f9c64233": "Nach 10 Minuten", "bf7f24afa7084dd7": "Nach 15 Minuten", "590df316b67cc7d5": "Nach 1 Stunde", - "c59720248f69d5aa": "Empfohlen", "e4369ea318964a77": "Schneller", "cd9732fb0b7326e3": "Genauer", "62900eb52209c2e3": "Ausgewogene Genauigkeit und Geschwindigkeit für deine ausgewählten Sprachen in Handys Referenz-Benchmarks.", @@ -11120,12 +11211,6 @@ "665cbb7042a42206": "Übersetzen", "82aa50f539d02537": "Kann aus Sprache in einer anderen Sprache englischen Text schreiben. Schalte „Ins Englische übersetzen“ ein, um das zu nutzen.", "dc23ce436a29363d": "{count, plural, one {{count} Sprache} other {{count} Sprachen}}", - "c522c5460548c481": "Downloadfortschritt von {name}", - "58a4b7a47e362024": "Download wird verifiziert…", - "8ee326cccca4ffe0": "{percent} % heruntergeladen", - "f36b40c99b8c221f": "Download von {name} abbrechen", - "53b05fd56e4de55b": "Deine Datei {name} nicht mehr verwenden; die Datei bleibt auf der Festplatte", - "34901bb929deb832": "{name} löschen", "58d9cedba566716c": "Wörter hinzufügen, durch Kommas getrennt", "8ce2d4078f890b77": "Ein Wort oder eine Phrase zu {label} hinzufügen", "6f40d219fdbe4ae9": "Alias für {term}", @@ -11172,8 +11257,6 @@ "1ce93a052681b78a": "Der Download konnte nicht abgebrochen werden", "51fd61b9c85dec5d": "Das Modell konnte nicht gelöscht werden", "3d4be5cb172d6f91": "Ein Modell aus diesem Pfad konnte nicht verwendet werden", - "b98b8459bc0fc482": "Pfad zu einer Modelldatei oder einem Modellordner, der bereits in dieser Umgebung liegt", - "9e6dabb14a4947e5": "Bereits anderswo heruntergeladen? Füge den Pfad der Modelldatei oder des Modellordners ein", "2060246c448d1de0": "Warte auf die Verbindung der Umgebung", "c32c85efb80dc740": "Testtranskript", "4b2f68f90eb004f6": "Keine Sprache erkannt. Versuch es erneut.", @@ -11187,8 +11270,6 @@ "5c3711f9ed600d2a": "Transkribieren mit", "dccbcc6f313dea7e": "{label} kann Audio nicht lokal transkribieren. Wähle ein anderes Ziel.", "817dbf1c068b62e7": "Wo deine Sprache in Text umgewandelt wird.", - "710d3e4f0243014c": "Gewählte Umgebung (nicht verfügbar)", - "61088464d1b7174d": "nicht verfügbare Umgebung", "71184e5a54a69f1d": "Der Anbieter erkennt deine Sprache automatisch.", "ffb2653eb2d9fc1a": "{model} erkennt die Sprache automatisch.", "773cbfca7c466cc4": "{model} verwendet eine feste Sprache.", @@ -11213,18 +11294,6 @@ "c652ed4a9a70f77f": "Eigene Bereinigungsanweisungen", "1c2d9ac371d77eea": "Korrektursignal", "4f6141a8af8dc570": "Die Phrase, die du sagst, um einen Fehler zu korrigieren, etwa „streich das“.", - "f7158c1af1da3afb": [ - "Deine Datei unter ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " wird verwendet" - ], - "bff944189ba9c100": "Herunterladen", - "b3976c9787134fd1": "Ausgewählt", - "f4c5cba0cd5dbb68": "Modell verwenden", "2c5c798252f91fdc": "Hinzufügen", "38b344bfa7d50343": "Alias", "c893707203cb6aee": "Verbinde zuerst eine Umgebung.", @@ -11233,19 +11302,9 @@ "111dbc8f88feacff": "Keine passenden Sprachen.", "003aa9115365f752": "Sortieren nach", "736406a96ddadcd8": "Nur heruntergeladene", - "0b5ab0399461fdbd": "Vorhandenes verwenden", "790951b4fc82052f": "Modell testen", "a3eda37e8d337ebb": "Sprich einen Satz. Die Bereinigung wird übersprungen, damit du genau siehst, was das Modell gehört hat.", "c613b9c5d54f3c91": "Mikrofone aktualisieren", - "23196cabaa71f1da": "In einer Umgebung", - "3ba49a214600d0ac": [ - "Cloud über ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Gewählte Umgebung (nicht verfügbar)", "e69e34d4f44d4136": "Integriert", "ae0b91ed52736998": "Verwendet den neuesten Commit des verfolgten Remote-Branches des Basis-Branches, auch wenn der Name abweicht. Andernfalls den gleichnamigen Branch auf origin. Fehlt dieser Remote-Branch, wird dein lokaler Branch verwendet.", @@ -11426,6 +11485,7 @@ "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", "bcb520297a9ae143": "beta schneller worktree checkout klonen apfs copy-on-write cache macos geschwindigkeit", "4c83ac419da342bd": "mikrofon audio senden diktat ziel sprache spracheingabe stt transkription umgebung rechner einwilligung datenschutz cloud OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts text to speech sprachausgabe vorlesen sprechen stimme wiedergabe OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "mikrofon eingabe audio gerät reihenfolge priorität bevorzugt", "22811f405e0b4b28": "sprache spracheingabe tastatur hotkey halten umschalten auto", "e27bccf50397d9fe": "sprache spracheingabe übersetzen englisch automatisch erkennen", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 246e11939fd89..8dd2c64f40cbc 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} reacted with eyes emoji", "0c982111ac348e9f": "You", "766ea446df1695f7": "Answer the question to edit queued messages", + "6e4d05cd77caff7c": "Could not resume speech.", + "b02cc7b7adaa2361": "Could not read this response.", "257dc29de5b1f1f7": "Context, no code", "edb97296086ba31e": "{count, plural, one {{count} file} other {{count} files}}", "556df31b330166ff": "Enter a name for this view.", @@ -3839,6 +3841,11 @@ "de5c52c3f47ff209": "Sent by T3 Code", "ded43a280aed9f20": "Open thread", "7635dd64bbbe10ec": "Open automation", + "154bec57dbece73c": "Stop reading", + "e3c3d4bcfa9727b9": "Resume reading", + "0eceb5780908eb6c": "Read aloud", + "09a3f02127015c7d": "Could not read aloud", + "81923647f1ef9740": "Cancel speech generation", "6327e4ffa0f2366d": "Pull requests unavailable", "90062342f04966ff": "Update this environment's T3 Code server to browse pull requests.", "5e7157db126f1641": "Issues unavailable", @@ -9152,6 +9159,90 @@ "5c0c973276a61fdb": "Could not save pull request routing permission", "1bfcffe8411e2439": "{environment} pull request routing", "ae4761ddc038b102": "Machines you trust here can read PR data through each other's source control access. Enable both machines. Read and act may use broader permissions than the machine that owns them. This applies only to this device.", + "65a238ad6bebf802": "Read replies aloud with {name}?", + "bfbaa4965c146e7c": "Everyone using {company} for dictation or read aloud on {environment} will lose access.", + "b9e06e668bd9bff0": "Replies you play are sent to {company} through {environment}, which bills its API key. The key is shared with dictation.", + "09f85302ef58020c": "Updating the key keeps read aloud on.", + "6e58953ca9c7fad5": "Anyone with access to {environment} can bill this key.", + "cf0740520675dcb9": [ + "Connect to ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " to continue." + ], + "b0900f4938210634": "API key", + "60609aae479dd41c": "Could not download the model. Check the environment’s connection and disk space.", + "1405f6ff92c1041a": "Could not change the model. Try again.", + "c59720248f69d5aa": "Recommended", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "{size} download.", + "c522c5460548c481": "{name} download progress", + "58a4b7a47e362024": "Verifying download…", + "8ee326cccca4ffe0": "{percent}% downloaded", + "f36b40c99b8c221f": "Cancel {name} download", + "53b05fd56e4de55b": "Stop using your {name} file; the file stays on disk", + "34901bb929deb832": "Delete {name}", + "69a7c539add37d29": "No speech model file was found at that path.", + "b98b8459bc0fc482": "Path to a model file or folder already on this environment", + "9e6dabb14a4947e5": "Already downloaded elsewhere? Paste the model file or folder path", + "b4b7580d21c53b5f": "Could not load speech models. Check the selected environment and provider configuration.", + "293d67c7b56e7b69": "Speech provider", + "7bc4af4101c8997b": "{environment} has no {company} API key. Add one with the key button.", + "944dfe57d9653d32": "This environment has no {company} API key. Add one with the key button.", + "1c3796a6ec44558f": "Read completed replies with the play button beside Copy. Hosted providers receive the response text through the selected environment; a local model runs on it.", + "ee6859d2ad7f5842": "Read-aloud provider", + "710d3e4f0243014c": "Chosen environment (unavailable)", + "61088464d1b7174d": "unavailable environment", + "52e8f8accdca2d32": "System voices", + "17076b27f1f3ada5": "Off", + "0097b134ae6e9d9c": "Manage read-aloud key", + "09bc28a37e6caf92": "Downloaded once to the selected environment, which reads replies without the text leaving it.", + "d33ab3b324ba0b36": "Read-aloud models", + "3fb69cb2e760f23d": "Speech model", + "2d2ee6c94580e79f": "Choose a speech model from the provider catalog.", + "44e370c9cc900c63": "Read-aloud model", + "9fa6e93a8218ad60": "Voice", + "eae80365006fbe17": "An empty value uses the provider’s default voice.", + "5a640ef031aed4a2": "Read-aloud voice", + "f7323911c24ed501": "Default", + "b9c9fc9b61d7243e": "Default voice", + "c10f66d628754b10": "Speed", + "bff81cb00fc73544": "Playback speed.", + "936895b764543aea": "Read-aloud speed", + "2fc5076786a6b6ed": "Skip code blocks", + "0fed42221c860bd6": "Read the prose and inline identifiers without narrating fenced code blocks.", + "951a30714876977f": "Skip code blocks when reading", + "bec2c35646e0496a": "Preview", + "8ed4191b261076ff": "Play a short sample using the selected speech provider.", + "4b009ef01c76df8e": "This is T3 Code. Your agent’s response is ready to read aloud.", + "0dde517387ea2d57": "Stop preview", + "88f2bec553b72827": "Play preview", + "f7158c1af1da3afb": [ + "Using your file at ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "bff944189ba9c100": "Download", + "b3976c9787134fd1": "Selected", + "f4c5cba0cd5dbb68": "Use model", + "0b5ab0399461fdbd": "Use existing", + "26aafec418058787": "On this device", + "23196cabaa71f1da": "On an environment", + "3ba49a214600d0ac": [ + "Cloud via ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Manage key", "02bca2d9c90e5f1e": "{value}s", "af22f973466903c3": "{value}m", "401ba3f2391d8742": "{value}h", @@ -11118,7 +11209,6 @@ "97c969a0f9c64233": "After 10 minutes", "bf7f24afa7084dd7": "After 15 minutes", "590df316b67cc7d5": "After 1 hour", - "c59720248f69d5aa": "Recommended", "e4369ea318964a77": "Faster", "cd9732fb0b7326e3": "More accurate", "62900eb52209c2e3": "Balanced accuracy and speed for your selected languages on Handy’s reference benchmarks.", @@ -11129,12 +11219,6 @@ "665cbb7042a42206": "Translate", "82aa50f539d02537": "Can write English text from speech in another language. Turn on Translate to English to use it.", "dc23ce436a29363d": "{count, plural, one {{count} language} other {{count} languages}}", - "c522c5460548c481": "{name} download progress", - "58a4b7a47e362024": "Verifying download…", - "8ee326cccca4ffe0": "{percent}% downloaded", - "f36b40c99b8c221f": "Cancel {name} download", - "53b05fd56e4de55b": "Stop using your {name} file; the file stays on disk", - "34901bb929deb832": "Delete {name}", "58d9cedba566716c": "Add words, separated by commas", "8ce2d4078f890b77": "Add a word or phrase to the {label}", "6f40d219fdbe4ae9": "Alias for {term}", @@ -11181,8 +11265,6 @@ "1ce93a052681b78a": "Could not cancel the download", "51fd61b9c85dec5d": "Could not delete the model", "3d4be5cb172d6f91": "Could not use a model from that path", - "b98b8459bc0fc482": "Path to a model file or folder already on this environment", - "9e6dabb14a4947e5": "Already downloaded elsewhere? Paste the model file or folder path", "2060246c448d1de0": "Waiting for the environment to connect", "c32c85efb80dc740": "Test transcript", "4b2f68f90eb004f6": "No speech recognized. Try again.", @@ -11196,8 +11278,6 @@ "5c3711f9ed600d2a": "Transcribe with", "dccbcc6f313dea7e": "{label} can’t transcribe audio locally. Choose another destination.", "817dbf1c068b62e7": "Where your speech is turned into text.", - "710d3e4f0243014c": "Chosen environment (unavailable)", - "61088464d1b7174d": "unavailable environment", "71184e5a54a69f1d": "The provider detects your language automatically.", "ffb2653eb2d9fc1a": "{model} detects the language automatically.", "773cbfca7c466cc4": "{model} uses one fixed language.", @@ -11222,17 +11302,6 @@ "c652ed4a9a70f77f": "Custom cleanup instructions", "1c2d9ac371d77eea": "Correction cue", "4f6141a8af8dc570": "The phrase you say to fix a mistake, like “scratch that”.", - "f7158c1af1da3afb": [ - "Using your file at ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], - "bff944189ba9c100": "Download", - "b3976c9787134fd1": "Selected", - "f4c5cba0cd5dbb68": "Use model", "2c5c798252f91fdc": "Add", "38b344bfa7d50343": "Alias", "c893707203cb6aee": "Connect an environment first.", @@ -11241,19 +11310,9 @@ "111dbc8f88feacff": "No languages match.", "003aa9115365f752": "Sort by", "736406a96ddadcd8": "Downloaded only", - "0b5ab0399461fdbd": "Use existing", "790951b4fc82052f": "Test model", "a3eda37e8d337ebb": "Say a sentence. Cleanup is skipped, so you see exactly what the model heard.", "c613b9c5d54f3c91": "Refresh microphones", - "23196cabaa71f1da": "On an environment", - "3ba49a214600d0ac": [ - "Cloud via ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Chosen environment (unavailable)", "e69e34d4f44d4136": "Built-in", "ae0b91ed52736998": "Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing.", @@ -11434,6 +11493,7 @@ "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", "bcb520297a9ae143": "beta fast worktree checkout clone apfs copy-on-write cache macos speed", "4c83ac419da342bd": "send microphone audio dictation destination speech voice stt transcription environment machine consent privacy cloud OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts text to speech speak read aloud OpenAI Grok OpenRouter ElevenLabs voice playback", "f9c000e92379d027": "mic input audio device order priority preferred", "22811f405e0b4b28": "speech voice keyboard hotkey hold toggle auto", "e27bccf50397d9fe": "speech voice translate english auto detect", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 38fe66011ed56..e0c8f5a53634b 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} reaccionó con el emoji de ojos", "0c982111ac348e9f": "Tú", "766ea446df1695f7": "Responde a la pregunta para editar los mensajes en cola", + "6e4d05cd77caff7c": "No se pudo reanudar la lectura.", + "b02cc7b7adaa2361": "No se pudo leer esta respuesta.", "257dc29de5b1f1f7": "Contexto, sin código", "edb97296086ba31e": "{count, plural, one {{count} archivo} other {{count} archivos}}", "556df31b330166ff": "Escribe un nombre para esta vista.", @@ -3837,6 +3839,11 @@ "de5c52c3f47ff209": "Enviado por T3 Code", "ded43a280aed9f20": "Abrir hilo", "7635dd64bbbe10ec": "Abrir automatización", + "154bec57dbece73c": "Dejar de leer", + "e3c3d4bcfa9727b9": "Reanudar lectura", + "0eceb5780908eb6c": "Leer en voz alta", + "09a3f02127015c7d": "No se pudo leer en voz alta", + "81923647f1ef9740": "Cancelar la generación de voz", "6327e4ffa0f2366d": "Pull requests no disponibles", "90062342f04966ff": "Actualiza el servidor de T3 Code de este entorno para explorar pull requests.", "5e7157db126f1641": "Issues no disponibles", @@ -9142,6 +9149,90 @@ "5c0c973276a61fdb": "No se pudo guardar el permiso de enrutamiento de pull requests", "1bfcffe8411e2439": "Enrutamiento de pull requests de {environment}", "ae4761ddc038b102": "Las máquinas en las que confías aquí pueden leer datos de PR a través del acceso al control de versiones de las otras. Activa ambas máquinas. Leer y actuar puede usar permisos más amplios que los de la máquina propietaria. Solo se aplica a este dispositivo.", + "65a238ad6bebf802": "¿Leer las respuestas en voz alta con {name}?", + "bfbaa4965c146e7c": "Todas las personas que usan {company} para dictado o lectura en voz alta en {environment} perderán el acceso.", + "b9e06e668bd9bff0": "Las respuestas que reproduces se envían a {company} a través de {environment}, que paga con su clave de API. La clave se comparte con el dictado.", + "09f85302ef58020c": "Actualizar la clave mantiene activada la lectura en voz alta.", + "6e58953ca9c7fad5": "Cualquiera con acceso a {environment} puede cargar costes a esta clave.", + "cf0740520675dcb9": [ + "Conéctate a ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " para continuar." + ], + "b0900f4938210634": "Clave de API", + "60609aae479dd41c": "No se pudo descargar el modelo. Comprueba la conexión y el espacio en disco del entorno.", + "1405f6ff92c1041a": "No se pudo cambiar el modelo. Inténtalo de nuevo.", + "c59720248f69d5aa": "Recomendado", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "Descarga de {size}.", + "c522c5460548c481": "Progreso de la descarga de {name}", + "58a4b7a47e362024": "Verificando la descarga…", + "8ee326cccca4ffe0": "{percent}% descargado", + "f36b40c99b8c221f": "Cancelar la descarga de {name}", + "53b05fd56e4de55b": "Dejar de usar tu archivo de {name}; el archivo se queda en el disco", + "34901bb929deb832": "Eliminar {name}", + "69a7c539add37d29": "No se encontró ningún archivo de modelo de voz en esa ruta.", + "b98b8459bc0fc482": "Ruta a un archivo o carpeta de modelo que ya está en este entorno", + "9e6dabb14a4947e5": "¿Ya lo descargaste en otro sitio? Pega la ruta del archivo o la carpeta del modelo", + "b4b7580d21c53b5f": "No se pudieron cargar los modelos de voz. Comprueba el entorno seleccionado y la configuración del proveedor.", + "293d67c7b56e7b69": "Proveedor de voz", + "7bc4af4101c8997b": "{environment} no tiene una clave de API de {company}. Añade una con el botón de la llave.", + "944dfe57d9653d32": "Este entorno no tiene una clave de API de {company}. Añade una con el botón de la llave.", + "1c3796a6ec44558f": "Lee las respuestas completadas con el botón de reproducir junto a Copiar. Los proveedores alojados reciben el texto a través del entorno seleccionado; un modelo local se ejecuta en él.", + "ee6859d2ad7f5842": "Proveedor de lectura en voz alta", + "710d3e4f0243014c": "Entorno elegido (no disponible)", + "61088464d1b7174d": "entorno no disponible", + "52e8f8accdca2d32": "Voces del sistema", + "17076b27f1f3ada5": "Desactivado", + "0097b134ae6e9d9c": "Gestionar la clave de lectura en voz alta", + "09bc28a37e6caf92": "Se descarga una vez en el entorno seleccionado, que lee las respuestas sin que el texto salga de él.", + "d33ab3b324ba0b36": "Modelos de lectura en voz alta", + "3fb69cb2e760f23d": "Modelo de voz", + "2d2ee6c94580e79f": "Elige un modelo de voz del catálogo del proveedor.", + "44e370c9cc900c63": "Modelo de lectura en voz alta", + "9fa6e93a8218ad60": "Voz", + "eae80365006fbe17": "Si se deja vacío, se usa la voz predeterminada del proveedor.", + "5a640ef031aed4a2": "Voz de lectura en voz alta", + "f7323911c24ed501": "Predeterminada", + "b9c9fc9b61d7243e": "Voz predeterminada", + "c10f66d628754b10": "Velocidad", + "bff81cb00fc73544": "Velocidad de reproducción.", + "936895b764543aea": "Velocidad de lectura en voz alta", + "2fc5076786a6b6ed": "Omitir bloques de código", + "0fed42221c860bd6": "Lee la prosa y los identificadores en línea sin narrar los bloques de código.", + "951a30714876977f": "Omitir bloques de código al leer", + "bec2c35646e0496a": "Vista previa", + "8ed4191b261076ff": "Reproduce una muestra breve con el proveedor de voz seleccionado.", + "4b009ef01c76df8e": "Esto es T3 Code. La respuesta de tu agente está lista para leerse en voz alta.", + "0dde517387ea2d57": "Detener la vista previa", + "88f2bec553b72827": "Reproducir vista previa", + "f7158c1af1da3afb": [ + "Usando tu archivo en ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "bff944189ba9c100": "Descargar", + "b3976c9787134fd1": "Seleccionado", + "f4c5cba0cd5dbb68": "Usar modelo", + "0b5ab0399461fdbd": "Usar existente", + "26aafec418058787": "En este dispositivo", + "23196cabaa71f1da": "En un entorno", + "3ba49a214600d0ac": [ + "En la nube con ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Gestionar clave", "02bca2d9c90e5f1e": "{value} s", "af22f973466903c3": "{value} min", "401ba3f2391d8742": "{value} h", @@ -11103,7 +11194,6 @@ "97c969a0f9c64233": "Tras 10 minutos", "bf7f24afa7084dd7": "Tras 15 minutos", "590df316b67cc7d5": "Tras 1 hora", - "c59720248f69d5aa": "Recomendado", "e4369ea318964a77": "Más rápido", "cd9732fb0b7326e3": "Más preciso", "62900eb52209c2e3": "Equilibrio entre precisión y velocidad para los idiomas seleccionados en los benchmarks de referencia de Handy.", @@ -11114,12 +11204,6 @@ "665cbb7042a42206": "Traducir", "82aa50f539d02537": "Puede escribir texto en inglés a partir de voz en otro idioma. Activa Traducir al inglés para usarlo.", "dc23ce436a29363d": "{count, plural, one {{count} idioma} other {{count} idiomas}}", - "c522c5460548c481": "Progreso de la descarga de {name}", - "58a4b7a47e362024": "Verificando la descarga…", - "8ee326cccca4ffe0": "{percent}% descargado", - "f36b40c99b8c221f": "Cancelar la descarga de {name}", - "53b05fd56e4de55b": "Dejar de usar tu archivo de {name}; el archivo se queda en el disco", - "34901bb929deb832": "Eliminar {name}", "58d9cedba566716c": "Añade palabras separadas por comas", "8ce2d4078f890b77": "Añadir una palabra o frase a {label}", "6f40d219fdbe4ae9": "Alias de {term}", @@ -11166,8 +11250,6 @@ "1ce93a052681b78a": "No se pudo cancelar la descarga", "51fd61b9c85dec5d": "No se pudo eliminar el modelo", "3d4be5cb172d6f91": "No se pudo usar un modelo de esa ruta", - "b98b8459bc0fc482": "Ruta a un archivo o carpeta de modelo que ya está en este entorno", - "9e6dabb14a4947e5": "¿Ya lo descargaste en otro sitio? Pega la ruta del archivo o la carpeta del modelo", "2060246c448d1de0": "Esperando a que se conecte el entorno", "c32c85efb80dc740": "Transcripción de prueba", "4b2f68f90eb004f6": "No se reconoció voz. Inténtalo de nuevo.", @@ -11181,8 +11263,6 @@ "5c3711f9ed600d2a": "Transcribir con", "dccbcc6f313dea7e": "{label} no puede transcribir audio localmente. Elige otro destino.", "817dbf1c068b62e7": "Dónde se convierte tu voz en texto.", - "710d3e4f0243014c": "Entorno elegido (no disponible)", - "61088464d1b7174d": "entorno no disponible", "71184e5a54a69f1d": "El proveedor detecta tu idioma automáticamente.", "ffb2653eb2d9fc1a": "{model} detecta el idioma automáticamente.", "773cbfca7c466cc4": "{model} usa un solo idioma fijo.", @@ -11207,17 +11287,6 @@ "c652ed4a9a70f77f": "Instrucciones de limpieza personalizadas", "1c2d9ac371d77eea": "Frase de corrección", "4f6141a8af8dc570": "La frase que dices para corregir un error, como «borra eso».", - "f7158c1af1da3afb": [ - "Usando tu archivo en ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], - "bff944189ba9c100": "Descargar", - "b3976c9787134fd1": "Seleccionado", - "f4c5cba0cd5dbb68": "Usar modelo", "2c5c798252f91fdc": "Añadir", "38b344bfa7d50343": "Alias", "c893707203cb6aee": "Primero conecta un entorno.", @@ -11226,19 +11295,9 @@ "111dbc8f88feacff": "Ningún idioma coincide.", "003aa9115365f752": "Ordenar por", "736406a96ddadcd8": "Solo descargados", - "0b5ab0399461fdbd": "Usar existente", "790951b4fc82052f": "Probar modelo", "a3eda37e8d337ebb": "Di una frase. Se omite la limpieza, así que ves exactamente lo que oyó el modelo.", "c613b9c5d54f3c91": "Actualizar micrófonos", - "23196cabaa71f1da": "En un entorno", - "3ba49a214600d0ac": [ - "En la nube con ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Entorno elegido (no disponible)", "e69e34d4f44d4136": "Integrado", "ae0b91ed52736998": "Usa el último commit de la rama remota a la que sigue la rama base, aunque su nombre sea distinto. Si no, usa la rama con el mismo nombre en origin. Usa tu rama local si falta esa rama remota.", @@ -11419,6 +11478,7 @@ "9d834d178130180e": "beta alfa simlock callstack simulador emulador ios android grupo préstamo gateway", "bcb520297a9ae143": "beta worktree rápido checkout clonar apfs copy-on-write caché macos velocidad", "4c83ac419da342bd": "enviar audio del micrófono dictado destino voz habla stt transcripción entorno máquina consentimiento privacidad nube OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts texto a voz hablar leer en voz alta voz reproducción OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "micrófono entrada audio dispositivo orden prioridad preferido", "22811f405e0b4b28": "voz habla teclado atajo mantener alternar automático", "e27bccf50397d9fe": "voz habla traducir inglés detectar automáticamente", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 658857f98fc48..70ccd231361bb 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} a réagi avec l’emoji yeux", "0c982111ac348e9f": "Vous", "766ea446df1695f7": "Répondez à la question pour modifier les messages en file d’attente", + "6e4d05cd77caff7c": "Impossible de reprendre la lecture.", + "b02cc7b7adaa2361": "Impossible de lire cette réponse.", "257dc29de5b1f1f7": "Contexte, sans code", "edb97296086ba31e": "{count, plural, one {{count} fichier} other {{count} fichiers}}", "556df31b330166ff": "Saisissez un nom pour cette vue.", @@ -3838,6 +3840,11 @@ "de5c52c3f47ff209": "Envoyé par T3 Code", "ded43a280aed9f20": "Ouvrir le fil", "7635dd64bbbe10ec": "Ouvrir l’automatisation", + "154bec57dbece73c": "Arrêter la lecture", + "e3c3d4bcfa9727b9": "Reprendre la lecture", + "0eceb5780908eb6c": "Lecture à voix haute", + "09a3f02127015c7d": "Impossible de lire à voix haute", + "81923647f1ef9740": "Annuler la génération vocale", "6327e4ffa0f2366d": "Pull requests indisponibles", "90062342f04966ff": "Mettez à jour le serveur T3 Code de cet environnement pour parcourir les pull requests.", "5e7157db126f1641": "Tickets indisponibles", @@ -9144,6 +9151,90 @@ "5c0c973276a61fdb": "Impossible d’enregistrer l’autorisation de routage des pull requests", "1bfcffe8411e2439": "Routage des pull requests de {environment}", "ae4761ddc038b102": "Les machines auxquelles vous faites confiance ici peuvent lire les données des PR via l’accès à la gestion de versions des unes et des autres. Activez les deux machines. Lire et agir peut utiliser des autorisations plus larges que celles de la machine qui les possède. Ne s’applique qu’à cet appareil.", + "65a238ad6bebf802": "Lire les réponses à voix haute avec {name} ?", + "bfbaa4965c146e7c": "Toutes les personnes qui utilisent {company} pour la dictée ou la lecture à voix haute sur {environment} perdront l’accès.", + "b9e06e668bd9bff0": "Les réponses que vous lisez sont envoyées à {company} via {environment}, qui facture sa clé d’API. La clé est partagée avec la dictée.", + "09f85302ef58020c": "La mise à jour de la clé garde la lecture à voix haute activée.", + "6e58953ca9c7fad5": "Toute personne ayant accès à {environment} peut facturer cette clé.", + "cf0740520675dcb9": [ + "Connectez-vous à ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " pour continuer." + ], + "b0900f4938210634": "Clé d’API", + "60609aae479dd41c": "Impossible de télécharger le modèle. Vérifiez la connexion et l’espace disque de l’environnement.", + "1405f6ff92c1041a": "Impossible de modifier le modèle. Réessayez.", + "c59720248f69d5aa": "Recommandé", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "Téléchargement de {size}.", + "c522c5460548c481": "Progression du téléchargement de {name}", + "58a4b7a47e362024": "Vérification du téléchargement…", + "8ee326cccca4ffe0": "{percent} % téléchargé", + "f36b40c99b8c221f": "Annuler le téléchargement de {name}", + "53b05fd56e4de55b": "Cesser d’utiliser votre fichier {name} ; le fichier reste sur le disque", + "34901bb929deb832": "Supprimer {name}", + "69a7c539add37d29": "Aucun fichier de modèle vocal n’a été trouvé à cet emplacement.", + "b98b8459bc0fc482": "Chemin d’un fichier ou dossier de modèle déjà présent dans cet environnement", + "9e6dabb14a4947e5": "Déjà téléchargé ailleurs ? Collez le chemin du fichier ou du dossier du modèle", + "b4b7580d21c53b5f": "Impossible de charger les modèles vocaux. Vérifiez l’environnement sélectionné et la configuration du fournisseur.", + "293d67c7b56e7b69": "Fournisseur vocal", + "7bc4af4101c8997b": "{environment} n’a pas de clé d’API {company}. Ajoutez-en une avec le bouton de clé.", + "944dfe57d9653d32": "Cet environnement n’a pas de clé d’API {company}. Ajoutez-en une avec le bouton de clé.", + "1c3796a6ec44558f": "Lisez les réponses terminées avec le bouton de lecture à côté de Copier. Les fournisseurs hébergés reçoivent le texte via l’environnement sélectionné ; un modèle local s’y exécute.", + "ee6859d2ad7f5842": "Fournisseur de lecture à voix haute", + "710d3e4f0243014c": "Environnement choisi (indisponible)", + "61088464d1b7174d": "environnement indisponible", + "52e8f8accdca2d32": "Voix du système", + "17076b27f1f3ada5": "Désactivé", + "0097b134ae6e9d9c": "Gérer la clé de lecture à voix haute", + "09bc28a37e6caf92": "Téléchargé une fois dans l’environnement sélectionné, qui lit les réponses sans que le texte le quitte.", + "d33ab3b324ba0b36": "Modèles de lecture à voix haute", + "3fb69cb2e760f23d": "Modèle vocal", + "2d2ee6c94580e79f": "Choisissez un modèle vocal dans le catalogue du fournisseur.", + "44e370c9cc900c63": "Modèle de lecture à voix haute", + "9fa6e93a8218ad60": "Voix", + "eae80365006fbe17": "Une valeur vide utilise la voix par défaut du fournisseur.", + "5a640ef031aed4a2": "Voix de lecture à voix haute", + "f7323911c24ed501": "Par défaut", + "b9c9fc9b61d7243e": "Voix par défaut", + "c10f66d628754b10": "Vitesse", + "bff81cb00fc73544": "Vitesse de lecture.", + "936895b764543aea": "Vitesse de lecture à voix haute", + "2fc5076786a6b6ed": "Ignorer les blocs de code", + "0fed42221c860bd6": "Lit le texte et les identifiants en ligne sans lire les blocs de code.", + "951a30714876977f": "Ignorer les blocs de code pendant la lecture", + "bec2c35646e0496a": "Aperçu", + "8ed4191b261076ff": "Lit un court extrait avec le fournisseur vocal sélectionné.", + "4b009ef01c76df8e": "Voici T3 Code. La réponse de votre agent est prête à être lue à voix haute.", + "0dde517387ea2d57": "Arrêter l’aperçu", + "88f2bec553b72827": "Lire l’aperçu", + "f7158c1af1da3afb": [ + "Utilise votre fichier dans ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "bff944189ba9c100": "Télécharger", + "b3976c9787134fd1": "Sélectionné", + "f4c5cba0cd5dbb68": "Utiliser le modèle", + "0b5ab0399461fdbd": "Utiliser l’existant", + "26aafec418058787": "Sur cet appareil", + "23196cabaa71f1da": "Dans un environnement", + "3ba49a214600d0ac": [ + "Cloud via ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Gérer la clé", "02bca2d9c90e5f1e": "{value} s", "af22f973466903c3": "{value} min", "401ba3f2391d8742": "{value} h", @@ -11108,7 +11199,6 @@ "97c969a0f9c64233": "Après 10 minutes", "bf7f24afa7084dd7": "Après 15 minutes", "590df316b67cc7d5": "Après 1 heure", - "c59720248f69d5aa": "Recommandé", "e4369ea318964a77": "Plus rapide", "cd9732fb0b7326e3": "Plus précis", "62900eb52209c2e3": "Bon équilibre entre précision et vitesse pour les langues sélectionnées, d’après les benchmarks de référence de Handy.", @@ -11119,12 +11209,6 @@ "665cbb7042a42206": "Traduire", "82aa50f539d02537": "Peut écrire du texte anglais à partir d’une parole dans une autre langue. Activez Traduire en anglais pour l’utiliser.", "dc23ce436a29363d": "{count, plural, one {{count} langue} other {{count} langues}}", - "c522c5460548c481": "Progression du téléchargement de {name}", - "58a4b7a47e362024": "Vérification du téléchargement…", - "8ee326cccca4ffe0": "{percent} % téléchargé", - "f36b40c99b8c221f": "Annuler le téléchargement de {name}", - "53b05fd56e4de55b": "Cesser d’utiliser votre fichier {name} ; le fichier reste sur le disque", - "34901bb929deb832": "Supprimer {name}", "58d9cedba566716c": "Ajoutez des mots, séparés par des virgules", "8ce2d4078f890b77": "Ajouter un mot ou une expression au {label}", "6f40d219fdbe4ae9": "Alias de {term}", @@ -11171,8 +11255,6 @@ "1ce93a052681b78a": "Impossible d’annuler le téléchargement", "51fd61b9c85dec5d": "Impossible de supprimer le modèle", "3d4be5cb172d6f91": "Impossible d’utiliser un modèle depuis ce chemin", - "b98b8459bc0fc482": "Chemin d’un fichier ou dossier de modèle déjà présent dans cet environnement", - "9e6dabb14a4947e5": "Déjà téléchargé ailleurs ? Collez le chemin du fichier ou du dossier du modèle", "2060246c448d1de0": "En attente de la connexion de l’environnement", "c32c85efb80dc740": "Transcription de test", "4b2f68f90eb004f6": "Aucune parole reconnue. Réessayez.", @@ -11186,8 +11268,6 @@ "5c3711f9ed600d2a": "Transcrire avec", "dccbcc6f313dea7e": "{label} ne peut pas transcrire l’audio localement. Choisissez une autre destination.", "817dbf1c068b62e7": "Où votre parole est convertie en texte.", - "710d3e4f0243014c": "Environnement choisi (indisponible)", - "61088464d1b7174d": "environnement indisponible", "71184e5a54a69f1d": "Le fournisseur détecte automatiquement votre langue.", "ffb2653eb2d9fc1a": "{model} détecte automatiquement la langue.", "773cbfca7c466cc4": "{model} utilise une seule langue fixe.", @@ -11212,17 +11292,6 @@ "c652ed4a9a70f77f": "Instructions de nettoyage personnalisées", "1c2d9ac371d77eea": "Formule de correction", "4f6141a8af8dc570": "La phrase que vous dites pour corriger une erreur, comme « annule ça ».", - "f7158c1af1da3afb": [ - "Utilise votre fichier dans ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], - "bff944189ba9c100": "Télécharger", - "b3976c9787134fd1": "Sélectionné", - "f4c5cba0cd5dbb68": "Utiliser le modèle", "2c5c798252f91fdc": "Ajouter", "38b344bfa7d50343": "Alias", "c893707203cb6aee": "Connectez d’abord un environnement.", @@ -11231,19 +11300,9 @@ "111dbc8f88feacff": "Aucune langue ne correspond.", "003aa9115365f752": "Trier par", "736406a96ddadcd8": "Téléchargés uniquement", - "0b5ab0399461fdbd": "Utiliser l’existant", "790951b4fc82052f": "Tester le modèle", "a3eda37e8d337ebb": "Dites une phrase. Le nettoyage est ignoré, vous voyez donc exactement ce que le modèle a entendu.", "c613b9c5d54f3c91": "Actualiser les microphones", - "23196cabaa71f1da": "Dans un environnement", - "3ba49a214600d0ac": [ - "Cloud via ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Environnement choisi (indisponible)", "e69e34d4f44d4136": "Intégrées", "ae0b91ed52736998": "Utilise le dernier commit de la branche distante suivie par la branche de base, même si son nom diffère. Sinon, utilise la branche du même nom sur origin. Utilise votre branche locale si cette branche distante n’existe pas.", @@ -11424,6 +11483,7 @@ "9d834d178130180e": "bêta alpha simlock callstack simulateur émulateur ios android pool bail passerelle", "bcb520297a9ae143": "bêta rapide worktree extraction clone apfs copie sur écriture cache macos vitesse", "4c83ac419da342bd": "envoyer microphone audio dictée destination parole voix stt transcription environnement machine consentement confidentialité cloud OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts synthèse vocale parler lecture à voix haute voix lecture OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "micro entrée audio appareil ordre priorité préféré", "22811f405e0b4b28": "parole voix clavier raccourci maintenir basculer auto", "e27bccf50397d9fe": "parole voix traduire anglais détection auto", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index a405829ae1a06..c7b7cf4a3685c 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} が目の絵文字でリアクションしました", "0c982111ac348e9f": "あなた", "766ea446df1695f7": "キューに入れたメッセージを編集するには質問に回答してください", + "6e4d05cd77caff7c": "読み上げを再開できませんでした。", + "b02cc7b7adaa2361": "この応答を読み上げられませんでした。", "257dc29de5b1f1f7": "コンテキストのみ、コードなし", "edb97296086ba31e": "{count, plural, other {{count} 個のファイル}}", "556df31b330166ff": "このビューの名前を入力してください。", @@ -3828,6 +3830,11 @@ "de5c52c3f47ff209": "T3 Code から送信", "ded43a280aed9f20": "スレッドを開く", "7635dd64bbbe10ec": "自動化を開く", + "154bec57dbece73c": "読み上げを停止", + "e3c3d4bcfa9727b9": "読み上げを再開", + "0eceb5780908eb6c": "読み上げ", + "09a3f02127015c7d": "読み上げできませんでした", + "81923647f1ef9740": "音声の生成をキャンセル", "6327e4ffa0f2366d": "プルリクエストを利用できません", "90062342f04966ff": "プルリクエストを参照するには、この環境の T3 Code サーバーを更新してください。", "5e7157db126f1641": "Issue を利用できません", @@ -9100,6 +9107,90 @@ "5c0c973276a61fdb": "プルリクエストのルーティング権限を保存できませんでした", "1bfcffe8411e2439": "{environment} のプルリクエストのルーティング", "ae4761ddc038b102": "ここで信頼したマシン同士は、互いのソース管理のアクセス権を通じて PR のデータを読み取れます。両方のマシンで有効にしてください。「読み取りと操作」では、所有するマシンより広い権限が使われる場合があります。この設定はこのデバイスにのみ適用されます。", + "65a238ad6bebf802": "{name} で返信を読み上げますか?", + "bfbaa4965c146e7c": "{environment} で音声入力または読み上げに {company} を使っているすべてのユーザーがアクセスできなくなります。", + "b9e06e668bd9bff0": "再生する返信は {environment} を通じて {company} に送信され、その API キーに課金されます。このキーは音声入力と共有されます。", + "09f85302ef58020c": "キーを更新しても読み上げはオンのままです。", + "6e58953ca9c7fad5": "{environment} にアクセスできるユーザーは誰でも、このキーに課金できます。", + "cf0740520675dcb9": [ + "続行するには ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " に接続してください。" + ], + "b0900f4938210634": "API キー", + "60609aae479dd41c": "モデルをダウンロードできませんでした。環境の接続とディスク容量を確認してください。", + "1405f6ff92c1041a": "モデルを変更できませんでした。もう一度お試しください。", + "c59720248f69d5aa": "推奨", + "d5b9ecbc5062b6a7": "{size}。", + "c2be8693c77597a3": "ダウンロードサイズ {size}。", + "c522c5460548c481": "{name} のダウンロードの進行状況", + "58a4b7a47e362024": "ダウンロードを検証しています…", + "8ee326cccca4ffe0": "{percent}% ダウンロード済み", + "f36b40c99b8c221f": "{name} のダウンロードをキャンセル", + "53b05fd56e4de55b": "{name} ファイルの使用を停止します。ファイルはディスクに残ります", + "34901bb929deb832": "{name} を削除", + "69a7c539add37d29": "そのパスに音声モデルのファイルが見つかりませんでした。", + "b98b8459bc0fc482": "この環境にすでにあるモデルファイルまたはフォルダーのパス", + "9e6dabb14a4947e5": "別の場所でダウンロード済みですか?モデルファイルまたはフォルダーのパスを貼り付けてください", + "b4b7580d21c53b5f": "音声モデルを読み込めませんでした。選択した環境とプロバイダーの設定を確認してください。", + "293d67c7b56e7b69": "音声プロバイダー", + "7bc4af4101c8997b": "{environment} には {company} の API キーがありません。キーボタンから追加してください。", + "944dfe57d9653d32": "この環境には {company} の API キーがありません。キーボタンから追加してください。", + "1c3796a6ec44558f": "完了した返信は、コピーの横にある再生ボタンで読み上げます。ホスト型プロバイダーは選択した環境を通じて応答テキストを受け取り、ローカルモデルはその環境で実行されます。", + "ee6859d2ad7f5842": "読み上げプロバイダー", + "710d3e4f0243014c": "選択した環境 (利用不可)", + "61088464d1b7174d": "利用できない環境", + "52e8f8accdca2d32": "システムの音声", + "17076b27f1f3ada5": "オフ", + "0097b134ae6e9d9c": "読み上げ用キーを管理", + "09bc28a37e6caf92": "選択した環境に一度だけダウンロードされ、テキストを外部に出さずに返信を読み上げます。", + "d33ab3b324ba0b36": "読み上げモデル", + "3fb69cb2e760f23d": "音声モデル", + "2d2ee6c94580e79f": "プロバイダーのカタログから音声モデルを選択します。", + "44e370c9cc900c63": "読み上げモデル", + "9fa6e93a8218ad60": "音声", + "eae80365006fbe17": "空欄の場合はプロバイダーの既定の音声を使います。", + "5a640ef031aed4a2": "読み上げの音声", + "f7323911c24ed501": "既定", + "b9c9fc9b61d7243e": "既定の音声", + "c10f66d628754b10": "速度", + "bff81cb00fc73544": "再生速度。", + "936895b764543aea": "読み上げ速度", + "2fc5076786a6b6ed": "コードブロックをスキップ", + "0fed42221c860bd6": "本文とインラインの識別子を読み上げ、コードブロックは読み上げません。", + "951a30714876977f": "読み上げ時にコードブロックをスキップ", + "bec2c35646e0496a": "プレビュー", + "8ed4191b261076ff": "選択した音声プロバイダーで短いサンプルを再生します。", + "4b009ef01c76df8e": "T3 Code です。エージェントの応答を読み上げる準備ができました。", + "0dde517387ea2d57": "プレビューを停止", + "88f2bec553b72827": "プレビューを再生", + "f7158c1af1da3afb": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " のファイルを使用中" + ], + "bff944189ba9c100": "ダウンロード", + "b3976c9787134fd1": "選択済み", + "f4c5cba0cd5dbb68": "モデルを使用", + "0b5ab0399461fdbd": "既存のものを使用", + "26aafec418058787": "このデバイス上", + "23196cabaa71f1da": "環境上", + "3ba49a214600d0ac": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 経由のクラウド" + ], + "6793112a0a873441": "キーを管理", "02bca2d9c90e5f1e": "{value}秒", "af22f973466903c3": "{value}分", "401ba3f2391d8742": "{value}時間", @@ -11058,7 +11149,6 @@ "97c969a0f9c64233": "10 分後", "bf7f24afa7084dd7": "15 分後", "590df316b67cc7d5": "1 時間後", - "c59720248f69d5aa": "推奨", "e4369ea318964a77": "より高速", "cd9732fb0b7326e3": "より正確", "62900eb52209c2e3": "Handy の参照ベンチマークで、選択した言語の精度と速度のバランスが取れています。", @@ -11069,12 +11159,6 @@ "665cbb7042a42206": "翻訳", "82aa50f539d02537": "他の言語の音声から英語のテキストを作成できます。使うには「英語に翻訳」をオンにしてください。", "dc23ce436a29363d": "{count, plural, other {{count} 言語}}", - "c522c5460548c481": "{name} のダウンロードの進行状況", - "58a4b7a47e362024": "ダウンロードを検証しています…", - "8ee326cccca4ffe0": "{percent}% ダウンロード済み", - "f36b40c99b8c221f": "{name} のダウンロードをキャンセル", - "53b05fd56e4de55b": "{name} ファイルの使用を停止します。ファイルはディスクに残ります", - "34901bb929deb832": "{name} を削除", "58d9cedba566716c": "単語をカンマ区切りで追加", "8ce2d4078f890b77": "{label} に単語またはフレーズを追加", "6f40d219fdbe4ae9": "{term} の別名", @@ -11121,8 +11205,6 @@ "1ce93a052681b78a": "ダウンロードをキャンセルできませんでした", "51fd61b9c85dec5d": "モデルを削除できませんでした", "3d4be5cb172d6f91": "そのパスのモデルを使用できませんでした", - "b98b8459bc0fc482": "この環境にすでにあるモデルファイルまたはフォルダーのパス", - "9e6dabb14a4947e5": "別の場所でダウンロード済みですか?モデルファイルまたはフォルダーのパスを貼り付けてください", "2060246c448d1de0": "環境の接続を待っています", "c32c85efb80dc740": "テストの文字起こし", "4b2f68f90eb004f6": "音声を認識できませんでした。もう一度お試しください。", @@ -11136,8 +11218,6 @@ "5c3711f9ed600d2a": "文字起こしの実行場所", "dccbcc6f313dea7e": "{label} ではローカルで音声を文字起こしできません。別の実行場所を選択してください。", "817dbf1c068b62e7": "音声をテキストに変換する場所です。", - "710d3e4f0243014c": "選択した環境 (利用不可)", - "61088464d1b7174d": "利用できない環境", "71184e5a54a69f1d": "プロバイダーが言語を自動的に検出します。", "ffb2653eb2d9fc1a": "{model} が言語を自動的に検出します。", "773cbfca7c466cc4": "{model} は 1 つの固定言語を使用します。", @@ -11162,17 +11242,6 @@ "c652ed4a9a70f77f": "カスタムの整形指示", "1c2d9ac371d77eea": "訂正の合図", "4f6141a8af8dc570": "間違いを訂正するときに言うフレーズ (例: 「今のなし」)。", - "f7158c1af1da3afb": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " のファイルを使用中" - ], - "bff944189ba9c100": "ダウンロード", - "b3976c9787134fd1": "選択済み", - "f4c5cba0cd5dbb68": "モデルを使用", "2c5c798252f91fdc": "追加", "38b344bfa7d50343": "別名", "c893707203cb6aee": "まず環境に接続してください。", @@ -11181,19 +11250,9 @@ "111dbc8f88feacff": "一致する言語はありません。", "003aa9115365f752": "並べ替え", "736406a96ddadcd8": "ダウンロード済みのみ", - "0b5ab0399461fdbd": "既存のものを使用", "790951b4fc82052f": "モデルをテスト", "a3eda37e8d337ebb": "文を 1 つ話してください。整形はスキップされるため、モデルが聞き取った内容がそのまま表示されます。", "c613b9c5d54f3c91": "マイクを更新", - "23196cabaa71f1da": "環境上", - "3ba49a214600d0ac": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 経由のクラウド" - ], "625f25278bc683ba": "選択した環境 (利用不可)", "e69e34d4f44d4136": "組み込み", "ae0b91ed52736998": "ベースブランチが追跡しているリモートブランチの最新コミットを使用します (名前が異なる場合も含む)。それ以外の場合は origin 上の同名ブランチを使用します。そのリモートブランチがない場合はローカルブランチを使用します。", @@ -11374,6 +11433,7 @@ "9d834d178130180e": "ベータ アルファ simlock callstack シミュレーター エミュレーター iOS Android プール リース ゲートウェイ simulator", "bcb520297a9ae143": "ベータ 高速 ワークツリー チェックアウト クローン APFS コピーオンライト キャッシュ macOS 速度 fast worktree", "4c83ac419da342bd": "送信 マイク 音声 音声入力 送信先 発話 STT 文字起こし 環境 マシン 同意 プライバシー クラウド OpenAI Grok OpenRouter dictation", + "3985d8550c7bc219": "tts 音声合成 読み上げ 音声 再生 OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "マイク 入力 オーディオ デバイス 順序 優先 優先度 mic", "22811f405e0b4b28": "音声 キーボード ホットキー 長押し 切り替え 自動 hotkey", "e27bccf50397d9fe": "音声 翻訳 英語 自動検出 translate", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c5690cb564f42..57e9491342f3d 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} 님이 눈 이모지로 반응했습니다", "0c982111ac348e9f": "나", "766ea446df1695f7": "대기열 메시지를 편집하려면 질문에 답하세요", + "6e4d05cd77caff7c": "읽기를 다시 시작할 수 없습니다.", + "b02cc7b7adaa2361": "이 응답을 읽을 수 없습니다.", "257dc29de5b1f1f7": "컨텍스트만, 코드 없음", "edb97296086ba31e": "{count, plural, other {파일 {count}개}}", "556df31b330166ff": "이 보기의 이름을 입력하세요.", @@ -3826,6 +3828,11 @@ "de5c52c3f47ff209": "T3 Code에서 보냄", "ded43a280aed9f20": "스레드 열기", "7635dd64bbbe10ec": "자동화 열기", + "154bec57dbece73c": "읽기 중지", + "e3c3d4bcfa9727b9": "읽기 다시 시작", + "0eceb5780908eb6c": "소리 내어 읽기", + "09a3f02127015c7d": "소리 내어 읽을 수 없음", + "81923647f1ef9740": "음성 생성 취소", "6327e4ffa0f2366d": "풀 리퀘스트를 사용할 수 없음", "90062342f04966ff": "풀 리퀘스트를 탐색하려면 이 환경의 T3 Code 서버를 업데이트하세요.", "5e7157db126f1641": "이슈를 사용할 수 없음", @@ -9102,6 +9109,90 @@ "5c0c973276a61fdb": "풀 리퀘스트 라우팅 권한을 저장할 수 없습니다", "1bfcffe8411e2439": "{environment} 풀 리퀘스트 라우팅", "ae4761ddc038b102": "여기서 신뢰하는 머신은 서로의 소스 제어 액세스를 통해 PR 데이터를 읽을 수 있습니다. 두 머신 모두에서 사용하도록 설정하세요. 읽기 및 작업은 해당 권한을 소유한 머신보다 넓은 권한을 사용할 수 있습니다. 이 기기에만 적용됩니다.", + "65a238ad6bebf802": "{name}(으)로 답변을 소리 내어 읽을까요?", + "bfbaa4965c146e7c": "{environment}에서 받아쓰기나 소리 내어 읽기에 {company}을(를) 사용하는 모든 사람이 액세스 권한을 잃습니다.", + "b9e06e668bd9bff0": "재생하는 답변은 {environment}을(를) 통해 {company}(으)로 전송되며 해당 API 키로 요금이 청구됩니다. 이 키는 받아쓰기와 공유됩니다.", + "09f85302ef58020c": "키를 업데이트해도 소리 내어 읽기는 계속 켜져 있습니다.", + "6e58953ca9c7fad5": "{environment}에 액세스할 수 있는 사람은 누구나 이 키로 요금을 발생시킬 수 있습니다.", + "cf0740520675dcb9": [ + "계속하려면 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "에 연결하세요." + ], + "b0900f4938210634": "API 키", + "60609aae479dd41c": "모델을 다운로드할 수 없습니다. 환경의 연결 상태와 디스크 공간을 확인하세요.", + "1405f6ff92c1041a": "모델을 변경할 수 없습니다. 다시 시도하세요.", + "c59720248f69d5aa": "추천", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "{size} 다운로드.", + "c522c5460548c481": "{name} 다운로드 진행률", + "58a4b7a47e362024": "다운로드 확인 중…", + "8ee326cccca4ffe0": "{percent}% 다운로드됨", + "f36b40c99b8c221f": "{name} 다운로드 취소", + "53b05fd56e4de55b": "{name} 파일 사용 중지. 파일은 디스크에 남습니다", + "34901bb929deb832": "{name} 삭제", + "69a7c539add37d29": "해당 경로에서 음성 모델 파일을 찾을 수 없습니다.", + "b98b8459bc0fc482": "이 환경에 이미 있는 모델 파일 또는 폴더 경로", + "9e6dabb14a4947e5": "이미 다른 곳에 다운로드했나요? 모델 파일 또는 폴더 경로를 붙여 넣으세요", + "b4b7580d21c53b5f": "음성 모델을 불러올 수 없습니다. 선택한 환경과 제공자 구성을 확인하세요.", + "293d67c7b56e7b69": "음성 제공자", + "7bc4af4101c8997b": "{environment}에 {company} API 키가 없습니다. 키 버튼으로 추가하세요.", + "944dfe57d9653d32": "이 환경에 {company} API 키가 없습니다. 키 버튼으로 추가하세요.", + "1c3796a6ec44558f": "완료된 답변은 복사 옆의 재생 버튼으로 읽습니다. 호스팅 제공자는 선택한 환경을 통해 응답 텍스트를 받고, 로컬 모델은 해당 환경에서 실행됩니다.", + "ee6859d2ad7f5842": "소리 내어 읽기 제공자", + "710d3e4f0243014c": "선택한 환경(사용할 수 없음)", + "61088464d1b7174d": "사용할 수 없는 환경", + "52e8f8accdca2d32": "시스템 음성", + "17076b27f1f3ada5": "끄기", + "0097b134ae6e9d9c": "소리 내어 읽기 키 관리", + "09bc28a37e6caf92": "선택한 환경에 한 번 다운로드되며, 텍스트가 환경 밖으로 나가지 않고 답변을 읽습니다.", + "d33ab3b324ba0b36": "소리 내어 읽기 모델", + "3fb69cb2e760f23d": "음성 모델", + "2d2ee6c94580e79f": "제공자 카탈로그에서 음성 모델을 선택하세요.", + "44e370c9cc900c63": "소리 내어 읽기 모델", + "9fa6e93a8218ad60": "음성", + "eae80365006fbe17": "비워 두면 제공자의 기본 음성을 사용합니다.", + "5a640ef031aed4a2": "소리 내어 읽기 음성", + "f7323911c24ed501": "기본값", + "b9c9fc9b61d7243e": "기본 음성", + "c10f66d628754b10": "속도", + "bff81cb00fc73544": "재생 속도입니다.", + "936895b764543aea": "소리 내어 읽기 속도", + "2fc5076786a6b6ed": "코드 블록 건너뛰기", + "0fed42221c860bd6": "본문과 인라인 식별자는 읽고 코드 블록은 읽지 않습니다.", + "951a30714876977f": "읽을 때 코드 블록 건너뛰기", + "bec2c35646e0496a": "미리 듣기", + "8ed4191b261076ff": "선택한 음성 제공자로 짧은 샘플을 재생합니다.", + "4b009ef01c76df8e": "T3 Code입니다. 에이전트의 응답을 소리 내어 읽을 준비가 되었습니다.", + "0dde517387ea2d57": "미리 듣기 중지", + "88f2bec553b72827": "미리 듣기 재생", + "f7158c1af1da3afb": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 파일 사용 중" + ], + "bff944189ba9c100": "다운로드", + "b3976c9787134fd1": "선택됨", + "f4c5cba0cd5dbb68": "모델 사용", + "0b5ab0399461fdbd": "기존 항목 사용", + "26aafec418058787": "이 기기에서", + "23196cabaa71f1da": "환경에서", + "3ba49a214600d0ac": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "을(를) 통한 클라우드" + ], + "6793112a0a873441": "키 관리", "02bca2d9c90e5f1e": "{value}초", "af22f973466903c3": "{value}분", "401ba3f2391d8742": "{value}시간", @@ -11055,7 +11146,6 @@ "97c969a0f9c64233": "10분 후", "bf7f24afa7084dd7": "15분 후", "590df316b67cc7d5": "1시간 후", - "c59720248f69d5aa": "추천", "e4369ea318964a77": "더 빠름", "cd9732fb0b7326e3": "더 정확함", "62900eb52209c2e3": "Handy 참조 벤치마크에서 선택한 언어의 정확도와 속도가 균형을 이룹니다.", @@ -11066,12 +11156,6 @@ "665cbb7042a42206": "번역", "82aa50f539d02537": "다른 언어로 말한 내용을 영어 텍스트로 작성할 수 있습니다. 사용하려면 영어로 번역을 켜세요.", "dc23ce436a29363d": "{count, plural, other {언어 {count}개}}", - "c522c5460548c481": "{name} 다운로드 진행률", - "58a4b7a47e362024": "다운로드 확인 중…", - "8ee326cccca4ffe0": "{percent}% 다운로드됨", - "f36b40c99b8c221f": "{name} 다운로드 취소", - "53b05fd56e4de55b": "{name} 파일 사용 중지. 파일은 디스크에 남습니다", - "34901bb929deb832": "{name} 삭제", "58d9cedba566716c": "쉼표로 구분해 단어 추가", "8ce2d4078f890b77": "{label}에 단어나 구문 추가", "6f40d219fdbe4ae9": "{term}의 별칭", @@ -11118,8 +11202,6 @@ "1ce93a052681b78a": "다운로드를 취소할 수 없습니다", "51fd61b9c85dec5d": "모델을 삭제할 수 없습니다", "3d4be5cb172d6f91": "해당 경로의 모델을 사용할 수 없습니다", - "b98b8459bc0fc482": "이 환경에 이미 있는 모델 파일 또는 폴더 경로", - "9e6dabb14a4947e5": "이미 다른 곳에 다운로드했나요? 모델 파일 또는 폴더 경로를 붙여 넣으세요", "2060246c448d1de0": "환경 연결을 기다리는 중", "c32c85efb80dc740": "받아쓰기 테스트", "4b2f68f90eb004f6": "인식된 음성이 없습니다. 다시 시도하세요.", @@ -11133,8 +11215,6 @@ "5c3711f9ed600d2a": "받아쓰기 위치", "dccbcc6f313dea7e": "{label}에서는 오디오를 로컬로 받아쓸 수 없습니다. 다른 대상을 선택하세요.", "817dbf1c068b62e7": "음성이 텍스트로 변환되는 곳입니다.", - "710d3e4f0243014c": "선택한 환경(사용할 수 없음)", - "61088464d1b7174d": "사용할 수 없는 환경", "71184e5a54a69f1d": "제공자가 언어를 자동으로 감지합니다.", "ffb2653eb2d9fc1a": "{model}이(가) 언어를 자동으로 감지합니다.", "773cbfca7c466cc4": "{model}은(는) 고정된 언어 하나를 사용합니다.", @@ -11159,17 +11239,6 @@ "c652ed4a9a70f77f": "사용자 지정 정리 지침", "1c2d9ac371d77eea": "수정 신호", "4f6141a8af8dc570": "실수를 바로잡을 때 말하는 문구입니다(예: “방금 거 취소”).", - "f7158c1af1da3afb": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - "의 파일 사용 중" - ], - "bff944189ba9c100": "다운로드", - "b3976c9787134fd1": "선택됨", - "f4c5cba0cd5dbb68": "모델 사용", "2c5c798252f91fdc": "추가", "38b344bfa7d50343": "별칭", "c893707203cb6aee": "먼저 환경을 연결하세요.", @@ -11178,19 +11247,9 @@ "111dbc8f88feacff": "일치하는 언어가 없습니다.", "003aa9115365f752": "정렬 기준", "736406a96ddadcd8": "다운로드한 항목만", - "0b5ab0399461fdbd": "기존 항목 사용", "790951b4fc82052f": "모델 테스트", "a3eda37e8d337ebb": "한 문장을 말해 보세요. 정리를 건너뛰므로 모델이 들은 그대로 확인할 수 있습니다.", "c613b9c5d54f3c91": "마이크 새로 고침", - "23196cabaa71f1da": "환경에서", - "3ba49a214600d0ac": [ - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - "을(를) 통한 클라우드" - ], "625f25278bc683ba": "선택한 환경(사용할 수 없음)", "e69e34d4f44d4136": "기본 제공", "ae0b91ed52736998": "기준 브랜치가 추적하는 원격 브랜치의 최신 커밋을 사용하며, 이름이 달라도 마찬가지입니다. 그렇지 않으면 origin의 같은 이름 브랜치를 사용합니다. 해당 원격 브랜치가 없으면 로컬 브랜치를 사용합니다.", @@ -11371,6 +11430,7 @@ "9d834d178130180e": "베타 알파 simlock callstack 시뮬레이터 에뮬레이터 iOS Android 풀 임대 게이트웨이", "bcb520297a9ae143": "베타 빠른 워크트리 체크아웃 복제 apfs copy-on-write 캐시 macOS 속도", "4c83ac419da342bd": "마이크 오디오 보내기 받아쓰기 대상 음성 stt 받아쓰기 환경 머신 동의 개인정보 클라우드 OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts 텍스트 음성 변환 소리 내어 읽기 음성 재생 OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "마이크 입력 오디오 장치 순서 우선순위 선호", "22811f405e0b4b28": "음성 키보드 단축키 길게 누르기 전환 자동", "e27bccf50397d9fe": "음성 번역 영어 자동 감지", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 9c4552aed155b..ccebc7274910a 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} reagiu com o emoji de olhos", "0c982111ac348e9f": "Você", "766ea446df1695f7": "Responda à pergunta para editar as mensagens na fila", + "6e4d05cd77caff7c": "Não foi possível retomar a leitura.", + "b02cc7b7adaa2361": "Não foi possível ler esta resposta.", "257dc29de5b1f1f7": "Contexto, sem código", "edb97296086ba31e": "{count, plural, one {{count} arquivo} other {{count} arquivos}}", "556df31b330166ff": "Digite um nome para esta visualização.", @@ -3838,6 +3840,11 @@ "de5c52c3f47ff209": "Enviado pelo T3 Code", "ded43a280aed9f20": "Abrir thread", "7635dd64bbbe10ec": "Abrir automação", + "154bec57dbece73c": "Parar leitura", + "e3c3d4bcfa9727b9": "Retomar leitura", + "0eceb5780908eb6c": "Ler em voz alta", + "09a3f02127015c7d": "Não foi possível ler em voz alta", + "81923647f1ef9740": "Cancelar geração de voz", "6327e4ffa0f2366d": "Pull requests indisponíveis", "90062342f04966ff": "Atualize o servidor do T3 Code deste ambiente para navegar pelos pull requests.", "5e7157db126f1641": "Issues indisponíveis", @@ -9143,6 +9150,90 @@ "5c0c973276a61fdb": "Não foi possível salvar a permissão de roteamento de pull requests", "1bfcffe8411e2439": "Roteamento de pull requests de {environment}", "ae4761ddc038b102": "As máquinas em que você confia aqui podem ler dados de PRs pelo acesso ao controle de versão umas das outras. Ative nas duas máquinas. \"Ler e agir\" pode usar permissões mais amplas que as da máquina dona delas. Isso vale só para este dispositivo.", + "65a238ad6bebf802": "Ler respostas em voz alta com {name}?", + "bfbaa4965c146e7c": "Todos que usam {company} para ditado ou leitura em voz alta em {environment} perderão o acesso.", + "b9e06e668bd9bff0": "As respostas que você reproduz são enviadas à {company} por meio de {environment}, que cobra na chave de API dele. A chave é compartilhada com o ditado.", + "09f85302ef58020c": "Atualizar a chave mantém a leitura em voz alta ativada.", + "6e58953ca9c7fad5": "Qualquer pessoa com acesso a {environment} pode gerar cobranças nesta chave.", + "cf0740520675dcb9": [ + "Conecte-se a ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " para continuar." + ], + "b0900f4938210634": "Chave de API", + "60609aae479dd41c": "Não foi possível baixar o modelo. Verifique a conexão e o espaço em disco do ambiente.", + "1405f6ff92c1041a": "Não foi possível alterar o modelo. Tente novamente.", + "c59720248f69d5aa": "Recomendado", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "Download de {size}.", + "c522c5460548c481": "Progresso do download de {name}", + "58a4b7a47e362024": "Verificando download…", + "8ee326cccca4ffe0": "{percent}% baixado", + "f36b40c99b8c221f": "Cancelar o download de {name}", + "53b05fd56e4de55b": "Parar de usar seu arquivo {name}; o arquivo continua no disco", + "34901bb929deb832": "Excluir {name}", + "69a7c539add37d29": "Nenhum arquivo de modelo de voz foi encontrado nesse caminho.", + "b98b8459bc0fc482": "Caminho de um arquivo ou pasta de modelo que já está neste ambiente", + "9e6dabb14a4947e5": "Já baixou em outro lugar? Cole o caminho do arquivo ou da pasta do modelo", + "b4b7580d21c53b5f": "Não foi possível carregar os modelos de voz. Verifique o ambiente selecionado e a configuração do provedor.", + "293d67c7b56e7b69": "Provedor de voz", + "7bc4af4101c8997b": "{environment} não tem uma chave de API da {company}. Adicione uma com o botão de chave.", + "944dfe57d9653d32": "Este ambiente não tem uma chave de API da {company}. Adicione uma com o botão de chave.", + "1c3796a6ec44558f": "Leia respostas concluídas com o botão de reproduzir ao lado de Copiar. Provedores hospedados recebem o texto pelo ambiente selecionado; um modelo local é executado nele.", + "ee6859d2ad7f5842": "Provedor de leitura em voz alta", + "710d3e4f0243014c": "Ambiente escolhido (indisponível)", + "61088464d1b7174d": "ambiente indisponível", + "52e8f8accdca2d32": "Vozes do sistema", + "17076b27f1f3ada5": "Desativado", + "0097b134ae6e9d9c": "Gerenciar chave de leitura em voz alta", + "09bc28a37e6caf92": "Baixado uma vez no ambiente selecionado, que lê as respostas sem que o texto saia dele.", + "d33ab3b324ba0b36": "Modelos de leitura em voz alta", + "3fb69cb2e760f23d": "Modelo de voz", + "2d2ee6c94580e79f": "Escolha um modelo de voz do catálogo do provedor.", + "44e370c9cc900c63": "Modelo de leitura em voz alta", + "9fa6e93a8218ad60": "Voz", + "eae80365006fbe17": "Um valor vazio usa a voz padrão do provedor.", + "5a640ef031aed4a2": "Voz de leitura em voz alta", + "f7323911c24ed501": "Padrão", + "b9c9fc9b61d7243e": "Voz padrão", + "c10f66d628754b10": "Velocidade", + "bff81cb00fc73544": "Velocidade de reprodução.", + "936895b764543aea": "Velocidade de leitura em voz alta", + "2fc5076786a6b6ed": "Pular blocos de código", + "0fed42221c860bd6": "Lê o texto e os identificadores em linha sem narrar os blocos de código.", + "951a30714876977f": "Pular blocos de código ao ler", + "bec2c35646e0496a": "Prévia", + "8ed4191b261076ff": "Reproduz uma amostra curta com o provedor de voz selecionado.", + "4b009ef01c76df8e": "Este é o T3 Code. A resposta do seu agente está pronta para ser lida em voz alta.", + "0dde517387ea2d57": "Parar prévia", + "88f2bec553b72827": "Reproduzir prévia", + "f7158c1af1da3afb": [ + "Usando seu arquivo em ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "bff944189ba9c100": "Baixar", + "b3976c9787134fd1": "Selecionado", + "f4c5cba0cd5dbb68": "Usar modelo", + "0b5ab0399461fdbd": "Usar existente", + "26aafec418058787": "Neste dispositivo", + "23196cabaa71f1da": "Em um ambiente", + "3ba49a214600d0ac": [ + "Nuvem via ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Gerenciar chave", "02bca2d9c90e5f1e": "{value}s", "af22f973466903c3": "{value}min", "401ba3f2391d8742": "{value}h", @@ -11107,7 +11198,6 @@ "97c969a0f9c64233": "Após 10 minutos", "bf7f24afa7084dd7": "Após 15 minutos", "590df316b67cc7d5": "Após 1 hora", - "c59720248f69d5aa": "Recomendado", "e4369ea318964a77": "Mais rápido", "cd9732fb0b7326e3": "Mais preciso", "62900eb52209c2e3": "Equilíbrio entre precisão e velocidade para os idiomas selecionados nos benchmarks de referência do Handy.", @@ -11118,12 +11208,6 @@ "665cbb7042a42206": "Traduzir", "82aa50f539d02537": "Pode escrever texto em inglês a partir de fala em outro idioma. Ative Traduzir para o inglês para usar.", "dc23ce436a29363d": "{count, plural, one {{count} idioma} other {{count} idiomas}}", - "c522c5460548c481": "Progresso do download de {name}", - "58a4b7a47e362024": "Verificando download…", - "8ee326cccca4ffe0": "{percent}% baixado", - "f36b40c99b8c221f": "Cancelar o download de {name}", - "53b05fd56e4de55b": "Parar de usar seu arquivo {name}; o arquivo continua no disco", - "34901bb929deb832": "Excluir {name}", "58d9cedba566716c": "Adicione palavras separadas por vírgulas", "8ce2d4078f890b77": "Adicionar uma palavra ou frase ao {label}", "6f40d219fdbe4ae9": "Alias de {term}", @@ -11170,8 +11254,6 @@ "1ce93a052681b78a": "Não foi possível cancelar o download", "51fd61b9c85dec5d": "Não foi possível excluir o modelo", "3d4be5cb172d6f91": "Não foi possível usar um modelo desse caminho", - "b98b8459bc0fc482": "Caminho de um arquivo ou pasta de modelo que já está neste ambiente", - "9e6dabb14a4947e5": "Já baixou em outro lugar? Cole o caminho do arquivo ou da pasta do modelo", "2060246c448d1de0": "Aguardando o ambiente se conectar", "c32c85efb80dc740": "Transcrição de teste", "4b2f68f90eb004f6": "Nenhuma fala reconhecida. Tente novamente.", @@ -11185,8 +11267,6 @@ "5c3711f9ed600d2a": "Transcrever com", "dccbcc6f313dea7e": "{label} não consegue transcrever áudio localmente. Escolha outro destino.", "817dbf1c068b62e7": "Onde sua fala é convertida em texto.", - "710d3e4f0243014c": "Ambiente escolhido (indisponível)", - "61088464d1b7174d": "ambiente indisponível", "71184e5a54a69f1d": "O provedor detecta seu idioma automaticamente.", "ffb2653eb2d9fc1a": "{model} detecta o idioma automaticamente.", "773cbfca7c466cc4": "{model} usa um idioma fixo.", @@ -11211,17 +11291,6 @@ "c652ed4a9a70f77f": "Instruções de limpeza personalizadas", "1c2d9ac371d77eea": "Frase de correção", "4f6141a8af8dc570": "A frase que você diz para corrigir um erro, como “apaga isso”.", - "f7158c1af1da3afb": [ - "Usando seu arquivo em ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], - "bff944189ba9c100": "Baixar", - "b3976c9787134fd1": "Selecionado", - "f4c5cba0cd5dbb68": "Usar modelo", "2c5c798252f91fdc": "Adicionar", "38b344bfa7d50343": "Alias", "c893707203cb6aee": "Conecte um ambiente primeiro.", @@ -11230,19 +11299,9 @@ "111dbc8f88feacff": "Nenhum idioma corresponde.", "003aa9115365f752": "Ordenar por", "736406a96ddadcd8": "Só baixados", - "0b5ab0399461fdbd": "Usar existente", "790951b4fc82052f": "Testar modelo", "a3eda37e8d337ebb": "Diga uma frase. A limpeza é ignorada, então você vê exatamente o que o modelo ouviu.", "c613b9c5d54f3c91": "Atualizar microfones", - "23196cabaa71f1da": "Em um ambiente", - "3ba49a214600d0ac": [ - "Nuvem via ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Ambiente escolhido (indisponível)", "e69e34d4f44d4136": "Integrado", "ae0b91ed52736998": "Usa o commit mais recente do branch remoto rastreado pelo branch base, mesmo que o nome seja diferente. Caso contrário, usa o branch de mesmo nome no origin. Usa seu branch local se esse branch remoto não existir.", @@ -11423,6 +11482,7 @@ "9d834d178130180e": "beta alpha simlock callstack simulador emulador ios android pool lease gateway", "bcb520297a9ae143": "beta rápido worktree checkout clonar apfs copy-on-write cache macos velocidade", "4c83ac419da342bd": "enviar áudio do microfone ditado destino fala voz stt transcrição ambiente máquina consentimento privacidade nuvem OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts texto para fala ler em voz alta voz reprodução OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "microfone entrada áudio dispositivo ordem prioridade preferido", "22811f405e0b4b28": "fala voz teclado atalho manter pressionado alternar automático", "e27bccf50397d9fe": "fala voz traduzir inglês detectar automaticamente", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 7e36f4bd730a1..5ee01dc4d0412 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names}: реакция «глаза»", "0c982111ac348e9f": "Вы", "766ea446df1695f7": "Ответьте на вопрос, чтобы редактировать сообщения в очереди", + "6e4d05cd77caff7c": "Не удалось возобновить чтение.", + "b02cc7b7adaa2361": "Не удалось прочитать этот ответ.", "257dc29de5b1f1f7": "Контекст, без кода", "edb97296086ba31e": "{count, plural, one {{count} файл} few {{count} файла} many {{count} файлов} other {{count} файла}}", "556df31b330166ff": "Введите название представления.", @@ -3838,6 +3840,11 @@ "de5c52c3f47ff209": "Отправлено T3 Code", "ded43a280aed9f20": "Открыть тред", "7635dd64bbbe10ec": "Открыть автоматизацию", + "154bec57dbece73c": "Остановить чтение", + "e3c3d4bcfa9727b9": "Продолжить чтение", + "0eceb5780908eb6c": "Чтение вслух", + "09a3f02127015c7d": "Не удалось прочитать вслух", + "81923647f1ef9740": "Отменить синтез речи", "6327e4ffa0f2366d": "Пул-реквесты недоступны", "90062342f04966ff": "Обновите сервер T3 Code этого окружения, чтобы просматривать пул-реквесты.", "5e7157db126f1641": "Issue недоступны", @@ -9144,6 +9151,90 @@ "5c0c973276a61fdb": "Не удалось сохранить разрешение маршрутизации пул-реквестов", "1bfcffe8411e2439": "Маршрутизация пул-реквестов для {environment}", "ae4761ddc038b102": "Машины, которым вы здесь доверяете, могут читать данные PR через доступ друг друга к контролю версий. Включите на обеих машинах. «Чтение и действия» может использовать более широкие права, чем у машины-владельца. Действует только на этом устройстве.", + "65a238ad6bebf802": "Читать ответы вслух с помощью {name}?", + "bfbaa4965c146e7c": "Все, кто использует {company} для диктовки или чтения вслух в {environment}, потеряют доступ.", + "b9e06e668bd9bff0": "Воспроизводимые ответы отправляются в {company} через {environment}, оплата идёт по его API-ключу. Ключ общий с диктовкой.", + "09f85302ef58020c": "При обновлении ключа чтение вслух остаётся включённым.", + "6e58953ca9c7fad5": "Любой, у кого есть доступ к {environment}, может тратить средства по этому ключу.", + "cf0740520675dcb9": [ + "Подключитесь к ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ", чтобы продолжить." + ], + "b0900f4938210634": "API-ключ", + "60609aae479dd41c": "Не удалось скачать модель. Проверьте подключение и свободное место в окружении.", + "1405f6ff92c1041a": "Не удалось изменить модель. Попробуйте ещё раз.", + "c59720248f69d5aa": "Рекомендуется", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "Загрузка {size}.", + "c522c5460548c481": "Прогресс загрузки {name}", + "58a4b7a47e362024": "Проверка загрузки…", + "8ee326cccca4ffe0": "Загружено {percent}%", + "f36b40c99b8c221f": "Отменить загрузку {name}", + "53b05fd56e4de55b": "Перестать использовать файл {name}; файл останется на диске", + "34901bb929deb832": "Удалить {name}", + "69a7c539add37d29": "По этому пути не найден файл речевой модели.", + "b98b8459bc0fc482": "Путь к файлу или папке модели, уже находящейся в этом окружении", + "9e6dabb14a4947e5": "Уже загружали в другом месте? Вставьте путь к файлу или папке модели", + "b4b7580d21c53b5f": "Не удалось загрузить речевые модели. Проверьте выбранное окружение и настройки провайдера.", + "293d67c7b56e7b69": "Провайдер речи", + "7bc4af4101c8997b": "У {environment} нет API-ключа {company}. Добавьте его кнопкой с ключом.", + "944dfe57d9653d32": "У этого окружения нет API-ключа {company}. Добавьте его кнопкой с ключом.", + "1c3796a6ec44558f": "Читайте готовые ответы кнопкой воспроизведения рядом с «Копировать». Облачные провайдеры получают текст через выбранное окружение; локальная модель работает на нём.", + "ee6859d2ad7f5842": "Провайдер чтения вслух", + "710d3e4f0243014c": "Выбранное окружение (недоступно)", + "61088464d1b7174d": "недоступное окружение", + "52e8f8accdca2d32": "Системные голоса", + "17076b27f1f3ada5": "Выкл.", + "0097b134ae6e9d9c": "Управлять ключом для чтения вслух", + "09bc28a37e6caf92": "Скачивается один раз в выбранное окружение, которое читает ответы, не передавая текст наружу.", + "d33ab3b324ba0b36": "Модели чтения вслух", + "3fb69cb2e760f23d": "Речевая модель", + "2d2ee6c94580e79f": "Выберите речевую модель из каталога провайдера.", + "44e370c9cc900c63": "Модель чтения вслух", + "9fa6e93a8218ad60": "Голос", + "eae80365006fbe17": "Пустое значение означает голос провайдера по умолчанию.", + "5a640ef031aed4a2": "Голос для чтения вслух", + "f7323911c24ed501": "По умолчанию", + "b9c9fc9b61d7243e": "Голос по умолчанию", + "c10f66d628754b10": "Скорость", + "bff81cb00fc73544": "Скорость воспроизведения.", + "936895b764543aea": "Скорость чтения вслух", + "2fc5076786a6b6ed": "Пропускать блоки кода", + "0fed42221c860bd6": "Читает текст и встроенные идентификаторы, не озвучивая блоки кода.", + "951a30714876977f": "Пропускать блоки кода при чтении", + "bec2c35646e0496a": "Пример", + "8ed4191b261076ff": "Воспроизводит короткий пример с выбранным провайдером речи.", + "4b009ef01c76df8e": "Это T3 Code. Ответ вашего агента готов к чтению вслух.", + "0dde517387ea2d57": "Остановить пример", + "88f2bec553b72827": "Воспроизвести пример", + "f7158c1af1da3afb": [ + "Используется ваш файл ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "bff944189ba9c100": "Скачать", + "b3976c9787134fd1": "Выбрано", + "f4c5cba0cd5dbb68": "Использовать модель", + "0b5ab0399461fdbd": "Использовать существующую", + "26aafec418058787": "На этом устройстве", + "23196cabaa71f1da": "В окружении", + "3ba49a214600d0ac": [ + "Облако через ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Управлять ключом", "02bca2d9c90e5f1e": "{value} с", "af22f973466903c3": "{value} мин", "401ba3f2391d8742": "{value} ч", @@ -11108,7 +11199,6 @@ "97c969a0f9c64233": "Через 10 минут", "bf7f24afa7084dd7": "Через 15 минут", "590df316b67cc7d5": "Через 1 час", - "c59720248f69d5aa": "Рекомендуется", "e4369ea318964a77": "Быстрее", "cd9732fb0b7326e3": "Точнее", "62900eb52209c2e3": "Баланс точности и скорости для выбранных языков по эталонным бенчмаркам Handy.", @@ -11119,12 +11209,6 @@ "665cbb7042a42206": "Перевод", "82aa50f539d02537": "Может записывать английский текст из речи на другом языке. Чтобы использовать, включите «Переводить на английский».", "dc23ce436a29363d": "{count, plural, one {{count} язык} few {{count} языка} many {{count} языков} other {{count} языка}}", - "c522c5460548c481": "Прогресс загрузки {name}", - "58a4b7a47e362024": "Проверка загрузки…", - "8ee326cccca4ffe0": "Загружено {percent}%", - "f36b40c99b8c221f": "Отменить загрузку {name}", - "53b05fd56e4de55b": "Перестать использовать файл {name}; файл останется на диске", - "34901bb929deb832": "Удалить {name}", "58d9cedba566716c": "Добавьте слова через запятую", "8ce2d4078f890b77": "Добавить слово или фразу в {label}", "6f40d219fdbe4ae9": "Псевдоним для {term}", @@ -11171,8 +11255,6 @@ "1ce93a052681b78a": "Не удалось отменить загрузку", "51fd61b9c85dec5d": "Не удалось удалить модель", "3d4be5cb172d6f91": "Не удалось использовать модель по этому пути", - "b98b8459bc0fc482": "Путь к файлу или папке модели, уже находящейся в этом окружении", - "9e6dabb14a4947e5": "Уже загружали в другом месте? Вставьте путь к файлу или папке модели", "2060246c448d1de0": "Ожидание подключения окружения", "c32c85efb80dc740": "Пробная расшифровка", "4b2f68f90eb004f6": "Речь не распознана. Попробуйте ещё раз.", @@ -11186,8 +11268,6 @@ "5c3711f9ed600d2a": "Расшифровывать через", "dccbcc6f313dea7e": "{label} не может расшифровывать аудио локально. Выберите другое место.", "817dbf1c068b62e7": "Где ваша речь превращается в текст.", - "710d3e4f0243014c": "Выбранное окружение (недоступно)", - "61088464d1b7174d": "недоступное окружение", "71184e5a54a69f1d": "Провайдер определяет язык автоматически.", "ffb2653eb2d9fc1a": "{model} определяет язык автоматически.", "773cbfca7c466cc4": "{model} использует один фиксированный язык.", @@ -11212,17 +11292,6 @@ "c652ed4a9a70f77f": "Свои инструкции для очистки", "1c2d9ac371d77eea": "Фраза исправления", "4f6141a8af8dc570": "Фраза, которую вы говорите, чтобы исправить ошибку, например «отмена».", - "f7158c1af1da3afb": [ - "Используется ваш файл ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], - "bff944189ba9c100": "Скачать", - "b3976c9787134fd1": "Выбрано", - "f4c5cba0cd5dbb68": "Использовать модель", "2c5c798252f91fdc": "Добавить", "38b344bfa7d50343": "Псевдоним", "c893707203cb6aee": "Сначала подключите окружение.", @@ -11231,19 +11300,9 @@ "111dbc8f88feacff": "Нет подходящих языков.", "003aa9115365f752": "Сортировать по", "736406a96ddadcd8": "Только загруженные", - "0b5ab0399461fdbd": "Использовать существующую", "790951b4fc82052f": "Проверить модель", "a3eda37e8d337ebb": "Скажите фразу. Очистка пропускается, поэтому вы увидите ровно то, что услышала модель.", "c613b9c5d54f3c91": "Обновить список микрофонов", - "23196cabaa71f1da": "В окружении", - "3ba49a214600d0ac": [ - "Облако через ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Выбранное окружение (недоступно)", "e69e34d4f44d4136": "Встроенные", "ae0b91ed52736998": "Использует последний коммит удалённой ветки, которую отслеживает базовая ветка, даже если её имя отличается. Иначе использует одноимённую ветку на origin. Если удалённой ветки нет, используется локальная.", @@ -11424,6 +11483,7 @@ "9d834d178130180e": "бета альфа simlock callstack симулятор эмулятор ios android пул аренда шлюз", "bcb520297a9ae143": "бета быстрый checkout рабочего дерева клон apfs copy-on-write кеш macos скорость", "4c83ac419da342bd": "отправить звук микрофона диктовка назначение речь голос stt расшифровка окружение компьютер согласие конфиденциальность облако OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts синтез речи озвучка чтение вслух голос воспроизведение OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "микрофон ввод звук устройство порядок приоритет предпочтительный", "22811f405e0b4b28": "речь голос клавиатура горячая клавиша удержание переключение авто", "e27bccf50397d9fe": "речь голос перевод английский автоопределение", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 95bcd0b80080a..ee25a8cae38dd 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} reagerade med ögon-emoji", "0c982111ac348e9f": "Du", "766ea446df1695f7": "Svara på frågan för att redigera köade meddelanden", + "6e4d05cd77caff7c": "Det gick inte att återuppta uppläsningen.", + "b02cc7b7adaa2361": "Det gick inte att läsa upp det här svaret.", "257dc29de5b1f1f7": "Kontext, ingen kod", "edb97296086ba31e": "{count, plural, one {{count} fil} other {{count} filer}}", "556df31b330166ff": "Ange ett namn för den här vyn.", @@ -3838,6 +3840,11 @@ "de5c52c3f47ff209": "Skickat av T3 Code", "ded43a280aed9f20": "Öppna tråd", "7635dd64bbbe10ec": "Öppna automatisering", + "154bec57dbece73c": "Sluta läsa upp", + "e3c3d4bcfa9727b9": "Fortsätt läsa upp", + "0eceb5780908eb6c": "Läs upp", + "09a3f02127015c7d": "Det gick inte att läsa upp", + "81923647f1ef9740": "Avbryt talgenereringen", "6327e4ffa0f2366d": "Pull requests är inte tillgängliga", "90062342f04966ff": "Uppdatera den här miljöns T3 Code-server för att bläddra bland pull requests.", "5e7157db126f1641": "Ärenden är inte tillgängliga", @@ -9150,6 +9157,90 @@ "5c0c973276a61fdb": "Kunde inte spara behörigheten för routning av pull requests", "1bfcffe8411e2439": "Routning av pull requests för {environment}", "ae4761ddc038b102": "Datorer du litar på här kan läsa PR-data via varandras åtkomst till versionshantering. Aktivera på båda datorerna. Läs och agera kan använda bredare behörigheter än den dator som äger dem. Gäller bara den här enheten.", + "65a238ad6bebf802": "Läsa upp svar med {name}?", + "bfbaa4965c146e7c": "Alla som använder {company} för diktering eller uppläsning på {environment} förlorar åtkomsten.", + "b9e06e668bd9bff0": "Svar som du spelar upp skickas till {company} via {environment}, som debiterar sin API-nyckel. Nyckeln delas med dikteringen.", + "09f85302ef58020c": "Uppläsningen förblir på när du uppdaterar nyckeln.", + "6e58953ca9c7fad5": "Alla med åtkomst till {environment} kan debitera den här nyckeln.", + "cf0740520675dcb9": [ + "Anslut till ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " för att fortsätta." + ], + "b0900f4938210634": "API-nyckel", + "60609aae479dd41c": "Det gick inte att ladda ned modellen. Kontrollera miljöns anslutning och diskutrymme.", + "1405f6ff92c1041a": "Det gick inte att ändra modellen. Försök igen.", + "c59720248f69d5aa": "Rekommenderad", + "d5b9ecbc5062b6a7": "{size}.", + "c2be8693c77597a3": "{size} att ladda ned.", + "c522c5460548c481": "Nedladdningsförlopp för {name}", + "58a4b7a47e362024": "Verifierar nedladdningen…", + "8ee326cccca4ffe0": "{percent} % nedladdat", + "f36b40c99b8c221f": "Avbryt nedladdningen av {name}", + "53b05fd56e4de55b": "Sluta använda din {name}-fil; filen ligger kvar på disken", + "34901bb929deb832": "Ta bort {name}", + "69a7c539add37d29": "Ingen talmodellfil hittades på den sökvägen.", + "b98b8459bc0fc482": "Sökväg till en modellfil eller mapp som redan finns i den här miljön", + "9e6dabb14a4947e5": "Redan nedladdad någon annanstans? Klistra in sökvägen till modellfilen eller mappen", + "b4b7580d21c53b5f": "Det gick inte att läsa in talmodeller. Kontrollera den valda miljön och leverantörens konfiguration.", + "293d67c7b56e7b69": "Talleverantör", + "7bc4af4101c8997b": "{environment} har ingen API-nyckel för {company}. Lägg till en med nyckelknappen.", + "944dfe57d9653d32": "Den här miljön har ingen API-nyckel för {company}. Lägg till en med nyckelknappen.", + "1c3796a6ec44558f": "Läs upp färdiga svar med uppspelningsknappen bredvid Kopiera. Värdbaserade leverantörer tar emot svarstexten via den valda miljön; en lokal modell körs på den.", + "ee6859d2ad7f5842": "Uppläsningsleverantör", + "710d3e4f0243014c": "Vald miljö (inte tillgänglig)", + "61088464d1b7174d": "miljö som inte är tillgänglig", + "52e8f8accdca2d32": "Systemröster", + "17076b27f1f3ada5": "Av", + "0097b134ae6e9d9c": "Hantera uppläsningsnyckel", + "09bc28a37e6caf92": "Laddas ned en gång till den valda miljön, som läser upp svar utan att texten lämnar den.", + "d33ab3b324ba0b36": "Uppläsningsmodeller", + "3fb69cb2e760f23d": "Talmodell", + "2d2ee6c94580e79f": "Välj en talmodell från leverantörens katalog.", + "44e370c9cc900c63": "Uppläsningsmodell", + "9fa6e93a8218ad60": "Röst", + "eae80365006fbe17": "Ett tomt värde använder leverantörens standardröst.", + "5a640ef031aed4a2": "Uppläsningsröst", + "f7323911c24ed501": "Standard", + "b9c9fc9b61d7243e": "Standardröst", + "c10f66d628754b10": "Hastighet", + "bff81cb00fc73544": "Uppspelningshastighet.", + "936895b764543aea": "Uppläsningshastighet", + "2fc5076786a6b6ed": "Hoppa över kodblock", + "0fed42221c860bd6": "Läser upp text och inbäddade identifierare utan att läsa upp kodblock.", + "951a30714876977f": "Hoppa över kodblock vid uppläsning", + "bec2c35646e0496a": "Förhandsvisning", + "8ed4191b261076ff": "Spelar upp ett kort exempel med den valda talleverantören.", + "4b009ef01c76df8e": "Det här är T3 Code. Agentens svar är redo att läsas upp.", + "0dde517387ea2d57": "Stoppa förhandsvisningen", + "88f2bec553b72827": "Spela upp förhandsvisning", + "f7158c1af1da3afb": [ + "Använder din fil på ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "bff944189ba9c100": "Ladda ned", + "b3976c9787134fd1": "Vald", + "f4c5cba0cd5dbb68": "Använd modell", + "0b5ab0399461fdbd": "Använd befintlig", + "26aafec418058787": "På den här enheten", + "23196cabaa71f1da": "I en miljö", + "3ba49a214600d0ac": [ + "Moln via ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "6793112a0a873441": "Hantera nyckel", "02bca2d9c90e5f1e": "{value} s", "af22f973466903c3": "{value} min", "401ba3f2391d8742": "{value} h", @@ -11116,7 +11207,6 @@ "97c969a0f9c64233": "Efter 10 minuter", "bf7f24afa7084dd7": "Efter 15 minuter", "590df316b67cc7d5": "Efter 1 timme", - "c59720248f69d5aa": "Rekommenderad", "e4369ea318964a77": "Snabbare", "cd9732fb0b7326e3": "Mer exakt", "62900eb52209c2e3": "Balanserad noggrannhet och hastighet för dina valda språk i Handys referensbenchmarks.", @@ -11127,12 +11217,6 @@ "665cbb7042a42206": "Översätt", "82aa50f539d02537": "Kan skriva engelsk text från tal på ett annat språk. Slå på Översätt till engelska för att använda det.", "dc23ce436a29363d": "{count, plural, one {{count} språk} other {{count} språk}}", - "c522c5460548c481": "Nedladdningsförlopp för {name}", - "58a4b7a47e362024": "Verifierar nedladdningen…", - "8ee326cccca4ffe0": "{percent} % nedladdat", - "f36b40c99b8c221f": "Avbryt nedladdningen av {name}", - "53b05fd56e4de55b": "Sluta använda din {name}-fil; filen ligger kvar på disken", - "34901bb929deb832": "Ta bort {name}", "58d9cedba566716c": "Lägg till ord, avgränsade med kommatecken", "8ce2d4078f890b77": "Lägg till ett ord eller en fras i {label}", "6f40d219fdbe4ae9": "Alias för {term}", @@ -11179,8 +11263,6 @@ "1ce93a052681b78a": "Kunde inte avbryta nedladdningen", "51fd61b9c85dec5d": "Kunde inte ta bort modellen", "3d4be5cb172d6f91": "Kunde inte använda en modell från den sökvägen", - "b98b8459bc0fc482": "Sökväg till en modellfil eller mapp som redan finns i den här miljön", - "9e6dabb14a4947e5": "Redan nedladdad någon annanstans? Klistra in sökvägen till modellfilen eller mappen", "2060246c448d1de0": "Väntar på att miljön ansluter", "c32c85efb80dc740": "Testtranskription", "4b2f68f90eb004f6": "Inget tal kändes igen. Försök igen.", @@ -11194,8 +11276,6 @@ "5c3711f9ed600d2a": "Transkribera med", "dccbcc6f313dea7e": "{label} kan inte transkribera ljud lokalt. Välj ett annat mål.", "817dbf1c068b62e7": "Var ditt tal omvandlas till text.", - "710d3e4f0243014c": "Vald miljö (inte tillgänglig)", - "61088464d1b7174d": "miljö som inte är tillgänglig", "71184e5a54a69f1d": "Leverantören identifierar ditt språk automatiskt.", "ffb2653eb2d9fc1a": "{model} identifierar språket automatiskt.", "773cbfca7c466cc4": "{model} använder ett fast språk.", @@ -11220,17 +11300,6 @@ "c652ed4a9a70f77f": "Anpassade instruktioner för rensning", "1c2d9ac371d77eea": "Rättelsefras", "4f6141a8af8dc570": "Frasen du säger för att rätta ett misstag, till exempel ”stryk det”.", - "f7158c1af1da3afb": [ - "Använder din fil på ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], - "bff944189ba9c100": "Ladda ned", - "b3976c9787134fd1": "Vald", - "f4c5cba0cd5dbb68": "Använd modell", "2c5c798252f91fdc": "Lägg till", "38b344bfa7d50343": "Alias", "c893707203cb6aee": "Anslut en miljö först.", @@ -11239,19 +11308,9 @@ "111dbc8f88feacff": "Inga språk matchar.", "003aa9115365f752": "Sortera efter", "736406a96ddadcd8": "Endast nedladdade", - "0b5ab0399461fdbd": "Använd befintlig", "790951b4fc82052f": "Testa modell", "a3eda37e8d337ebb": "Säg en mening. Rensningen hoppas över, så du ser exakt vad modellen hörde.", "c613b9c5d54f3c91": "Uppdatera mikrofoner", - "23196cabaa71f1da": "I en miljö", - "3ba49a214600d0ac": [ - "Moln via ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - } - ], "625f25278bc683ba": "Vald miljö (inte tillgänglig)", "e69e34d4f44d4136": "Inbyggd", "ae0b91ed52736998": "Använder den senaste commiten i basgrenens spårade fjärrgren, även om namnet skiljer sig. Annars används grenen med samma namn på origin. Använder din lokala gren om fjärrgrenen saknas.", @@ -11432,6 +11491,7 @@ "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lån gateway", "bcb520297a9ae143": "beta snabb worktree utcheckning klon apfs copy-on-write cache macos hastighet", "4c83ac419da342bd": "skicka mikrofonljud diktering mål tal röst stt transkribering miljö dator samtycke integritet moln OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts text till tal uppläsning läs upp röst uppspelning OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "mikrofon indata ljud enhet ordning prioritet föredragen", "22811f405e0b4b28": "tal röst tangentbord snabbtangent håll växla auto", "e27bccf50397d9fe": "tal röst översätt engelska identifiera automatiskt", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 7f161ed108acf..c19fc50f37bb4 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -112,6 +112,8 @@ "fc34e41fa0315912": "{names} 用“眼睛”表情做出了回应", "0c982111ac348e9f": "你", "766ea446df1695f7": "请回答问题后再编辑排队消息", + "6e4d05cd77caff7c": "无法继续朗读。", + "b02cc7b7adaa2361": "无法朗读此回复。", "257dc29de5b1f1f7": "背景说明,无代码", "edb97296086ba31e": "{count, plural, other {{count} 个文件}}", "556df31b330166ff": "请输入此视图的名称。", @@ -3843,6 +3845,11 @@ "de5c52c3f47ff209": "由 T3 Code 发送", "ded43a280aed9f20": "打开会话", "7635dd64bbbe10ec": "打开自动化", + "154bec57dbece73c": "停止朗读", + "e3c3d4bcfa9727b9": "继续朗读", + "0eceb5780908eb6c": "朗读", + "09a3f02127015c7d": "无法朗读", + "81923647f1ef9740": "取消语音生成", "6327e4ffa0f2366d": "PR 不可用", "90062342f04966ff": "请更新此环境的 T3 Code 服务器后再浏览 pull request。", "5e7157db126f1641": "issue 不可用", @@ -9160,6 +9167,92 @@ "5c0c973276a61fdb": "无法保存 pull request 路由权限", "1bfcffe8411e2439": "{environment} 的 PR 路由", "ae4761ddc038b102": "此处信任的机器可借助彼此的版本控制访问权限读取 PR 数据。需要在两台机器上都启用。“读取并操作”可能使用比权限所属机器更广的权限。此设置仅适用于当前设备。", + "65a238ad6bebf802": "使用 {name} 朗读回复?", + "bfbaa4965c146e7c": "在 {environment} 上使用 {company} 进行听写或朗读的所有人都将失去访问权限。", + "b9e06e668bd9bff0": "你播放的回复会通过 {environment} 发送到 {company},费用计入其 API 密钥。该密钥与听写共用。", + "09f85302ef58020c": "更新密钥后朗读仍保持开启。", + "6e58953ca9c7fad5": "有权访问 {environment} 的人都可以使用此密钥产生费用。", + "cf0740520675dcb9": [ + "连接到 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 以继续。" + ], + "b0900f4938210634": "API 密钥", + "60609aae479dd41c": "无法下载模型。请检查环境的连接和磁盘空间。", + "1405f6ff92c1041a": "无法更改模型。请重试。", + "c59720248f69d5aa": "推荐", + "d5b9ecbc5062b6a7": "{size}。", + "c2be8693c77597a3": "下载大小 {size}。", + "c522c5460548c481": "{name} 下载进度", + "58a4b7a47e362024": "正在校验下载内容…", + "8ee326cccca4ffe0": "已下载 {percent}%", + "f36b40c99b8c221f": "取消 {name} 下载", + "53b05fd56e4de55b": "停止使用你的 {name} 文件;文件会保留在磁盘上", + "34901bb929deb832": "删除 {name}", + "69a7c539add37d29": "在该路径下未找到语音模型文件。", + "b98b8459bc0fc482": "此环境上已有的模型文件或文件夹路径", + "9e6dabb14a4947e5": "已在别处下载过?粘贴模型文件或文件夹路径", + "b4b7580d21c53b5f": "无法加载语音模型。请检查所选环境和提供商配置。", + "293d67c7b56e7b69": "语音提供商", + "7bc4af4101c8997b": "{environment} 没有 {company} API 密钥。请使用密钥按钮添加。", + "944dfe57d9653d32": "此环境没有 {company} API 密钥。请使用密钥按钮添加。", + "1c3796a6ec44558f": "使用“复制”旁边的播放按钮朗读已完成的回复。托管提供商会通过所选环境接收回复文本;本地模型在该环境上运行。", + "ee6859d2ad7f5842": "朗读提供商", + "710d3e4f0243014c": "已选择的环境(不可用)", + "61088464d1b7174d": "环境不可用", + "52e8f8accdca2d32": "系统语音", + "17076b27f1f3ada5": "关闭", + "0097b134ae6e9d9c": "管理朗读密钥", + "09bc28a37e6caf92": "只需下载一次到所选环境,朗读回复时文本不会离开该环境。", + "d33ab3b324ba0b36": "朗读模型", + "3fb69cb2e760f23d": "语音模型", + "2d2ee6c94580e79f": "从提供商目录中选择语音模型。", + "44e370c9cc900c63": "朗读模型", + "9fa6e93a8218ad60": "声音", + "eae80365006fbe17": "留空则使用提供商的默认声音。", + "5a640ef031aed4a2": "朗读声音", + "f7323911c24ed501": "默认", + "b9c9fc9b61d7243e": "默认声音", + "c10f66d628754b10": "语速", + "bff81cb00fc73544": "播放速度。", + "936895b764543aea": "朗读语速", + "2fc5076786a6b6ed": "跳过代码块", + "0fed42221c860bd6": "朗读正文和行内标识符,不朗读代码块。", + "951a30714876977f": "朗读时跳过代码块", + "bec2c35646e0496a": "试听", + "8ed4191b261076ff": "使用所选语音提供商播放一段简短示例。", + "4b009ef01c76df8e": "这里是 T3 Code。你的代理回复已可以朗读。", + "0dde517387ea2d57": "停止试听", + "88f2bec553b72827": "播放试听", + "f7158c1af1da3afb": [ + "正在使用你位于 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 的文件" + ], + "bff944189ba9c100": "下载", + "b3976c9787134fd1": "已选择", + "f4c5cba0cd5dbb68": "使用模型", + "0b5ab0399461fdbd": "使用已有", + "26aafec418058787": "在此设备上", + "23196cabaa71f1da": "在环境中", + "3ba49a214600d0ac": [ + "通过 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 使用云端" + ], + "6793112a0a873441": "管理密钥", "02bca2d9c90e5f1e": "{value} 秒", "af22f973466903c3": "{value} 分钟", "401ba3f2391d8742": "{value} 小时", @@ -11130,7 +11223,6 @@ "97c969a0f9c64233": "10 分钟后", "bf7f24afa7084dd7": "15 分钟后", "590df316b67cc7d5": "1 小时后", - "c59720248f69d5aa": "推荐", "e4369ea318964a77": "更快", "cd9732fb0b7326e3": "更准确", "62900eb52209c2e3": "根据 Handy 的参考基准测试,在所选语言上兼顾准确率与速度。", @@ -11141,12 +11233,6 @@ "665cbb7042a42206": "翻译", "82aa50f539d02537": "可将其他语言的语音转为英文。开启“翻译为英文”即可使用。", "dc23ce436a29363d": "{count, plural, other {{count} 种语言}}", - "c522c5460548c481": "{name} 下载进度", - "58a4b7a47e362024": "正在校验下载内容…", - "8ee326cccca4ffe0": "已下载 {percent}%", - "f36b40c99b8c221f": "取消 {name} 下载", - "53b05fd56e4de55b": "停止使用你的 {name} 文件;文件会保留在磁盘上", - "34901bb929deb832": "删除 {name}", "58d9cedba566716c": "添加词语,以逗号分隔", "8ce2d4078f890b77": "向 {label} 添加词语或短语", "6f40d219fdbe4ae9": "{term} 的别名", @@ -11193,8 +11279,6 @@ "1ce93a052681b78a": "无法取消下载", "51fd61b9c85dec5d": "无法删除模型", "3d4be5cb172d6f91": "无法使用该路径下的模型", - "b98b8459bc0fc482": "此环境上已有的模型文件或文件夹路径", - "9e6dabb14a4947e5": "已在别处下载过?粘贴模型文件或文件夹路径", "2060246c448d1de0": "正在等待环境连接", "c32c85efb80dc740": "测试转写文本", "4b2f68f90eb004f6": "未识别到语音,请重试。", @@ -11208,8 +11292,6 @@ "5c3711f9ed600d2a": "转写方式", "dccbcc6f313dea7e": "{label} 无法在本地转写音频。请选择其他位置。", "817dbf1c068b62e7": "将语音转为文本的位置。", - "710d3e4f0243014c": "已选择的环境(不可用)", - "61088464d1b7174d": "环境不可用", "71184e5a54a69f1d": "提供方会自动检测语言。", "ffb2653eb2d9fc1a": "{model} 会自动检测语言。", "773cbfca7c466cc4": "{model} 使用固定语言。", @@ -11234,18 +11316,6 @@ "c652ed4a9a70f77f": "自定义文本整理指令", "1c2d9ac371d77eea": "纠正提示词", "4f6141a8af8dc570": "用于更正错误的口头指令,例如“撤销刚才的话”。", - "f7158c1af1da3afb": [ - "正在使用你位于 ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 的文件" - ], - "bff944189ba9c100": "下载", - "b3976c9787134fd1": "已选择", - "f4c5cba0cd5dbb68": "使用模型", "2c5c798252f91fdc": "添加", "38b344bfa7d50343": "别名", "c893707203cb6aee": "请先连接一个环境。", @@ -11254,20 +11324,9 @@ "111dbc8f88feacff": "没有匹配的语言。", "003aa9115365f752": "排序方式", "736406a96ddadcd8": "仅已下载", - "0b5ab0399461fdbd": "使用已有", "790951b4fc82052f": "测试模型", "a3eda37e8d337ebb": "说一句话。测试会跳过整理步骤,直接显示模型听到的内容。", "c613b9c5d54f3c91": "刷新麦克风", - "23196cabaa71f1da": "在环境中", - "3ba49a214600d0ac": [ - "通过 ", - { - "i": 1, - "k": "_gt_value_1", - "v": "v" - }, - " 使用云端" - ], "625f25278bc683ba": "已选择的环境(不可用)", "e69e34d4f44d4136": "内置", "ae0b91ed52736998": "使用基准分支所跟踪的远程分支的最新提交,即使名称不同。未跟踪远程分支时,使用 origin 上的同名分支。远程分支不存在时,使用本地分支。", @@ -11448,6 +11507,7 @@ "9d834d178130180e": "测试版 alpha simlock callstack 模拟器 ios android 池 租用 网关", "bcb520297a9ae143": "测试版 快速工作树检出 克隆 apfs 写时复制 缓存 macos 速度", "4c83ac419da342bd": "发送 麦克风 音频 听写 目标 语音 stt 转写 环境 机器 授权 隐私 云 OpenAI Grok OpenRouter", + "3985d8550c7bc219": "tts 文字转语音 朗读 语音 播放 OpenAI Grok OpenRouter ElevenLabs", "f9c000e92379d027": "麦克风 输入 音频 设备 顺序 优先级 首选", "22811f405e0b4b28": "语音 键盘 热键 长按 切换 自动", "e27bccf50397d9fe": "语音 翻译 英语 自动检测", diff --git a/apps/web/src/speech/readAloud.ts b/apps/web/src/speech/readAloud.ts index 2c1bb658328b5..abc83c8199cb1 100644 --- a/apps/web/src/speech/readAloud.ts +++ b/apps/web/src/speech/readAloud.ts @@ -1,3 +1,4 @@ +import { m } from "~/i18n/messages"; import { speechSpeedAppliedByProvider, type SpeechSynthesisCatalog } from "@t3tools/contracts"; import { createReadAloudController, @@ -108,4 +109,4 @@ export const readAloudController = createReadAloudController(async (text, settin }, finished, }; -}); +}, m); diff --git a/packages/client-runtime/src/readAloud.ts b/packages/client-runtime/src/readAloud.ts index 024e8fbf14bd0..2289c98038601 100644 --- a/packages/client-runtime/src/readAloud.ts +++ b/packages/client-runtime/src/readAloud.ts @@ -4,6 +4,8 @@ import { type ReadAloudSettings, } from "@t3tools/contracts"; import { readAloudText, splitReadAloudText } from "@t3tools/shared/read-aloud"; +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; const WARM_INTERVAL_MS = 4 * 60_000; @@ -39,6 +41,7 @@ export function createReadAloudController( settings: ReadAloudSettings, signal: AbortSignal, ) => Promise, + resolve: MFunctionType = mFallback, ) { type State = { id: string | null; @@ -126,7 +129,7 @@ export function createReadAloudController( } catch { if (active === owner) { stop(); - publish({ id, status: "error", error: "Could not resume speech." }); + publish({ id, status: "error", error: resolve(msg("Could not resume speech.")) }); } } }, @@ -178,7 +181,8 @@ export function createReadAloudController( publish({ id, status: "error", - error: error instanceof Error ? error.message : "Could not read this response.", + error: + error instanceof Error ? error.message : resolve(msg("Could not read this response.")), }); } }, From fab3ea8ce0fa0c1ebc2ee2b00a1fc3de937965f8 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 23 Nov 2026 20:32:54 -0600 Subject: [PATCH 33/33] fix(server): the CLI executable loads the MP3 encoder from disk Co-Authored-By: Claude Opus 5.5 --- apps/server/src/speech/synthesisAudio.ts | 46 ++++++++++++++++++------ 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/apps/server/src/speech/synthesisAudio.ts b/apps/server/src/speech/synthesisAudio.ts index 7675a15afd278..1c6ffe341c39d 100644 --- a/apps/server/src/speech/synthesisAudio.ts +++ b/apps/server/src/speech/synthesisAudio.ts @@ -1,7 +1,23 @@ -import { Mp3Encoder } from "@breezystack/lamejs"; +// @effect-diagnostics nodeBuiltinImport:off - lamejs loads from disk outside the bundle. +import * as NodeFSP from "node:fs/promises"; +import * as NodeModule from "node:module"; +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; +// lamejs stays external, and single-executables cannot import disk packages. Its `require` +// entry is an IIFE that exports nothing, so import its ES module by path instead. +let lamejs: Promise | undefined; +const loadLamejs = () => + (lamejs ??= (async () => { + const packagePath = NodeModule.findPackageJSON("@breezystack/lamejs", import.meta.url); + if (!packagePath) throw new Error("The MP3 encoder package is unavailable."); + const { module } = JSON.parse(await NodeFSP.readFile(packagePath, "utf8")); + const entry = NodePath.join(NodePath.dirname(packagePath), module); + return import(NodeURL.pathToFileURL(entry).href); + })()); + export const MAX_SYNTHESIS_BYTES = 32 * 1024 * 1024; /** @@ -58,17 +74,25 @@ export function encodeMp3( for (let index = 0; index < samples.length; index++) samples[index] = view.getInt16(index * 2, true) / 0x8000; const mono = pcm16Mono(samples, channels); - const encoder = new Mp3Encoder(1, rate, mp3Kbps(rate)); const slices = Math.ceil(mono.length / ENCODE_SLICE_SAMPLES); - return Stream.range(0, slices - 1).pipe( - Stream.mapEffect((slice) => - Effect.sync(() => { - const start = slice * ENCODE_SLICE_SAMPLES; - const parts = [encoder.encodeBuffer(mono.subarray(start, start + ENCODE_SLICE_SAMPLES))]; - if (slice === slices - 1) parts.push(encoder.flush()); - return concat(parts); - }).pipe(Effect.tap(() => Effect.yieldNow)), - ), + // A missing encoder package is a packaging defect, not a recoverable failure. + return Effect.promise(loadLamejs).pipe( + Effect.map(({ Mp3Encoder }) => { + const encoder = new Mp3Encoder(1, rate, mp3Kbps(rate)); + return Stream.range(0, slices - 1).pipe( + Stream.mapEffect((slice) => + Effect.sync(() => { + const start = slice * ENCODE_SLICE_SAMPLES; + const parts = [ + encoder.encodeBuffer(mono.subarray(start, start + ENCODE_SLICE_SAMPLES)), + ]; + if (slice === slices - 1) parts.push(encoder.flush()); + return concat(parts); + }).pipe(Effect.tap(() => Effect.yieldNow)), + ), + ); + }), + Stream.unwrap, Stream.filter((bytes) => bytes.length > 0), ); }