diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index a868851d5c9da..f657ceb5ef0bc 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -392,7 +392,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 d86ac2320328b..0f5b345681c90 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..d745ef5853f17 --- /dev/null +++ b/apps/mobile/src/features/read-aloud/ReadAloudButton.tsx @@ -0,0 +1,64 @@ +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"; +import * as Dialog from "../../components/ui/Dialog"; +import { readAloudController, warmReadAloud } 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, + ); + // 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 + ? gt("Stop reading") + : active && state.status === "paused" + ? gt("Resume reading") + : gt("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(gt("Could not read aloud"), result.error); + }} + > + + + ); +} 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..3e7ea0df9e590 --- /dev/null +++ b/apps/mobile/src/features/read-aloud/playback.test.ts @@ -0,0 +1,295 @@ +import { startSpeechSynthesis } from "@t3tools/client-runtime/voice-input"; +import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import * as Speech from "expo-speech"; +import { AppState, Platform } from "react-native"; +import { createAudioPlayer, setAudioModeAsync, type AudioStatus } from "expo-audio"; +import { acquireAudioSession, releaseAudioSession } from "../../lib/audioSession"; +import { readAloudController } from "./playback"; + +vi.mock("react-native", () => ({ + AppState: { + get currentState() { + return "active"; + }, + addEventListener: () => ({ remove() {} }), + }, + Platform: { + get OS() { + return "ios"; + }, + }, +})); +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("../../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", () => ({ + startSpeechSynthesis: vi.fn(() => ({ kind: "audio" })), + getSpeechSynthesisModels: vi.fn((_prepared: unknown, provider: string) => ({ + kind: "catalog", + provider, + })), +})); +vi.mock("../voice-input/voiceDestination", async () => { + const { EMPTY_SPEECH_SYNTHESIS_CATALOG } = await import("@t3tools/contracts"); + return { + runSpeech: async (operation: { kind: string; provider?: string }) => + operation.kind === "catalog" + ? { + ...EMPTY_SPEECH_SYNTHESIS_CATALOG, + defaultModel: "server-model", + speedAppliedByProvider: operation.provider !== "openrouter", + } + : "https://host.test/api/voice/synthesis/audio?token=stream", + }; +}); + +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 playing = Promise.withResolvers(); + const unsubscribe = readAloudController.subscribe(() => { + if (readAloudController.getSnapshot().status === "playing") playing.resolve(); + }); + using cleanup = new DisposableStack(); + cleanup.defer(() => { + readAloudController.stop(); + unsubscribe(); + }); + const player = { + play: vi.fn(() => started.resolve()), + pause: vi.fn(), + release: vi.fn(), + setPlaybackRate: vi.fn(), + setActiveForLockScreen: vi.fn(), + addListener: + vi.fn<(_event: string, listener: (status: Partial) => void) => void>(), + }; + vi.mocked(createAudioPlayer).mockReturnValue( + player as unknown as ReturnType, + ); + const run = readAloudController.start("cloud", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "openrouter", + speed: 1.25, + environmentId: EnvironmentId.make("host"), + backgroundPlayback: true, + }); + await started.promise; + await playing.promise; + expect(player.setPlaybackRate).toHaveBeenCalledWith(1.25); + expect(createAudioPlayer).toHaveBeenLastCalledWith( + "https://host.test/api/voice/synthesis/audio?token=stream", + expect.anything(), + ); + expect(startSpeechSynthesis).toHaveBeenLastCalledWith( + expect.anything(), + "openrouter", + expect.objectContaining({ model: "server-model", speed: 1.25 }), + ); + const statusChanged = player.addListener.mock.calls[0]![1]; + statusChanged({ + currentTime: 1, + duration: 10, + playing: false, + isLoaded: true, + isBuffering: true, + timeControlStatus: "waiting", + }); + expect(readAloudController.getSnapshot().status).toBe("playing"); + statusChanged({ + currentTime: 10, + duration: 10, + playing: false, + isLoaded: true, + isBuffering: false, + timeControlStatus: "paused", + }); + expect(readAloudController.getSnapshot().status).toBe("playing"); + statusChanged({ + currentTime: 1, + duration: 10, + playing: false, + isLoaded: true, + isBuffering: false, + timeControlStatus: "paused", + }); + expect(readAloudController.getSnapshot().status).toBe("paused"); + expect(player.setActiveForLockScreen).toHaveBeenLastCalledWith(true, expect.anything()); + const pausedRecorder = acquireAudioSession("recording"); + try { + expect(player.setActiveForLockScreen).toHaveBeenLastCalledWith(false); + } finally { + await releaseAudioSession(pausedRecorder); + } + await readAloudController.resume(); + statusChanged({ + currentTime: 1, + duration: 10, + playing: false, + isLoaded: true, + isBuffering: false, + timeControlStatus: "paused", + }); + const resumed = Promise.withResolvers(); + const unsubscribeResume = readAloudController.subscribe(() => { + if (readAloudController.getSnapshot().status === "playing") resumed.resolve(); + }); + cleanup.defer(unsubscribeResume); + statusChanged({ playing: true, isLoaded: true }); + await resumed.promise; + const recorder = acquireAudioSession("recording"); + try { + expect(player.setActiveForLockScreen).toHaveBeenLastCalledWith(false); + } finally { + readAloudController.stop(); + await run; + await releaseAudioSession(recorder); + unsubscribe(); + } +}); + +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(); + const initialized = Promise.withResolvers(); + vi.mocked(Speech.getAvailableVoicesAsync).mockClear(); + vi.mocked(Speech.getAvailableVoicesAsync).mockImplementationOnce(() => { + loading.resolve(); + return initialized.promise; + }); + vi.mocked(Speech.speak).mockClear(); + const run = readAloudController.start("android", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + voice: "", + }); + expect(Speech.getAvailableVoicesAsync).toHaveBeenCalled(); + await loading.promise; + readAloudController.stop(); + initialized.resolve([]); + await run; + expect(Speech.speak).not.toHaveBeenCalled(); +}); + +it.each(["system", "xai"] as const)( + "keeps %s silent when backgrounded during activation", + async (provider) => { + using state = vi.spyOn(AppState, "currentState", "get").mockReturnValue("active"); + const activating = Promise.withResolvers(); + const activated = Promise.withResolvers(); + vi.mocked(setAudioModeAsync).mockImplementationOnce(async () => { + activating.resolve(); + await activated.promise; + }); + const play = vi.fn(); + vi.mocked(Speech.speak).mockClear(); + const player = { + play, + pause: vi.fn(), + release: vi.fn(), + addListener: vi.fn(), + setActiveForLockScreen: vi.fn(), + }; + vi.mocked(createAudioPlayer).mockReturnValue( + player as unknown as ReturnType, + ); + const paused = Promise.withResolvers(); + const unsubscribe = readAloudController.subscribe(() => { + if (["paused", "playing"].includes(readAloudController.getSnapshot().status)) + paused.resolve(); + }); + const run = readAloudController.start("activation", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider, + environmentId: EnvironmentId.make("host"), + backgroundPlayback: false, + }); + try { + await activating.promise; + state.mockReturnValue("background"); + activated.resolve(); + await paused.promise; + expect(play).not.toHaveBeenCalled(); + expect(Speech.speak).not.toHaveBeenCalled(); + } finally { + readAloudController.stop(); + await run; + unsubscribe(); + } + }, +); 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..a79a4d904a330 --- /dev/null +++ b/apps/mobile/src/features/read-aloud/playback.ts @@ -0,0 +1,219 @@ +import { m } from "../../i18n/messages"; +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"; +import * as Speech from "expo-speech"; +import * as Option from "effect/Option"; +import { AppState, Platform } from "react-native"; +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"; +import { runSpeech } from "../voice-input/voiceDestination"; + +function pauseInBackground(settings: ReadAloudSettings) { + const shouldPause = !settings.backgroundPlayback && AppState.currentState !== "active"; + if (shouldPause) readAloudController.pause(); + return shouldPause; +} + +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 (pauseInBackground(settings)) return; + 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 () => { + if (pauseInBackground(settings)) return; + if (!(await session.play())) throw new Error("Finish recording before reading aloud."); + }, + pause: () => session.pause(), + stop: () => { + stopWatching(); + session.pause(); + generation++; + void Speech.stop().catch(() => {}); + done(); + }, + finished, + }; +} + +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 = + settings.voice || Platform.OS === "android" ? 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( + appAtomRegistry.get(environmentSession.preparedConnectionValueAtom(settings.environmentId)), + ) + : null; + if (!prepared) + throw new Error("Connect to the read-aloud environment selected in Settings → Voice."); + let pendingCatalog = catalogs.get(signal); + if (!pendingCatalog) { + pendingCatalog = runSpeech(getSpeechSynthesisModels(prepared, settings.provider), signal); + catalogs.set(signal, pendingCatalog); + } + 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, + voice: settings.voice, + speed: settings.speed, + language: settings.language, + }), + signal, + ); + signal.throwIfAborted(); + const player = createAudioPlayer(url, { updateInterval: 500 }); + if (!speechSpeedAppliedByProvider(catalog, model)) player.setPlaybackRate(settings.speed); + const stopWatching = watchForeground(settings); + const session = createAudioPlaybackSession( + { + play() { + if (!pauseInBackground(settings)) player.play(); + }, + pause: (deactivateSession) => player.pause(deactivateSession), + }, + false, + (requested, reason) => { + if (!requested) { + if (reason !== "pause") player.setActiveForLockScreen(false); + readAloudController.pause(); + } + }, + settings.backgroundPlayback, + // Native lock-screen Play bypasses JS, so a paused player must keep revocable ownership. + 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.")); + else if ( + status.playing && + session.requested && + readAloudController.getSnapshot().status === "paused" + ) + void readAloudController.resume(); + else if ( + session.requested && + status.isLoaded && + status.duration > 0 && + status.currentTime < status.duration && + !status.playing && + !status.isBuffering && + status.timeControlStatus === "paused" && + readAloudController.getSnapshot().status === "playing" + ) + readAloudController.pause(); + }); + }); + return { + play: async () => { + if (pauseInBackground(settings)) return; + if (settings.backgroundPlayback) + player.setActiveForLockScreen(true, { title: "T3 Code", artist: "Read aloud" }); + if (!(await session.play())) throw new Error("Finish recording before reading aloud."); + }, + pause: () => session.pause(), + stop: () => { + stopWatching(); + session.stop(); + disposeAudioPlayer(player); + done(); + }, + finished, + }; +}, m); diff --git a/apps/mobile/src/features/settings/ReadAloudSection.test.tsx b/apps/mobile/src/features/settings/ReadAloudSection.test.tsx new file mode 100644 index 0000000000000..f650628f6e09b --- /dev/null +++ b/apps/mobile/src/features/settings/ReadAloudSection.test.tsx @@ -0,0 +1,216 @@ +import { + DEFAULT_READ_ALOUD_SETTINGS, + EMPTY_SPEECH_SYNTHESIS_CATALOG, + EnvironmentId, + READ_ALOUD_LABELS, + type ReadAloudSettings, +} from "@t3tools/contracts"; +import { AsyncResult } from "effect/reactivity"; +import * as Option from "effect/Option"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; +import { ReadAloudSection } from "./ReadAloudSection"; + +const mocks = vi.hoisted(() => ({ + settings: null as ReadAloudSettings | null, + failures: 0, + pendingKey: null as Promise | null, + catalogError: "", + connection: { environmentId: "voice-host" }, + playback: { id: null, status: "idle" }, +})); +vi.mock("@effect/atom-react", () => ({ + useAtomValue: () => AsyncResult.success({ readAloud: mocks.settings }), +})); +vi.mock("../../state/preferences", () => ({ + mobilePreferencesAtom: {}, + saveMobilePreferences: {}, +})); +vi.mock("../../state/use-atom-command", () => ({ + useAtomCommand: () => async (patch: { readAloud: ReadAloudSettings }) => { + mocks.settings = patch.readAloud; + }, +})); +vi.mock("../../state/environments", () => ({ + useEnvironments: () => ({ environments: [{ environmentId: "voice-host", label: "Voice host" }] }), +})); +vi.mock("../../state/session", () => ({ + useEnvironmentScope: () => true, + usePreparedConnection: () => Option.some(mocks.connection), +})); +vi.mock("react-native", () => ({ + View: (props: { children?: ReactNode }) =>
{props.children}
, + ScrollView: (props: { children?: ReactNode }) =>
{props.children}
, + TextInput: ({ + value, + onChangeText, + accessibilityLabel, + }: { + value: string; + onChangeText(value: string): void; + accessibilityLabel: string; + }) => ( + onChangeText(event.currentTarget.value)} + /> + ), +})); +vi.mock("expo-speech", () => ({ getAvailableVoicesAsync: async () => [] })); +vi.mock("../../components/ui/AppText", () => ({ + AppText: ({ + children, + accessibilityRole, + }: { + children?: ReactNode; + accessibilityRole?: "alert"; + }) =>

{children}

, +})); +vi.mock("../../components/ui/ListSection", () => ({ + ListSection: (props: { children?: ReactNode }) =>
{props.children}
, +})); +vi.mock("../../components/ui/ListActionRow", () => ({ + ListActionRow: ({ label, onPress }: { label: string; onPress(): void }) => ( + + ), +})); +vi.mock("../../components/ui/ListChoiceRow", () => ({ + ListChoiceRow: ({ label, onPress }: { label: string; onPress(): void }) => ( + + ), +})); +vi.mock("../../components/ui/ListToggleRow", () => ({ ListToggleRow: () => null })); +vi.mock("../../components/ui/Sheet", () => ({ + Sheet: (props: { children?: ReactNode }) =>
{props.children}
, +})); +vi.mock("../../components/ui/Button", () => ({ + Button: ({ + label, + disabled, + onPress, + }: { + label: string; + disabled?: boolean; + onPress(): void; + }) => ( + + ), +})); +vi.mock("../read-aloud/playback", () => ({ + readAloudController: { subscribe: () => () => {}, getSnapshot: () => mocks.playback, stop() {} }, +})); +vi.mock("@t3tools/client-runtime/voice-input", () => ({ + getSpeechSynthesisModels: () => "catalog", + setCloudSpeechKey: () => "key", +})); +vi.mock("../voice-input/voiceDestination", () => ({ + runSpeech: async (operation: string) => { + if (operation === "catalog") + return { + ...EMPTY_SPEECH_SYNTHESIS_CATALOG, + apiKeyProvider: "xai", + error: mocks.catalogError, + }; + if (mocks.pendingKey) return mocks.pendingKey; + if (mocks.failures-- > 0) throw new Error("key operation failed"); + }, +})); + +async function mount() { + await using cleanup = new AsyncDisposableStack(); + const reactGlobal = globalThis as typeof globalThis & { + IS_REACT_ACT_ENVIRONMENT: boolean | undefined; + }; + const previous = reactGlobal.IS_REACT_ACT_ENVIRONMENT; + reactGlobal.IS_REACT_ACT_ENVIRONMENT = true; + cleanup.defer(() => { + reactGlobal.IS_REACT_ACT_ENVIRONMENT = previous; + }); + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + cleanup.defer(async () => { + try { + await act(async () => root.unmount()); + } finally { + host.remove(); + } + }); + await act(async () => root.render()); + const owned = cleanup.move(); + return { + host, + async [Symbol.asyncDispose]() { + await owned.disposeAsync(); + }, + }; +} + +async function click(host: HTMLElement, label: string) { + const button = [...host.querySelectorAll("button")].find((entry) => entry.textContent === label); + expect(button).toBeDefined(); + await act(async () => button!.click()); +} + +it.each(["retry", "source change"])("clears a failed key operation after %s", async (action) => { + mocks.settings = { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "xai", + environmentId: EnvironmentId.make("voice-host"), + }; + mocks.failures = 1; + mocks.pendingKey = null; + mocks.catalogError = ""; + await using screen = await mount(); + await click(screen.host, "Remove shared API key"); + expect(screen.host.querySelector('[role="alert"]')?.textContent).toContain("Could not remove"); + if (action === "retry") { + mocks.catalogError = "Later catalog error"; + await click(screen.host, "Remove shared API key"); + } else { + await click(screen.host, "Speech provider"); + await click(screen.host, "Off"); + } + if (action === "retry") + expect(screen.host.querySelector('[role="alert"]')?.textContent).toBe("Later catalog error"); + else expect(screen.host.querySelector('[role="alert"]')).toBeNull(); +}); + +it.each(["save", "remove"])( + "ignores stale key %s completions after switching providers", + async (operation) => { + mocks.settings = { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "xai", + environmentId: EnvironmentId.make("voice-host"), + }; + mocks.failures = 0; + mocks.catalogError = ""; + const pending = Promise.withResolvers(); + mocks.pendingKey = pending.promise; + await using screen = await mount(); + const draft = () => + screen.host.querySelector('input[aria-label="Read-aloud API key"]')!; + const enter = async (value: string) => + act(async () => { + draft().value = value; + draft().dispatchEvent(new Event("input", { bubbles: true })); + }); + await enter("original key"); + await click(screen.host, operation === "save" ? "Save key" : "Remove shared API key"); + await click(screen.host, "Speech provider"); + await click(screen.host, READ_ALOUD_LABELS.openai); + await enter("new provider draft"); + await act(async () => { + if (operation === "save") pending.resolve(); + else pending.reject(new Error("old provider failed")); + await pending.promise.catch(() => {}); + }); + expect(draft().value).toBe("new provider draft"); + expect(screen.host.querySelector('[role="alert"]')).toBeNull(); + }, +); diff --git a/apps/mobile/src/features/settings/ReadAloudSection.tsx b/apps/mobile/src/features/settings/ReadAloudSection.tsx new file mode 100644 index 0000000000000..f404a3fc33de6 --- /dev/null +++ b/apps/mobile/src/features/settings/ReadAloudSection.tsx @@ -0,0 +1,518 @@ +import { useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { 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, + CloudSpeechProvider, + DEFAULT_READ_ALOUD_SETTINGS, + READ_ALOUD_LABELS, + EMPTY_SPEECH_SYNTHESIS_CATALOG, + type ReadAloudSettings, + type SpeechSynthesisCatalog, +} from "@t3tools/contracts"; +import { + cancelSpeechSynthesisModelDownload, + downloadSpeechSynthesisModel, + getSpeechSynthesisModels, + removeSpeechSynthesisModel, + setCloudSpeechKey, +} from "@t3tools/client-runtime/voice-input"; +import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { useEnvironments } from "../../state/environments"; +import { useEnvironmentScope, usePreparedConnection } 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 gt = useGT(); + const preferences = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomCommand(saveMobilePreferences); + 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 } = 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<{ + key: string; + version: number; + catalog: SpeechSynthesisCatalog; + 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.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([]); + const [error, setError] = useState(""); + const [key, setKey] = useState(""); + const keyRequestVersion = useRef(0); + const state = useSyncExternalStore( + readAloudController.subscribe, + readAloudController.getSnapshot, + ); + const change = (patch: Partial) => { + readAloudController.stop(); + if (patch.provider !== undefined || patch.environmentId !== undefined) { + keyRequestVersion.current++; + setKey(""); + setError(""); + } + void savePreferences({ readAloud: { ...settings, ...patch } }); + }; + const cloud = catalog.apiKeyProvider !== null; + // 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 and invalidate speech requests when their environment or provider changes. + 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, + version: catalogVersion, + catalog: value, + failed: false, + }); + }, + () => { + if (!abort.signal.aborted) + setCatalogState({ + key: catalogKey, + version: catalogVersion, + catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, + failed: true, + }); + }, + ); + return () => { + abort.abort(); + keyRequestVersion.current++; + }; + }, [prepared, settings.provider, catalogKey, catalogVersion]); + const selectedModel = catalog.models.find((entry) => entry.id === model); + const install = settings.provider === "local" ? selectedModel?.install : undefined; + // 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 === 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. + useEffect(() => { + 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; + const requestKey = installKey; + if (action === "download") setInstalling(requestKey); + setError(""); + void runSpeech( + action === "download" + ? downloadSpeechSynthesisModel(prepared, selectedModel.id) + : action === "cancel" + ? cancelSpeechSynthesisModelDownload(prepared, selectedModel.id) + : removeSpeechSynthesisModel(prepared, selectedModel.id), + ) + .then( + () => {}, + () => + setError( + action === "download" + ? 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((current) => (current === requestKey ? null : current)); + setCatalogVersion((value) => value + 1); + }); + }; + const installProgress = + install?.downloaded === undefined ? 0 : Math.round((install.downloaded / install.size) * 100); + const voiceChoices = + settings.provider === "system" + ? voices.map((voice) => ({ id: voice.identifier, name: voice.name })) + : (selectedModel?.voices ?? []).map((voice) => ({ + id: voice, + name: selectedModel?.voiceNames?.[voice] ?? voice, + })); + const providerEnvironment = environments.find( + (environment) => environment.environmentId === settings.environmentId, + ); + return ( + <> + + { + setSheet("source"); + }} + /> + {settings.provider !== "off" && ( + <> + {settings.provider !== "system" && + catalog.supportsModelSelection && + catalog.models.length > 0 && ( + setSheet("model")} + /> + )} + {(settings.provider === "system" || + (catalog.supportsVoiceSelection && catalog.models.length > 0)) && ( + voice.id === settings.voice)?.name || + settings.voice || + 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", + gt("This is T3 Code. Your agent’s response is ready to read aloud."), + settings, + ) + } + /> + + )} + + {install && prepared && selectedModel && ( + + {downloading ? ( + changeInstall("cancel")} + /> + ) : install.state === "installed" ? ( + changeInstall("remove")} + /> + ) : ( + changeInstall("download")} + /> + )} + + )} + {cloud && prepared && canManage && ( + + + + + } + /> + + {active && state.status === "loading" + ? gt("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 9692bbedad62a..a7c1694e763d2 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/assistantInsights"; import { MessageId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; @@ -234,6 +235,9 @@ function AssistantMessageMeta({ {!message.streaming && projectedItem ? ( ) : null} + {!copyStreaming && message.text?.trim() && ( + + )} {!message.streaming && ( }> diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx index f859695e3360d..64586d2abe2ea 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.browser.test.tsx @@ -1,5 +1,9 @@ import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; -import { EnvironmentId } from "@t3tools/contracts"; +import { + DEFAULT_READ_ALOUD_SETTINGS, + EMPTY_SPEECH_SYNTHESIS_CATALOG, + 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,35 +11,40 @@ 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"; vi.mock(import("../../state/session"), { spy: true }); -vi.mock("../../state/environments", async (importOriginal) => ({ - ...(await importOriginal()), - useEnvironments: () => ({ - environments: [ - { - environmentId: "voice-host", - label: "Laptop", - connection: { phase: "available" }, - serverConfig: { - featureFlags: { secretProviders: true }, - 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: { + featureFlags: { secretProviders: true }, + 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"; @@ -259,3 +268,92 @@ it("OpenRouter needs an exact model, and changing it writes no credential", asyn }, ); }); + +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 }); + try { + await withVoicePanel( + (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 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({ + ...EMPTY_SPEECH_SYNTHESIS_CATALOG, + apiKeyProvider: "xai", + defaultModel: "server-default", + supportsModelSelection: true, + models: [{ id: "server-default", name: "Server default", voices: [] }], + }), + ); + return null; + }, + async (screen) => { + 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"); + }, + ); + } finally { + await updateClientSettings({ readAloud: previous }); + } +}); + +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 }, + }); + try { + await withVoicePanel( + (url) => + url.pathname === "/api/voice/synthesis/xai/models" + ? Promise.resolve(new Response(null, { status: 500 })) + : null, + async (screen) => { + await expect + .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 { + await updateClientSettings({ readAloud: previous }); + } +}); diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 3d41537abf182..a4b7ec7465db4 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -69,7 +69,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..fbe75a224b658 --- /dev/null +++ b/apps/web/src/components/settings/ReadAloudKeyDialog.tsx @@ -0,0 +1,291 @@ +import { + configuredSecretSources, + secretRequestReference, +} from "@t3tools/client-runtime/secret-request"; +import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; +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 { T, useGT, useMessages, Var } from "gt-react"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { AsyncResult } from "effect/reactivity"; +import { useId, useState } from "react"; +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 gt = useGT(); + const messages = useMessages(); + 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 = + hasFeatureFlag(environment.serverConfig, "secretProviders") && + environment.serverConfig?.secretReferences + ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) + : []; + 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(gt("Couldn’t save this change. Check your connection and try again.")); + } + setBusy(false); + }; + + return ( + { + if (!open && !busy) close(); + }} + > + + + + {remove + ? gt("Remove the {company} key?", { company }) + : active + ? gt("Manage {company} key", { company }) + : gt("Read replies aloud with {name}?", { name })} + + + {remove + ? gt( + "Everyone using {company} for dictation or read aloud on {environment} will lose access.", + { company, environment: environment.label }, + ) + : gt( + "Replies you play are sent to {company} through {environment}, which bills its API key. The key is shared with dictation.", + { company, environment: environment.label }, + )} + + + {!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 ?? + gt("Enter an API key, not a URL or secret reference.")) + : active + ? 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. + +

+ ) : ( +

+ + 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 new file mode 100644 index 0000000000000..52522baf03dbb --- /dev/null +++ b/apps/web/src/components/settings/ReadAloudSettingsSection.tsx @@ -0,0 +1,772 @@ +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 { + cancelSpeechSynthesisModelDownload, + downloadSpeechSynthesisModel, + getCloudSpeechKeys, + getSpeechSynthesisModels, + linkSpeechSynthesisModels, + removeSpeechSynthesisModel, +} 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, + type SpeechSynthesisProvider, +} from "@t3tools/contracts"; +import { + getClientSettings, + useClientSettings, + updateClientSettings, +} from "../../hooks/useSettings"; +import { useEnvironments } from "../../state/environments"; +import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; +import { runEnvironmentSpeech } from "../../speech/runEnvironmentSpeech"; +import { readAloudController } from "../../speech/readAloud"; +import { + CheckIcon, + DownloadIcon, + KeyRoundIcon, + MonitorIcon, + StarIcon, + Trash2Icon, + UnlinkIcon, + XIcon, +} from "lucide-react"; +import { Badge } from "../ui/badge"; +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 { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { useCloudRead } from "./CloudVoiceConfiguration"; +import { ReadAloudKeyDialog } from "./ReadAloudKeyDialog"; +import { SpeechProviderIcon } from "./SpeechProviderIcon"; + +const formatSize = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`; + +function LocalSpeechModel({ + prepared, + model, + selected, + recommended, + refreshing, + onSelect, + onDownloaded, + onChanged, +}: { + 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; + onDownloaded: () => void; + onChanged: () => void; +}) { + const gt = useGT(); + const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); + const [requesting, setRequesting] = useState(false); + const [error, setError] = 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. + useEffect(() => { + 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); + setError(""); + try { + const catalog = await runEnvironmentSpeech( + action === "download" + ? downloadSpeechSynthesisModel(prepared, model.id) + : action === "cancel" + ? cancelSpeechSynthesisModelDownload(prepared, model.id) + : removeSpeechSynthesisModel(prepared, model.id), + ); + // 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" + ? gt("Could not download the model. Check the environment’s connection and disk space.") + : gt("Could not change the model. Try again."), + ); + } + setRequesting(false); + onChanged(); + }; + const progress = + install.downloaded === undefined || install.size === 0 + ? 0 + : Math.min(100, (install.downloaded / install.size) * 100); + return ( +
+
+
+
+ {model.name} + {recommended && ( + + + {gt("Recommended")} + + )} +
+

+ {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} + +

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

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

+
+ )} + {error && ( +

+ {error} +

+ )} +
+
+ {downloading ? ( + + ) : install.state === "downloadable" ? ( + + ) : selected ? ( + + ) : ( + + )} + {install.state === "installed" && ( + + )} +
+
+
+ ); +} + +/** Links model files already on the environment instead of downloading them. */ +function LocalSpeechModelLink({ + prepared, + onChanged, +}: { + prepared: PreparedConnection; + onChanged: () => void; +}) { + const gt = useGT(); + const canManage = useEnvironmentScope(prepared.environmentId, AuthSettingsWriteScope); + const canReadFiles = useEnvironmentScope(prepared.environmentId, AuthFilesystemReadScope); + const [path, setPath] = useState(""); + const [linking, setLinking] = useState(false); + const [error, setError] = useState(""); + if (!canManage || !canReadFiles) return null; + return ( +
{ + event.preventDefault(); + setLinking(true); + setError(""); + void runEnvironmentSpeech(linkSpeechSynthesisModels(prepared, path)) + .then( + () => setPath(""), + () => setError(gt("No speech model file was found at that path.")), + ) + .finally(() => { + setLinking(false); + onChanged(); + }); + }} + > +
+ setPath(event.target.value)} + /> + {error && ( +

+ {error} +

+ )} +
+ +
+ ); +} + +export function ReadAloudSettingsSection() { + const gt = useGT(); + const settings = useClientSettings((value) => value.readAloud); + const { environments } = useEnvironments(); + + 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; + version: number; + catalog: SpeechSynthesisCatalog; + 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.failed + ? gt( + "Could not load speech models. Check the selected environment and provider configuration.", + ) + : catalog.error || "" + : ""; + const model = settings.model || catalog.defaultModel; + const localModels = + 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, + ); + 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, + version: catalogVersion, + catalog: result, + failed: false, + }); + }, + () => { + if (!abort.signal.aborted) + setCatalogState({ + key: catalogKey, + version: catalogVersion, + catalog: EMPTY_SPEECH_SYNTHESIS_CATALOG, + failed: true, + }); + }, + ); + 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 })) + : (modelEntry?.voices ?? []).map((voice) => ({ + id: voice, + 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, + ); + return ( + + + + {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} + ) : ( + 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={ +
+ + {cloudProvider && selectedEnvironment && ( + + + setPendingCloud({ + provider: cloudProvider, + environmentId: selectedEnvironment.environmentId, + }) + } + > + + + } + /> + + Manage key + + + )} +
+ } + /> +
+ {pendingCloud && pendingEnvironment && ( + + change({ + provider: pendingCloud.provider, + environmentId: pendingCloud.environmentId, + model: "", + voice: "", + }) + } + close={() => { + setPendingCloud(null); + refreshCatalog(); + }} + /> + )} + {settings.provider === "off" ? null : ( + <> + {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} + /> + ))} +
+ +
+ )} + {cloudProvider && catalog.supportsModelSelection && catalog.models.length > 0 && ( + { + if (value) change({ model: value, voice: "" }); + }} + > + + + {catalog.models.find((entry) => entry.id === model)?.name || + model || + gt("Choose a model")} + + + + {catalog.models.map((model) => ( + + {model.name} + + ))} + + + } + /> + )} + {(settings.provider === "system" || + (catalog.supportsVoiceSelection && catalog.models.length > 0)) && ( + { + if (value) change({ voice: value === "default" ? "" : value }); + }} + > + + + {voices.find((entry) => entry.id === settings.voice)?.name || + gt("Default", { $context: "default voice" })} + + + + + {gt("Default", { $context: "default voice" })} + + {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" && state.status !== "error" + ? readAloudController.stop() + : void readAloudController.start( + "read-aloud-preview", + gt("This is T3 Code. Your agent’s response is ready to read aloud."), + settings, + ) + } + > + {state.id === "read-aloud-preview" && state.status !== "error" + ? gt("Stop preview") + : gt("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..99eee76939444 --- /dev/null +++ b/apps/web/src/components/settings/SpeechProviderIcon.tsx @@ -0,0 +1,32 @@ +import { elevenLabsIcon, openRouterIcon } from "@t3tools/client-runtime/provider-clients"; +import { + CLOUD_SPEECH_LABELS, + READ_ALOUD_LABELS, + ProviderDriverKind, + type CloudSpeechProvider, + type ReadAloudSettings, +} from "@t3tools/contracts"; +import { CpuIcon, 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 === "local") return ; + if (provider === "openrouter") + return ; + if (provider === "elevenlabs") + return ; + return ( + + ); +} diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index a6283977cf534..2895ae96620ab 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 { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { m } from "~/i18n/messages"; import { @@ -12,7 +13,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, @@ -23,7 +23,6 @@ import { type EnvironmentSpeechModel, type EnvironmentSpeechStatus, type ProjectId, - ProviderDriverKind, type SpeechAcceleration, type SpeechBenchmarkTier, type SpeechCustomWords, @@ -95,8 +94,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"; @@ -150,17 +148,6 @@ import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings" const OFF = "off"; const DEVICE = "device"; -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: { @@ -1919,6 +1906,7 @@ export function VoiceSettingsPanel() { /> ) : null} + ); } diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index a7629c16be088..76640ae73530b 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -615,6 +615,14 @@ export const SETTINGS_SEARCH_ITEMS = [ ), ], }, + { + id: "read-aloud", + title: msg("Read aloud"), + to: "/settings/voice", + searchTerms: [ + msg("tts text to speech speak read aloud OpenAI Grok OpenRouter ElevenLabs voice playback"), + ], + }, { id: "voice-microphone", title: msg("Microphone"), diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 451583e0af615..c0b6a90f99aa9 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12870,5 +12870,65 @@ "f6a91589456cca50": "Genehmigt", "c92657bb7f2293ff": "Genehmigung nötig", "f1e5c1be1ac92361": "Genehmigen", - "fcb5f3c4d4753326": "Über diese Verbindung lassen sich keine Befehle genehmigen. Verwende einen Client, der das Terminal verwenden darf." + "fcb5f3c4d4753326": "Über diese Verbindung lassen sich keine Befehle genehmigen. Verwende einen Client, der das Terminal verwenden darf.", + "2fc5076786a6b6ed": "Codeblöcke überspringen", + "b0900f4938210634": "API-Schlüssel", + "6e4d05cd77caff7c": "Wiedergabe konnte nicht fortgesetzt werden.", + "8ed4191b261076ff": "Spielt ein kurzes Beispiel mit dem ausgewählten Sprachanbieter ab.", + "951a30714876977f": "Codeblöcke beim Vorlesen überspringen", + "26aafec418058787": "Auf diesem Gerät", + "5a640ef031aed4a2": "Vorlese-Stimme", + "3fb69cb2e760f23d": "Sprachmodell", + "81923647f1ef9740": "Sprachausgabe abbrechen", + "60609aae479dd41c": "Das Modell konnte nicht heruntergeladen werden. Prüfen Sie die Verbindung und den Speicherplatz der Umgebung.", + "c10f66d628754b10": "Geschwindigkeit", + "09a3f02127015c7d": "Vorlesen fehlgeschlagen", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "Unter diesem Pfad wurde keine Sprachmodelldatei gefunden.", + "944dfe57d9653d32": "Diese Umgebung hat keinen {company}-API-Schlüssel. Fügen Sie über die Schlüssel-Schaltfläche einen hinzu.", + "e3c3d4bcfa9727b9": "Vorlesen fortsetzen", + "09bc28a37e6caf92": "Wird einmal in die ausgewählte Umgebung heruntergeladen, die Antworten vorliest, ohne dass der Text sie verlässt.", + "0097b134ae6e9d9c": "Vorlese-Schlüssel verwalten", + "44e370c9cc900c63": "Vorlese-Modell", + "6e58953ca9c7fad5": "Alle mit Zugriff auf {environment} können über diesen Schlüssel abrechnen.", + "f7323911c24ed501": "Standard", + "c2be8693c77597a3": "{size} Download.", + "eae80365006fbe17": "Ohne Angabe wird die Standardstimme des Anbieters verwendet.", + "b02cc7b7adaa2361": "Diese Antwort konnte nicht vorgelesen werden.", + "0dde517387ea2d57": "Vorschau beenden", + "ee6859d2ad7f5842": "Vorlese-Anbieter", + "0fed42221c860bd6": "Liest Fließtext und Inline-Bezeichner, ohne Codeblöcke vorzulesen.", + "88f2bec553b72827": "Vorschau abspielen", + "d33ab3b324ba0b36": "Vorlese-Modelle", + "2d2ee6c94580e79f": "Wählen Sie ein Sprachmodell aus dem Katalog des Anbieters.", + "bfbaa4965c146e7c": "Alle, die {company} auf {environment} zum Diktieren oder Vorlesen nutzen, verlieren den Zugriff.", + "bff81cb00fc73544": "Wiedergabegeschwindigkeit.", + "6793112a0a873441": "Schlüssel verwalten", + "b9c9fc9b61d7243e": "Standardstimme", + "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.", + "936895b764543aea": "Vorlesegeschwindigkeit", + "4b009ef01c76df8e": "Das ist T3 Code. Die Antwort Ihres Agenten kann jetzt vorgelesen werden.", + "09f85302ef58020c": "Wenn Sie den Schlüssel aktualisieren, bleibt Vorlesen aktiviert.", + "bec2c35646e0496a": "Vorschau", + "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.", + "3985d8550c7bc219": "tts text to speech sprachausgabe vorlesen sprechen stimme wiedergabe OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "Stimme", + "17076b27f1f3ada5": "Aus", + "154bec57dbece73c": "Vorlesen beenden", + "65a238ad6bebf802": "Antworten mit {name} vorlesen?", + "293d67c7b56e7b69": "Sprachanbieter", + "7bc4af4101c8997b": "{environment} hat keinen {company}-API-Schlüssel. Fügen Sie über die Schlüssel-Schaltfläche einen hinzu.", + "b4b7580d21c53b5f": "Sprachmodelle konnten nicht geladen werden. Prüfen Sie die ausgewählte Umgebung und die Anbieterkonfiguration.", + "52e8f8accdca2d32": "Systemstimmen", + "0eceb5780908eb6c": "Vorlesen", + "cf0740520675dcb9": [ + "Verbinden Sie sich mit ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ", um fortzufahren." + ], + "1405f6ff92c1041a": "Das Modell konnte nicht geändert werden. Versuchen Sie es erneut." } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index bbdaf48e88d35..465e09eb85d7a 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12879,5 +12879,65 @@ "f6a91589456cca50": "Approved", "c92657bb7f2293ff": "Needs approval", "f1e5c1be1ac92361": "Approve", - "fcb5f3c4d4753326": "This connection cannot approve commands. Use a client that can use the terminal." + "fcb5f3c4d4753326": "This connection cannot approve commands. Use a client that can use the terminal.", + "2fc5076786a6b6ed": "Skip code blocks", + "b0900f4938210634": "API key", + "6e4d05cd77caff7c": "Could not resume speech.", + "8ed4191b261076ff": "Play a short sample using the selected speech provider.", + "951a30714876977f": "Skip code blocks when reading", + "26aafec418058787": "On this device", + "5a640ef031aed4a2": "Read-aloud voice", + "3fb69cb2e760f23d": "Speech model", + "81923647f1ef9740": "Cancel speech generation", + "60609aae479dd41c": "Could not download the model. Check the environment’s connection and disk space.", + "c10f66d628754b10": "Speed", + "09a3f02127015c7d": "Could not read aloud", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "No speech model file was found at that path.", + "944dfe57d9653d32": "This environment has no {company} API key. Add one with the key button.", + "e3c3d4bcfa9727b9": "Resume reading", + "09bc28a37e6caf92": "Downloaded once to the selected environment, which reads replies without the text leaving it.", + "0097b134ae6e9d9c": "Manage read-aloud key", + "44e370c9cc900c63": "Read-aloud model", + "6e58953ca9c7fad5": "Anyone with access to {environment} can bill this key.", + "f7323911c24ed501": "Default", + "c2be8693c77597a3": "{size} download.", + "eae80365006fbe17": "An empty value uses the provider’s default voice.", + "b02cc7b7adaa2361": "Could not read this response.", + "0dde517387ea2d57": "Stop preview", + "ee6859d2ad7f5842": "Read-aloud provider", + "0fed42221c860bd6": "Read the prose and inline identifiers without narrating fenced code blocks.", + "88f2bec553b72827": "Play preview", + "d33ab3b324ba0b36": "Read-aloud models", + "2d2ee6c94580e79f": "Choose a speech model from the provider catalog.", + "bfbaa4965c146e7c": "Everyone using {company} for dictation or read aloud on {environment} will lose access.", + "bff81cb00fc73544": "Playback speed.", + "6793112a0a873441": "Manage key", + "b9c9fc9b61d7243e": "Default voice", + "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.", + "936895b764543aea": "Read-aloud speed", + "4b009ef01c76df8e": "This is T3 Code. Your agent’s response is ready to read aloud.", + "09f85302ef58020c": "Updating the key keeps read aloud on.", + "bec2c35646e0496a": "Preview", + "b9e06e668bd9bff0": "Replies you play are sent to {company} through {environment}, which bills its API key. The key is shared with dictation.", + "3985d8550c7bc219": "tts text to speech speak read aloud OpenAI Grok OpenRouter ElevenLabs voice playback", + "9fa6e93a8218ad60": "Voice", + "17076b27f1f3ada5": "Off", + "154bec57dbece73c": "Stop reading", + "65a238ad6bebf802": "Read replies aloud with {name}?", + "293d67c7b56e7b69": "Speech provider", + "7bc4af4101c8997b": "{environment} has no {company} API key. Add one with the key button.", + "b4b7580d21c53b5f": "Could not load speech models. Check the selected environment and provider configuration.", + "52e8f8accdca2d32": "System voices", + "0eceb5780908eb6c": "Read aloud", + "cf0740520675dcb9": [ + "Connect to ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " to continue." + ], + "1405f6ff92c1041a": "Could not change the model. Try again." } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4daae8ed3cbfd..9f0c2fe1f154a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12865,5 +12865,65 @@ "f6a91589456cca50": "Aprobado", "c92657bb7f2293ff": "Necesita aprobación", "f1e5c1be1ac92361": "Aprobar", - "fcb5f3c4d4753326": "Esta conexión no puede aprobar comandos. Usa un cliente que pueda usar el terminal." + "fcb5f3c4d4753326": "Esta conexión no puede aprobar comandos. Usa un cliente que pueda usar el terminal.", + "2fc5076786a6b6ed": "Omitir bloques de código", + "b0900f4938210634": "Clave de API", + "6e4d05cd77caff7c": "No se pudo reanudar la lectura.", + "8ed4191b261076ff": "Reproduce una muestra breve con el proveedor de voz seleccionado.", + "951a30714876977f": "Omitir bloques de código al leer", + "26aafec418058787": "En este dispositivo", + "5a640ef031aed4a2": "Voz de lectura en voz alta", + "3fb69cb2e760f23d": "Modelo de voz", + "81923647f1ef9740": "Cancelar la generación de voz", + "60609aae479dd41c": "No se pudo descargar el modelo. Comprueba la conexión y el espacio en disco del entorno.", + "c10f66d628754b10": "Velocidad", + "09a3f02127015c7d": "No se pudo leer en voz alta", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "No se encontró ningún archivo de modelo de voz en esa ruta.", + "944dfe57d9653d32": "Este entorno no tiene una clave de API de {company}. Añade una con el botón de la llave.", + "e3c3d4bcfa9727b9": "Reanudar lectura", + "09bc28a37e6caf92": "Se descarga una vez en el entorno seleccionado, que lee las respuestas sin que el texto salga de él.", + "0097b134ae6e9d9c": "Gestionar la clave de lectura en voz alta", + "44e370c9cc900c63": "Modelo de lectura en voz alta", + "6e58953ca9c7fad5": "Cualquiera con acceso a {environment} puede cargar costes a esta clave.", + "f7323911c24ed501": "Predeterminada", + "c2be8693c77597a3": "Descarga de {size}.", + "eae80365006fbe17": "Si se deja vacío, se usa la voz predeterminada del proveedor.", + "b02cc7b7adaa2361": "No se pudo leer esta respuesta.", + "0dde517387ea2d57": "Detener la vista previa", + "ee6859d2ad7f5842": "Proveedor de lectura en voz alta", + "0fed42221c860bd6": "Lee la prosa y los identificadores en línea sin narrar los bloques de código.", + "88f2bec553b72827": "Reproducir vista previa", + "d33ab3b324ba0b36": "Modelos de lectura en voz alta", + "2d2ee6c94580e79f": "Elige un modelo de voz del catálogo del proveedor.", + "bfbaa4965c146e7c": "Todas las personas que usan {company} para dictado o lectura en voz alta en {environment} perderán el acceso.", + "bff81cb00fc73544": "Velocidad de reproducción.", + "6793112a0a873441": "Gestionar clave", + "b9c9fc9b61d7243e": "Voz predeterminada", + "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.", + "936895b764543aea": "Velocidad de lectura en voz alta", + "4b009ef01c76df8e": "Esto es T3 Code. La respuesta de tu agente está lista para leerse en voz alta.", + "09f85302ef58020c": "Actualizar la clave mantiene activada la lectura en voz alta.", + "bec2c35646e0496a": "Vista previa", + "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.", + "3985d8550c7bc219": "tts texto a voz hablar leer en voz alta voz reproducción OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "Voz", + "17076b27f1f3ada5": "Desactivado", + "154bec57dbece73c": "Dejar de leer", + "65a238ad6bebf802": "¿Leer las respuestas en voz alta con {name}?", + "293d67c7b56e7b69": "Proveedor de voz", + "7bc4af4101c8997b": "{environment} no tiene una clave de API de {company}. Añade una con el botón de la llave.", + "b4b7580d21c53b5f": "No se pudieron cargar los modelos de voz. Comprueba el entorno seleccionado y la configuración del proveedor.", + "52e8f8accdca2d32": "Voces del sistema", + "0eceb5780908eb6c": "Leer en voz alta", + "cf0740520675dcb9": [ + "Conéctate a ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " para continuar." + ], + "1405f6ff92c1041a": "No se pudo cambiar el modelo. Inténtalo de nuevo." } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index eb31951f011ef..0805cfa551fe5 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12870,5 +12870,65 @@ "f6a91589456cca50": "Approuvée", "c92657bb7f2293ff": "Approbation requise", "f1e5c1be1ac92361": "Approuver", - "fcb5f3c4d4753326": "Cette connexion ne peut pas approuver de commandes. Utilisez un client qui peut utiliser le terminal." + "fcb5f3c4d4753326": "Cette connexion ne peut pas approuver de commandes. Utilisez un client qui peut utiliser le terminal.", + "2fc5076786a6b6ed": "Ignorer les blocs de code", + "b0900f4938210634": "Clé d’API", + "6e4d05cd77caff7c": "Impossible de reprendre la lecture.", + "8ed4191b261076ff": "Lit un court extrait avec le fournisseur vocal sélectionné.", + "951a30714876977f": "Ignorer les blocs de code pendant la lecture", + "26aafec418058787": "Sur cet appareil", + "5a640ef031aed4a2": "Voix de lecture à voix haute", + "3fb69cb2e760f23d": "Modèle vocal", + "81923647f1ef9740": "Annuler la génération vocale", + "60609aae479dd41c": "Impossible de télécharger le modèle. Vérifiez la connexion et l’espace disque de l’environnement.", + "c10f66d628754b10": "Vitesse", + "09a3f02127015c7d": "Impossible de lire à voix haute", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "Aucun fichier de modèle vocal n’a été trouvé à cet emplacement.", + "944dfe57d9653d32": "Cet environnement n’a pas de clé d’API {company}. Ajoutez-en une avec le bouton de clé.", + "e3c3d4bcfa9727b9": "Reprendre la lecture", + "09bc28a37e6caf92": "Téléchargé une fois dans l’environnement sélectionné, qui lit les réponses sans que le texte le quitte.", + "0097b134ae6e9d9c": "Gérer la clé de lecture à voix haute", + "44e370c9cc900c63": "Modèle de lecture à voix haute", + "6e58953ca9c7fad5": "Toute personne ayant accès à {environment} peut facturer cette clé.", + "f7323911c24ed501": "Par défaut", + "c2be8693c77597a3": "Téléchargement de {size}.", + "eae80365006fbe17": "Une valeur vide utilise la voix par défaut du fournisseur.", + "b02cc7b7adaa2361": "Impossible de lire cette réponse.", + "0dde517387ea2d57": "Arrêter l’aperçu", + "ee6859d2ad7f5842": "Fournisseur de lecture à voix haute", + "0fed42221c860bd6": "Lit le texte et les identifiants en ligne sans lire les blocs de code.", + "88f2bec553b72827": "Lire l’aperçu", + "d33ab3b324ba0b36": "Modèles de lecture à voix haute", + "2d2ee6c94580e79f": "Choisissez un modèle vocal dans le catalogue du fournisseur.", + "bfbaa4965c146e7c": "Toutes les personnes qui utilisent {company} pour la dictée ou la lecture à voix haute sur {environment} perdront l’accès.", + "bff81cb00fc73544": "Vitesse de lecture.", + "6793112a0a873441": "Gérer la clé", + "b9c9fc9b61d7243e": "Voix par défaut", + "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.", + "936895b764543aea": "Vitesse de lecture à voix haute", + "4b009ef01c76df8e": "Voici T3 Code. La réponse de votre agent est prête à être lue à voix haute.", + "09f85302ef58020c": "La mise à jour de la clé garde la lecture à voix haute activée.", + "bec2c35646e0496a": "Aperçu", + "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.", + "3985d8550c7bc219": "tts synthèse vocale parler lecture à voix haute voix lecture OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "Voix", + "17076b27f1f3ada5": "Désactivé", + "154bec57dbece73c": "Arrêter la lecture", + "65a238ad6bebf802": "Lire les réponses à voix haute avec {name} ?", + "293d67c7b56e7b69": "Fournisseur vocal", + "7bc4af4101c8997b": "{environment} n’a pas de clé d’API {company}. Ajoutez-en une avec le bouton de clé.", + "b4b7580d21c53b5f": "Impossible de charger les modèles vocaux. Vérifiez l’environnement sélectionné et la configuration du fournisseur.", + "52e8f8accdca2d32": "Voix du système", + "0eceb5780908eb6c": "Lecture à voix haute", + "cf0740520675dcb9": [ + "Connectez-vous à ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " pour continuer." + ], + "1405f6ff92c1041a": "Impossible de modifier le modèle. Réessayez." } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 9b2b896206856..9407265fd9409 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12811,5 +12811,65 @@ "f6a91589456cca50": "承認済み", "c92657bb7f2293ff": "承認が必要", "f1e5c1be1ac92361": "承認", - "fcb5f3c4d4753326": "この接続ではコマンドを承認できません。ターミナルを使用できるクライアントを使ってください。" + "fcb5f3c4d4753326": "この接続ではコマンドを承認できません。ターミナルを使用できるクライアントを使ってください。", + "2fc5076786a6b6ed": "コードブロックをスキップ", + "b0900f4938210634": "API キー", + "6e4d05cd77caff7c": "読み上げを再開できませんでした。", + "8ed4191b261076ff": "選択した音声プロバイダーで短いサンプルを再生します。", + "951a30714876977f": "読み上げ時にコードブロックをスキップ", + "26aafec418058787": "このデバイス上", + "5a640ef031aed4a2": "読み上げの音声", + "3fb69cb2e760f23d": "音声モデル", + "81923647f1ef9740": "音声の生成をキャンセル", + "60609aae479dd41c": "モデルをダウンロードできませんでした。環境の接続とディスク容量を確認してください。", + "c10f66d628754b10": "速度", + "09a3f02127015c7d": "読み上げできませんでした", + "d5b9ecbc5062b6a7": "{size}。", + "69a7c539add37d29": "そのパスに音声モデルのファイルが見つかりませんでした。", + "944dfe57d9653d32": "この環境には {company} の API キーがありません。キーボタンから追加してください。", + "e3c3d4bcfa9727b9": "読み上げを再開", + "09bc28a37e6caf92": "選択した環境に一度だけダウンロードされ、テキストを外部に出さずに返信を読み上げます。", + "0097b134ae6e9d9c": "読み上げ用キーを管理", + "44e370c9cc900c63": "読み上げモデル", + "6e58953ca9c7fad5": "{environment} にアクセスできるユーザーは誰でも、このキーに課金できます。", + "f7323911c24ed501": "既定", + "c2be8693c77597a3": "ダウンロードサイズ {size}。", + "eae80365006fbe17": "空欄の場合はプロバイダーの既定の音声を使います。", + "b02cc7b7adaa2361": "この応答を読み上げられませんでした。", + "0dde517387ea2d57": "プレビューを停止", + "ee6859d2ad7f5842": "読み上げプロバイダー", + "0fed42221c860bd6": "本文とインラインの識別子を読み上げ、コードブロックは読み上げません。", + "88f2bec553b72827": "プレビューを再生", + "d33ab3b324ba0b36": "読み上げモデル", + "2d2ee6c94580e79f": "プロバイダーのカタログから音声モデルを選択します。", + "bfbaa4965c146e7c": "{environment} で音声入力または読み上げに {company} を使っているすべてのユーザーがアクセスできなくなります。", + "bff81cb00fc73544": "再生速度。", + "6793112a0a873441": "キーを管理", + "b9c9fc9b61d7243e": "既定の音声", + "1c3796a6ec44558f": "完了した返信は、コピーの横にある再生ボタンで読み上げます。ホスト型プロバイダーは選択した環境を通じて応答テキストを受け取り、ローカルモデルはその環境で実行されます。", + "936895b764543aea": "読み上げ速度", + "4b009ef01c76df8e": "T3 Code です。エージェントの応答を読み上げる準備ができました。", + "09f85302ef58020c": "キーを更新しても読み上げはオンのままです。", + "bec2c35646e0496a": "プレビュー", + "b9e06e668bd9bff0": "再生する返信は {environment} を通じて {company} に送信され、その API キーに課金されます。このキーは音声入力と共有されます。", + "3985d8550c7bc219": "tts 音声合成 読み上げ 音声 再生 OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "音声", + "17076b27f1f3ada5": "オフ", + "154bec57dbece73c": "読み上げを停止", + "65a238ad6bebf802": "{name} で返信を読み上げますか?", + "293d67c7b56e7b69": "音声プロバイダー", + "7bc4af4101c8997b": "{environment} には {company} の API キーがありません。キーボタンから追加してください。", + "b4b7580d21c53b5f": "音声モデルを読み込めませんでした。選択した環境とプロバイダーの設定を確認してください。", + "52e8f8accdca2d32": "システムの音声", + "0eceb5780908eb6c": "読み上げ", + "cf0740520675dcb9": [ + "続行するには ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " に接続してください。" + ], + "1405f6ff92c1041a": "モデルを変更できませんでした。もう一度お試しください。" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 0960dbaf5549c..c0d1e45f14479 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12807,5 +12807,65 @@ "f6a91589456cca50": "승인됨", "c92657bb7f2293ff": "승인 필요", "f1e5c1be1ac92361": "승인", - "fcb5f3c4d4753326": "이 연결에서는 명령을 승인할 수 없습니다. 터미널을 사용할 수 있는 클라이언트를 사용하세요." + "fcb5f3c4d4753326": "이 연결에서는 명령을 승인할 수 없습니다. 터미널을 사용할 수 있는 클라이언트를 사용하세요.", + "2fc5076786a6b6ed": "코드 블록 건너뛰기", + "b0900f4938210634": "API 키", + "6e4d05cd77caff7c": "읽기를 다시 시작할 수 없습니다.", + "8ed4191b261076ff": "선택한 음성 제공자로 짧은 샘플을 재생합니다.", + "951a30714876977f": "읽을 때 코드 블록 건너뛰기", + "26aafec418058787": "이 기기에서", + "5a640ef031aed4a2": "소리 내어 읽기 음성", + "3fb69cb2e760f23d": "음성 모델", + "81923647f1ef9740": "음성 생성 취소", + "60609aae479dd41c": "모델을 다운로드할 수 없습니다. 환경의 연결 상태와 디스크 공간을 확인하세요.", + "c10f66d628754b10": "속도", + "09a3f02127015c7d": "소리 내어 읽을 수 없음", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "해당 경로에서 음성 모델 파일을 찾을 수 없습니다.", + "944dfe57d9653d32": "이 환경에 {company} API 키가 없습니다. 키 버튼으로 추가하세요.", + "e3c3d4bcfa9727b9": "읽기 다시 시작", + "09bc28a37e6caf92": "선택한 환경에 한 번 다운로드되며, 텍스트가 환경 밖으로 나가지 않고 답변을 읽습니다.", + "0097b134ae6e9d9c": "소리 내어 읽기 키 관리", + "44e370c9cc900c63": "소리 내어 읽기 모델", + "6e58953ca9c7fad5": "{environment}에 액세스할 수 있는 사람은 누구나 이 키로 요금을 발생시킬 수 있습니다.", + "f7323911c24ed501": "기본값", + "c2be8693c77597a3": "{size} 다운로드.", + "eae80365006fbe17": "비워 두면 제공자의 기본 음성을 사용합니다.", + "b02cc7b7adaa2361": "이 응답을 읽을 수 없습니다.", + "0dde517387ea2d57": "미리 듣기 중지", + "ee6859d2ad7f5842": "소리 내어 읽기 제공자", + "0fed42221c860bd6": "본문과 인라인 식별자는 읽고 코드 블록은 읽지 않습니다.", + "88f2bec553b72827": "미리 듣기 재생", + "d33ab3b324ba0b36": "소리 내어 읽기 모델", + "2d2ee6c94580e79f": "제공자 카탈로그에서 음성 모델을 선택하세요.", + "bfbaa4965c146e7c": "{environment}에서 받아쓰기나 소리 내어 읽기에 {company}을(를) 사용하는 모든 사람이 액세스 권한을 잃습니다.", + "bff81cb00fc73544": "재생 속도입니다.", + "6793112a0a873441": "키 관리", + "b9c9fc9b61d7243e": "기본 음성", + "1c3796a6ec44558f": "완료된 답변은 복사 옆의 재생 버튼으로 읽습니다. 호스팅 제공자는 선택한 환경을 통해 응답 텍스트를 받고, 로컬 모델은 해당 환경에서 실행됩니다.", + "936895b764543aea": "소리 내어 읽기 속도", + "4b009ef01c76df8e": "T3 Code입니다. 에이전트의 응답을 소리 내어 읽을 준비가 되었습니다.", + "09f85302ef58020c": "키를 업데이트해도 소리 내어 읽기는 계속 켜져 있습니다.", + "bec2c35646e0496a": "미리 듣기", + "b9e06e668bd9bff0": "재생하는 답변은 {environment}을(를) 통해 {company}(으)로 전송되며 해당 API 키로 요금이 청구됩니다. 이 키는 받아쓰기와 공유됩니다.", + "3985d8550c7bc219": "tts 텍스트 음성 변환 소리 내어 읽기 음성 재생 OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "음성", + "17076b27f1f3ada5": "끄기", + "154bec57dbece73c": "읽기 중지", + "65a238ad6bebf802": "{name}(으)로 답변을 소리 내어 읽을까요?", + "293d67c7b56e7b69": "음성 제공자", + "7bc4af4101c8997b": "{environment}에 {company} API 키가 없습니다. 키 버튼으로 추가하세요.", + "b4b7580d21c53b5f": "음성 모델을 불러올 수 없습니다. 선택한 환경과 제공자 구성을 확인하세요.", + "52e8f8accdca2d32": "시스템 음성", + "0eceb5780908eb6c": "소리 내어 읽기", + "cf0740520675dcb9": [ + "계속하려면 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "에 연결하세요." + ], + "1405f6ff92c1041a": "모델을 변경할 수 없습니다. 다시 시도하세요." } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 62a1343f38c16..287578c78a91c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12870,5 +12870,65 @@ "f6a91589456cca50": "Aprovado", "c92657bb7f2293ff": "Precisa de aprovação", "f1e5c1be1ac92361": "Aprovar", - "fcb5f3c4d4753326": "Esta conexão não pode aprovar comandos. Use um cliente que possa usar o terminal." + "fcb5f3c4d4753326": "Esta conexão não pode aprovar comandos. Use um cliente que possa usar o terminal.", + "2fc5076786a6b6ed": "Pular blocos de código", + "b0900f4938210634": "Chave de API", + "6e4d05cd77caff7c": "Não foi possível retomar a leitura.", + "8ed4191b261076ff": "Reproduz uma amostra curta com o provedor de voz selecionado.", + "951a30714876977f": "Pular blocos de código ao ler", + "26aafec418058787": "Neste dispositivo", + "5a640ef031aed4a2": "Voz de leitura em voz alta", + "3fb69cb2e760f23d": "Modelo de voz", + "81923647f1ef9740": "Cancelar geração de voz", + "60609aae479dd41c": "Não foi possível baixar o modelo. Verifique a conexão e o espaço em disco do ambiente.", + "c10f66d628754b10": "Velocidade", + "09a3f02127015c7d": "Não foi possível ler em voz alta", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "Nenhum arquivo de modelo de voz foi encontrado nesse caminho.", + "944dfe57d9653d32": "Este ambiente não tem uma chave de API da {company}. Adicione uma com o botão de chave.", + "e3c3d4bcfa9727b9": "Retomar leitura", + "09bc28a37e6caf92": "Baixado uma vez no ambiente selecionado, que lê as respostas sem que o texto saia dele.", + "0097b134ae6e9d9c": "Gerenciar chave de leitura em voz alta", + "44e370c9cc900c63": "Modelo de leitura em voz alta", + "6e58953ca9c7fad5": "Qualquer pessoa com acesso a {environment} pode gerar cobranças nesta chave.", + "f7323911c24ed501": "Padrão", + "c2be8693c77597a3": "Download de {size}.", + "eae80365006fbe17": "Um valor vazio usa a voz padrão do provedor.", + "b02cc7b7adaa2361": "Não foi possível ler esta resposta.", + "0dde517387ea2d57": "Parar prévia", + "ee6859d2ad7f5842": "Provedor de leitura em voz alta", + "0fed42221c860bd6": "Lê o texto e os identificadores em linha sem narrar os blocos de código.", + "88f2bec553b72827": "Reproduzir prévia", + "d33ab3b324ba0b36": "Modelos de leitura em voz alta", + "2d2ee6c94580e79f": "Escolha um modelo de voz do catálogo do provedor.", + "bfbaa4965c146e7c": "Todos que usam {company} para ditado ou leitura em voz alta em {environment} perderão o acesso.", + "bff81cb00fc73544": "Velocidade de reprodução.", + "6793112a0a873441": "Gerenciar chave", + "b9c9fc9b61d7243e": "Voz padrão", + "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.", + "936895b764543aea": "Velocidade de leitura em voz alta", + "4b009ef01c76df8e": "Este é o T3 Code. A resposta do seu agente está pronta para ser lida em voz alta.", + "09f85302ef58020c": "Atualizar a chave mantém a leitura em voz alta ativada.", + "bec2c35646e0496a": "Prévia", + "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.", + "3985d8550c7bc219": "tts texto para fala ler em voz alta voz reprodução OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "Voz", + "17076b27f1f3ada5": "Desativado", + "154bec57dbece73c": "Parar leitura", + "65a238ad6bebf802": "Ler respostas em voz alta com {name}?", + "293d67c7b56e7b69": "Provedor de voz", + "7bc4af4101c8997b": "{environment} não tem uma chave de API da {company}. Adicione uma com o botão de chave.", + "b4b7580d21c53b5f": "Não foi possível carregar os modelos de voz. Verifique o ambiente selecionado e a configuração do provedor.", + "52e8f8accdca2d32": "Vozes do sistema", + "0eceb5780908eb6c": "Ler em voz alta", + "cf0740520675dcb9": [ + "Conecte-se a ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " para continuar." + ], + "1405f6ff92c1041a": "Não foi possível alterar o modelo. Tente novamente." } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 65a775122b675..17e80faa7d6ef 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12870,5 +12870,65 @@ "f6a91589456cca50": "Подтверждена", "c92657bb7f2293ff": "Нужно подтверждение", "f1e5c1be1ac92361": "Подтвердить", - "fcb5f3c4d4753326": "Это подключение не может подтверждать команды. Используйте клиент, которому доступен терминал." + "fcb5f3c4d4753326": "Это подключение не может подтверждать команды. Используйте клиент, которому доступен терминал.", + "2fc5076786a6b6ed": "Пропускать блоки кода", + "b0900f4938210634": "API-ключ", + "6e4d05cd77caff7c": "Не удалось возобновить чтение.", + "8ed4191b261076ff": "Воспроизводит короткий пример с выбранным провайдером речи.", + "951a30714876977f": "Пропускать блоки кода при чтении", + "26aafec418058787": "На этом устройстве", + "5a640ef031aed4a2": "Голос для чтения вслух", + "3fb69cb2e760f23d": "Речевая модель", + "81923647f1ef9740": "Отменить синтез речи", + "60609aae479dd41c": "Не удалось скачать модель. Проверьте подключение и свободное место в окружении.", + "c10f66d628754b10": "Скорость", + "09a3f02127015c7d": "Не удалось прочитать вслух", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "По этому пути не найден файл речевой модели.", + "944dfe57d9653d32": "У этого окружения нет API-ключа {company}. Добавьте его кнопкой с ключом.", + "e3c3d4bcfa9727b9": "Продолжить чтение", + "09bc28a37e6caf92": "Скачивается один раз в выбранное окружение, которое читает ответы, не передавая текст наружу.", + "0097b134ae6e9d9c": "Управлять ключом для чтения вслух", + "44e370c9cc900c63": "Модель чтения вслух", + "6e58953ca9c7fad5": "Любой, у кого есть доступ к {environment}, может тратить средства по этому ключу.", + "f7323911c24ed501": "По умолчанию", + "c2be8693c77597a3": "Загрузка {size}.", + "eae80365006fbe17": "Пустое значение означает голос провайдера по умолчанию.", + "b02cc7b7adaa2361": "Не удалось прочитать этот ответ.", + "0dde517387ea2d57": "Остановить пример", + "ee6859d2ad7f5842": "Провайдер чтения вслух", + "0fed42221c860bd6": "Читает текст и встроенные идентификаторы, не озвучивая блоки кода.", + "88f2bec553b72827": "Воспроизвести пример", + "d33ab3b324ba0b36": "Модели чтения вслух", + "2d2ee6c94580e79f": "Выберите речевую модель из каталога провайдера.", + "bfbaa4965c146e7c": "Все, кто использует {company} для диктовки или чтения вслух в {environment}, потеряют доступ.", + "bff81cb00fc73544": "Скорость воспроизведения.", + "6793112a0a873441": "Управлять ключом", + "b9c9fc9b61d7243e": "Голос по умолчанию", + "1c3796a6ec44558f": "Читайте готовые ответы кнопкой воспроизведения рядом с «Копировать». Облачные провайдеры получают текст через выбранное окружение; локальная модель работает на нём.", + "936895b764543aea": "Скорость чтения вслух", + "4b009ef01c76df8e": "Это T3 Code. Ответ вашего агента готов к чтению вслух.", + "09f85302ef58020c": "При обновлении ключа чтение вслух остаётся включённым.", + "bec2c35646e0496a": "Пример", + "b9e06e668bd9bff0": "Воспроизводимые ответы отправляются в {company} через {environment}, оплата идёт по его API-ключу. Ключ общий с диктовкой.", + "3985d8550c7bc219": "tts синтез речи озвучка чтение вслух голос воспроизведение OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "Голос", + "17076b27f1f3ada5": "Выкл.", + "154bec57dbece73c": "Остановить чтение", + "65a238ad6bebf802": "Читать ответы вслух с помощью {name}?", + "293d67c7b56e7b69": "Провайдер речи", + "7bc4af4101c8997b": "У {environment} нет API-ключа {company}. Добавьте его кнопкой с ключом.", + "b4b7580d21c53b5f": "Не удалось загрузить речевые модели. Проверьте выбранное окружение и настройки провайдера.", + "52e8f8accdca2d32": "Системные голоса", + "0eceb5780908eb6c": "Чтение вслух", + "cf0740520675dcb9": [ + "Подключитесь к ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ", чтобы продолжить." + ], + "1405f6ff92c1041a": "Не удалось изменить модель. Попробуйте ещё раз." } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index ade74af462e87..39fba485befb1 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12877,5 +12877,65 @@ "f6a91589456cca50": "Godkänt", "c92657bb7f2293ff": "Behöver godkännande", "f1e5c1be1ac92361": "Godkänn", - "fcb5f3c4d4753326": "Den här anslutningen kan inte godkänna kommandon. Använd en klient som får använda terminalen." + "fcb5f3c4d4753326": "Den här anslutningen kan inte godkänna kommandon. Använd en klient som får använda terminalen.", + "2fc5076786a6b6ed": "Hoppa över kodblock", + "b0900f4938210634": "API-nyckel", + "6e4d05cd77caff7c": "Det gick inte att återuppta uppläsningen.", + "8ed4191b261076ff": "Spelar upp ett kort exempel med den valda talleverantören.", + "951a30714876977f": "Hoppa över kodblock vid uppläsning", + "26aafec418058787": "På den här enheten", + "5a640ef031aed4a2": "Uppläsningsröst", + "3fb69cb2e760f23d": "Talmodell", + "81923647f1ef9740": "Avbryt talgenereringen", + "60609aae479dd41c": "Det gick inte att ladda ned modellen. Kontrollera miljöns anslutning och diskutrymme.", + "c10f66d628754b10": "Hastighet", + "09a3f02127015c7d": "Det gick inte att läsa upp", + "d5b9ecbc5062b6a7": "{size}.", + "69a7c539add37d29": "Ingen talmodellfil hittades på den sökvägen.", + "944dfe57d9653d32": "Den här miljön har ingen API-nyckel för {company}. Lägg till en med nyckelknappen.", + "e3c3d4bcfa9727b9": "Fortsätt läsa upp", + "09bc28a37e6caf92": "Laddas ned en gång till den valda miljön, som läser upp svar utan att texten lämnar den.", + "0097b134ae6e9d9c": "Hantera uppläsningsnyckel", + "44e370c9cc900c63": "Uppläsningsmodell", + "6e58953ca9c7fad5": "Alla med åtkomst till {environment} kan debitera den här nyckeln.", + "f7323911c24ed501": "Standard", + "c2be8693c77597a3": "{size} att ladda ned.", + "eae80365006fbe17": "Ett tomt värde använder leverantörens standardröst.", + "b02cc7b7adaa2361": "Det gick inte att läsa upp det här svaret.", + "0dde517387ea2d57": "Stoppa förhandsvisningen", + "ee6859d2ad7f5842": "Uppläsningsleverantör", + "0fed42221c860bd6": "Läser upp text och inbäddade identifierare utan att läsa upp kodblock.", + "88f2bec553b72827": "Spela upp förhandsvisning", + "d33ab3b324ba0b36": "Uppläsningsmodeller", + "2d2ee6c94580e79f": "Välj en talmodell från leverantörens katalog.", + "bfbaa4965c146e7c": "Alla som använder {company} för diktering eller uppläsning på {environment} förlorar åtkomsten.", + "bff81cb00fc73544": "Uppspelningshastighet.", + "6793112a0a873441": "Hantera nyckel", + "b9c9fc9b61d7243e": "Standardröst", + "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.", + "936895b764543aea": "Uppläsningshastighet", + "4b009ef01c76df8e": "Det här är T3 Code. Agentens svar är redo att läsas upp.", + "09f85302ef58020c": "Uppläsningen förblir på när du uppdaterar nyckeln.", + "bec2c35646e0496a": "Förhandsvisning", + "b9e06e668bd9bff0": "Svar som du spelar upp skickas till {company} via {environment}, som debiterar sin API-nyckel. Nyckeln delas med dikteringen.", + "3985d8550c7bc219": "tts text till tal uppläsning läs upp röst uppspelning OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "Röst", + "17076b27f1f3ada5": "Av", + "154bec57dbece73c": "Sluta läsa upp", + "65a238ad6bebf802": "Läsa upp svar med {name}?", + "293d67c7b56e7b69": "Talleverantör", + "7bc4af4101c8997b": "{environment} har ingen API-nyckel för {company}. Lägg till en med nyckelknappen.", + "b4b7580d21c53b5f": "Det gick inte att läsa in talmodeller. Kontrollera den valda miljön och leverantörens konfiguration.", + "52e8f8accdca2d32": "Systemröster", + "0eceb5780908eb6c": "Läs upp", + "cf0740520675dcb9": [ + "Anslut till ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " för att fortsätta." + ], + "1405f6ff92c1041a": "Det gick inte att ändra modellen. Försök igen." } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index f1b529ec39ff6..61b97363ecb37 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12889,5 +12889,65 @@ "f6a91589456cca50": "已批准", "c92657bb7f2293ff": "待批准", "f1e5c1be1ac92361": "批准", - "fcb5f3c4d4753326": "此连接无法批准命令。请使用可以使用终端的客户端。" + "fcb5f3c4d4753326": "此连接无法批准命令。请使用可以使用终端的客户端。", + "2fc5076786a6b6ed": "跳过代码块", + "b0900f4938210634": "API 密钥", + "6e4d05cd77caff7c": "无法继续朗读。", + "8ed4191b261076ff": "使用所选语音提供商播放一段简短示例。", + "951a30714876977f": "朗读时跳过代码块", + "26aafec418058787": "在此设备上", + "5a640ef031aed4a2": "朗读声音", + "3fb69cb2e760f23d": "语音模型", + "81923647f1ef9740": "取消语音生成", + "60609aae479dd41c": "无法下载模型。请检查环境的连接和磁盘空间。", + "c10f66d628754b10": "语速", + "09a3f02127015c7d": "无法朗读", + "d5b9ecbc5062b6a7": "{size}。", + "69a7c539add37d29": "在该路径下未找到语音模型文件。", + "944dfe57d9653d32": "此环境没有 {company} API 密钥。请使用密钥按钮添加。", + "e3c3d4bcfa9727b9": "继续朗读", + "09bc28a37e6caf92": "只需下载一次到所选环境,朗读回复时文本不会离开该环境。", + "0097b134ae6e9d9c": "管理朗读密钥", + "44e370c9cc900c63": "朗读模型", + "6e58953ca9c7fad5": "有权访问 {environment} 的人都可以使用此密钥产生费用。", + "f7323911c24ed501": "默认", + "c2be8693c77597a3": "下载大小 {size}。", + "eae80365006fbe17": "留空则使用提供商的默认声音。", + "b02cc7b7adaa2361": "无法朗读此回复。", + "0dde517387ea2d57": "停止试听", + "ee6859d2ad7f5842": "朗读提供商", + "0fed42221c860bd6": "朗读正文和行内标识符,不朗读代码块。", + "88f2bec553b72827": "播放试听", + "d33ab3b324ba0b36": "朗读模型", + "2d2ee6c94580e79f": "从提供商目录中选择语音模型。", + "bfbaa4965c146e7c": "在 {environment} 上使用 {company} 进行听写或朗读的所有人都将失去访问权限。", + "bff81cb00fc73544": "播放速度。", + "6793112a0a873441": "管理密钥", + "b9c9fc9b61d7243e": "默认声音", + "1c3796a6ec44558f": "使用“复制”旁边的播放按钮朗读已完成的回复。托管提供商会通过所选环境接收回复文本;本地模型在该环境上运行。", + "936895b764543aea": "朗读语速", + "4b009ef01c76df8e": "这里是 T3 Code。你的代理回复已可以朗读。", + "09f85302ef58020c": "更新密钥后朗读仍保持开启。", + "bec2c35646e0496a": "试听", + "b9e06e668bd9bff0": "你播放的回复会通过 {environment} 发送到 {company},费用计入其 API 密钥。该密钥与听写共用。", + "3985d8550c7bc219": "tts 文字转语音 朗读 语音 播放 OpenAI Grok OpenRouter ElevenLabs", + "9fa6e93a8218ad60": "声音", + "17076b27f1f3ada5": "关闭", + "154bec57dbece73c": "停止朗读", + "65a238ad6bebf802": "使用 {name} 朗读回复?", + "293d67c7b56e7b69": "语音提供商", + "7bc4af4101c8997b": "{environment} 没有 {company} API 密钥。请使用密钥按钮添加。", + "b4b7580d21c53b5f": "无法加载语音模型。请检查所选环境和提供商配置。", + "52e8f8accdca2d32": "系统语音", + "0eceb5780908eb6c": "朗读", + "cf0740520675dcb9": [ + "连接到 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 以继续。" + ], + "1405f6ff92c1041a": "无法更改模型。请重试。" } diff --git a/apps/web/src/speech/readAloud.ts b/apps/web/src/speech/readAloud.ts new file mode 100644 index 0000000000000..abc83c8199cb1 --- /dev/null +++ b/apps/web/src/speech/readAloud.ts @@ -0,0 +1,112 @@ +import { m } from "~/i18n/messages"; +import { speechSpeedAppliedByProvider, type SpeechSynthesisCatalog } from "@t3tools/contracts"; +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"; +import { runEnvironmentSpeech } from "./runEnvironmentSpeech"; + +function systemPlayback( + text: string, + voice: string, + speed: number, + language: string, +): SpeechPlayback { + if (!("speechSynthesis" in window)) + throw new Error("System voices are not available in this browser."); + const utterance = new SpeechSynthesisUtterance(text); + utterance.rate = speed; + if (language !== "auto") utterance.lang = language; + 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, + }; +} + +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); + 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."); + let pendingCatalog = catalogs.get(signal); + if (!pendingCatalog) { + pendingCatalog = runEnvironmentSpeech(getSpeechSynthesisModels(prepared, settings.provider), { + signal, + }); + catalogs.set(signal, pendingCatalog); + } + const catalog = await pendingCatalog; + signal.throwIfAborted(); + if (catalog.error) throw new Error(catalog.error); + const model = settings.model || catalog.defaultModel; + const url = await runEnvironmentSpeech( + startSpeechSynthesis(prepared, settings.provider, { + text, + model, + voice: settings.voice, + speed: settings.speed, + language: settings.language, + }), + { signal }, + ); + signal.throwIfAborted(); + const audio = new Audio(url); + if (!speechSpeedAppliedByProvider(catalog, model)) 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(); + done(); + }, + finished, + }; +}, m); diff --git a/docs/user/composer.md b/docs/user/composer.md index 53017052a2a01..4d1503d526575 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -216,6 +216,27 @@ 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. OpenAI, Grok TTS, OpenRouter, and ElevenLabs 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. + +**Local model** reads replies on your selected environment, so the text never leaves it. +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. + +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/docs/user/voice-input.md b/docs/user/voice-input.md index 9831eeafd49f8..d84b75d385a6b 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -31,8 +31,8 @@ recording in a language can take longer while macOS downloads its speech model. filler-word removal are not available; the dictionary applies only when transcript cleanup is on. -For cloud dictation, choose **OpenAI** or **Grok Voice Transcribe** via the environment -you want to use. If it needs a key, enter one and choose **Save and enable**. +For cloud dictation, choose **OpenAI**, **Grok Voice Transcribe**, or **ElevenLabs** via the +environment you want to use. If it needs a key, enter one and choose **Save and enable**. You can also choose a [secret provider](secrets.md) instead of **Value** and enter a reference. Unlock the vault on that environment before dictating. Anyone with dictation access to the environment can use the key, but only this device opts in. diff --git a/knip.jsonc b/knip.jsonc index 6f2a40fe94473..be374b8a3e6b3 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -78,6 +78,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..5e7494a59b298 --- /dev/null +++ b/packages/audio-cpp/package.json @@ -0,0 +1,18 @@ +{ + "name": "@t3tools/audio-cpp", + "private": true, + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "import": "./src/index.ts" + } + }, + "scripts": { + "typecheck": "effect-tsgo tsrs --noEmit" + }, + "devDependencies": { + "@types/node": "catalog:", + "koffi": "3.3.6" + } +} diff --git a/packages/audio-cpp/src/bindings.ts b/packages/audio-cpp/src/bindings.ts new file mode 100644 index 0000000000000..421facee35534 --- /dev/null +++ b/packages/audio-cpp/src/bindings.ts @@ -0,0 +1,248 @@ +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]), + 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", + 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 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( + 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]; + // 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..a02ca0aff2862 --- /dev/null +++ b/packages/audio-cpp/src/index.ts @@ -0,0 +1,13 @@ +export { + bindAudioCpp, + type AudioCppAudio, + type AudioCppLibrary, + type AudioCppModel, + type AudioCppSynthesisRequest, +} from "./bindings.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 new file mode 100644 index 0000000000000..281a5bc1f6b90 --- /dev/null +++ b/packages/audio-cpp/src/runtime.ts @@ -0,0 +1,95 @@ +/** A release of github.com/pingdotgg/audio.cpp, whose `T3 release` workflow builds these libraries. */ +export const AUDIO_CPP_VERSION = "t3-2026.11.17"; + +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/pingdotgg/audio.cpp/releases/download/${AUDIO_CPP_VERSION}/${filename}`, + size, + sha256, + library, + backend, + ...(minimumGlibc ? { minimumGlibc } : {}), + }; +}; + +// 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_293_898, + "4f06e1d834e2e7a43fb9f257d561e946196a9e2459a8b4648cf36e24a0e5ac14", + "libs/libaudiocpp.0.1.0.dylib", + "metal", + ), + "darwin-x64": runtime( + "macos-x64-cpu.tar.gz", + 16_460_460, + "02066f1ee9a7cad1a601d65cc6be3349ad570d9b9268c65e17b7cf88b706f10b", + "libs/libaudiocpp.0.1.0.dylib", + "cpu", + ), + "linux-x64": runtime( + "linux-x64-vulkan.tar.gz", + 46_783_748, + "3b6ce18303f203eabc82997a2af14e6052f5aad2ea326e444973200a5fd908ca", + "libs/libaudiocpp.so.0.1.0", + "vulkan", + "2.28", + ), + "linux-arm64": runtime( + "linux-arm64-vulkan.tar.gz", + 40_477_068, + "39c59b4ef06fe1ac8fd49fbdf14d3392515949d719ce1ebda5134a73a5c4fd10", + "libs/libaudiocpp.so.0.1.0", + "vulkan", + "2.28", + ), + "win32-arm64": runtime( + "windows-arm64-vulkan.zip", + 34_757_900, + "2e3692e2eab320d58056e38492d8fa2dc8e0de9699e156d783addae3c789c50c", + "libs/audiocpp.dll", + "vulkan", + ), + "win32-x64": runtime( + "windows-x64-vulkan.zip", + 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}`]; 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/package.json b/packages/client-runtime/package.json index cf6f16f5a6a07..0e692e2eade13 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/providerClients.ts b/packages/client-runtime/src/providerClients.ts index 3759cecbc7c7d..1672bcd0d9f84 100644 --- a/packages/client-runtime/src/providerClients.ts +++ b/packages/client-runtime/src/providerClients.ts @@ -27,6 +27,13 @@ export const openRouterIcon: ProviderIcon = { ], }; +// ElevenLabs' two-bar mark from https://elevenlabs.io/brand. +export const elevenLabsIcon: ProviderIcon = { + viewBox: "0 0 24 24", + fill: { light: "#000000", dark: "#FFFFFF" }, + paths: [{ d: "M7 3h3.5v18H7zM13.5 3H17v18h-3.5z" }], +}; + export const providerClients = makeProviderClientRegistry([ { driverKind: ProviderDriverKind.make("codex"), diff --git a/packages/client-runtime/src/readAloud.test.ts b/packages/client-runtime/src/readAloud.test.ts new file mode 100644 index 0000000000000..a4d7808a2ea32 --- /dev/null +++ b/packages/client-runtime/src/readAloud.test.ts @@ -0,0 +1,237 @@ +import { expect, it, vi } from "vite-plus/test"; +import { DEFAULT_READ_ALOUD_SETTINGS, EnvironmentId } from "@t3tools/contracts"; +import { + createReadAloudController, + createReadAloudWarmup, + 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"); +}); + +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; +}); + +it("does not treat chunk disposal as a pause", async () => { + const started = deferred(); + const finished = deferred(); + const nextPrepared = deferred(); + let controller: ReturnType; + const prepare = vi.fn(async () => { + if (prepare.mock.calls.length > 1) nextPrepared.resolve(); + return { + play: async () => started.resolve(), + pause: () => {}, + stop: () => controller.pause(), + finished: finished.promise, + }; + }); + controller = createReadAloudController(prepare); + const run = controller.start("1", "word ".repeat(1000), { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + }); + await started.promise; + finished.resolve(); + await nextPrepared.promise; + expect(controller.getSnapshot().status).toBe("loading"); + controller.stop(); + await run; + expect(controller.getSnapshot().status).toBe("idle"); +}); + +it("keeps a new pause while resume activates playback", async () => { + const playing = deferred(); + const resuming = deferred(); + const activated = deferred(); + const finished = deferred(); + const play = vi.fn(async () => { + if (play.mock.calls.length === 1) return; + else { + resuming.resolve(); + await activated.promise; + } + }); + const controller = createReadAloudController(async () => ({ + play, + pause: () => {}, + stop: () => finished.resolve(), + finished: finished.promise, + })); + const unsubscribe = controller.subscribe(() => { + if (controller.getSnapshot().status === "playing") playing.resolve(); + }); + const run = controller.start("resume", "reply", { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "system", + }); + await playing.promise; + controller.pause(); + const resume = controller.resume(); + await resuming.promise; + try { + expect(controller.getSnapshot().status).toBe("loading"); + controller.pause(); + activated.resolve(); + await resume; + expect(controller.getSnapshot().status).toBe("paused"); + } finally { + activated.resolve(); + controller.stop(); + await resume; + await run; + 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 new file mode 100644 index 0000000000000..2289c98038601 --- /dev/null +++ b/packages/client-runtime/src/readAloud.ts @@ -0,0 +1,190 @@ +import { + SPEECH_SYNTHESIS_MAX_TEXT, + type EnvironmentId, + 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; + +/** + * 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; + stop: () => void; + finished: Promise; +}; + +export function createReadAloudController( + prepare: ( + text: string, + settings: ReadAloudSettings, + signal: AbortSignal, + ) => Promise, + resolve: MFunctionType = mFallback, +) { + 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; + let disposing = false; + const dispose = (current: SpeechPlayback) => { + disposing = true; + try { + current.stop(); + } finally { + disposing = false; + } + }; + 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; + for (const listener of listeners) listener(); + }; + const stop = () => { + active?.abort(); + active = null; + paused = false; + starting = false; + resumePending?.(); + resumePending = null; + if (playback) dispose(playback); + playback = null; + publish({ id: null, status: "idle" }); + }; + return { + getSnapshot: () => state, + subscribe: (listener: () => void) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + stop, + pause() { + if (disposing || !active || (state.status !== "playing" && state.status !== "loading")) + return; + paused = true; + publish({ ...state, status: "paused" }); + if (!starting) playback?.pause(); + }, + async resume() { + 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; + publish({ ...state, status: "loading" }); + await playback.play(); + if (active === owner) { + starting = false; + if (paused) playback.pause(); + else publish({ ...state, status: "playing" }); + } + } catch { + if (active === owner) { + stop(); + publish({ id, status: "error", error: resolve(msg("Could not resume speech.")) }); + } + } + }, + async start(id: string, markdown: string, settings: ReadAloudSettings) { + stop(); + if (settings.provider === "off") return; + // 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; + try { + for (const chunk of chunks) { + publish({ id, status: paused ? "paused" : "loading" }); + const next = await prepare(chunk, settings, owner.signal); + if (active !== owner) { + dispose(next); + return; + } + playback = next; + // Playback can fail while the platform is still activating its audio session. + void next.finished.catch(() => {}); + 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; + dispose(next); + playback = null; + } + if (active === owner) stop(); + } catch (error) { + if (active !== owner) return; + stop(); + publish({ + id, + status: "error", + error: + error instanceof Error ? error.message : resolve(msg("Could not read this response.")), + }); + } + }, + }; +} diff --git a/packages/client-runtime/src/voice-input/environment.test.ts b/packages/client-runtime/src/voice-input/environment.test.ts index 50e28d6d416da..411fd3aa45890 100644 --- a/packages/client-runtime/src/voice-input/environment.test.ts +++ b/packages/client-runtime/src/voice-input/environment.test.ts @@ -3,8 +3,13 @@ import { EnvironmentId, type EnvironmentSpeechModel } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { HttpClient, HttpClientResponse } from "effect/http"; -import { BearerConnectionTarget, type PreparedConnection } from "../connection/model.ts"; -import { installEnvironmentSpeechModel } from "./environment.ts"; +import { + BearerConnectionTarget, + PrimaryConnectionTarget, + type PreparedConnection, +} from "../connection/model.ts"; +import * as RpcHttp from "../rpc/http.ts"; +import { installEnvironmentSpeechModel, startSpeechSynthesis } from "./environment.ts"; const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); const PREPARED: PreparedConnection = { @@ -102,3 +107,53 @@ describe("installEnvironmentSpeechModel", () => { }), ); }); + +const SPEECH_TARGET = new PrimaryConnectionTarget({ + environmentId: "environment-speech" as never, + label: "Speech", + httpBaseUrl: "https://environment.example.test", + wsBaseUrl: "wss://environment.example.test", +}); + +const SPEECH_PREPARED: PreparedConnection = { + environmentId: SPEECH_TARGET.environmentId, + label: SPEECH_TARGET.label, + httpBaseUrl: SPEECH_TARGET.httpBaseUrl, + socketUrl: SPEECH_TARGET.wsBaseUrl, + httpAuthorization: null, + target: SPEECH_TARGET, +}; + +const start = (response: Response) => + startSpeechSynthesis(SPEECH_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 2aa18a7beb5a5..b41f772af2db6 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -1,8 +1,14 @@ +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"; 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 +32,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> >; @@ -331,3 +338,96 @@ 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 } }), + }); + +/** Starts synthesis and resolves, once audio exists, with the URL of its live MP3 stream. */ +export const startSpeechSynthesis = ( + prepared: PreparedConnection, + provider: SpeechSynthesisProvider, + payload: SpeechSynthesisRequest, +) => { + let endpoint = prepared.httpBaseUrl; + return request({ + group: "voice", + prepared, + method: "POST", + timeoutMs: 130_000, + 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(); + }), + ); +}; + +/** 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", + 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 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", + 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 d607b32aad355..41d288fd292ad 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -42,3 +42,13 @@ export { type VoiceTranscriptionErrorCode, type VoiceTranscriptionOptions, } from "./transcription.ts"; + +export { + cancelSpeechSynthesisModelDownload, + downloadSpeechSynthesisModel, + getSpeechSynthesisModels, + linkSpeechSynthesisModels, + prepareSpeechSynthesis, + removeSpeechSynthesisModel, + startSpeechSynthesis, +} from "./environment.ts"; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 2a6c0dc43d50c..b6fd0f44e653a 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -1,3 +1,12 @@ +import { + SpeechSynthesisProvider, + SpeechSynthesisRequest, + SpeechSynthesisCatalog, + SpeechSynthesisError, + SpeechSynthesisModelRequest, + SpeechSynthesisPrepareRequest, + SpeechSynthesisStream, +} from "./readAloud.ts"; import * as Context from "effect/Context"; import type * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; @@ -852,6 +861,66 @@ export class EnvironmentVoiceBodyLimit extends HttpApiMiddleware.Service (value === "chatgpt" ? ("off" as const) : value), + encode: (value) => value, + }), + ), + ), + environmentId: Schema.NullOr(EnvironmentId), + 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)), + skipCodeBlocks: Schema.Boolean, + backgroundPlayback: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), +}); +export type ReadAloudSettings = typeof ReadAloudSettings.Type; +export const DEFAULT_READ_ALOUD_SETTINGS: ReadAloudSettings = { + provider: "off", + environmentId: null, + model: "", + voice: "", + speed: 1, + language: "auto", + skipCodeBlocks: true, + backgroundPlayback: true, +}; +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(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), + /** 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; +/** 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)), +}); +export const SpeechSynthesisCatalog = Schema.Struct({ + defaultModel: Schema.String, + apiKeyProvider: Schema.NullOr(CloudSpeechProvider), + supportsModelSelection: Schema.Boolean, + supportsVoiceSelection: Schema.Boolean, + speedAppliedByProvider: Schema.Boolean, + error: Schema.optionalKey(Schema.String), + models: Schema.Array( + Schema.Struct({ + id: Schema.String, + 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. */ + 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, + supportsModelSelection: false, + supportsVoiceSelection: false, + speedAppliedByProvider: false, + models: [], +}; + +export class SpeechSynthesisError extends Schema.TaggedError()( + "SpeechSynthesisError", + { + provider: SpeechSynthesisProvider, + cause: Schema.optionalKey(Schema.Defect()), + reason: Schema.Literals([ + "missing-key", + "key-changed", + "unreadable-key", + "rejected-key", + "rate-limit", + "unavailable", + "model-unavailable", + "missing-model", + ]), + }, + { httpApiStatus: 422 }, +) { + override get message() { + const name = READ_ALOUD_LABELS[this.provider]; + switch (this.reason) { + 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 "missing-model": + return "Download a local speech model in Settings → Voice."; + case "unavailable": + return `${name} could not generate speech. Try again later.`; + } + } +} diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index 9dc56d7a6a02d..c2cdf8a196a0e 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; import * as Schema from "effect/Schema"; +import { DEFAULT_READ_ALOUD_SETTINGS } from "./readAloud.ts"; import { type CommandId, ProjectId } from "./baseSchemas.ts"; import { ProviderDriverKind, @@ -555,3 +556,22 @@ describe("server model preferences", () => { expect(decodeServerSettingsPatch(input)).toEqual(input); }); }); + +it("disables retired subscription speech without resetting other preferences", () => { + const settings = decodeClientSettings({ + speechCorrectionWord: "correct", + readAloud: { + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "chatgpt", + speed: 1.25, + backgroundPlayback: false, + }, + }); + expect(settings.readAloud).toEqual({ + ...DEFAULT_READ_ALOUD_SETTINGS, + provider: "off", + speed: 1.25, + backgroundPlayback: false, + }); + expect(settings.speechCorrectionWord).toBe("correct"); +}); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4922cceeda19f..0c150b55131f8 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, @@ -402,7 +403,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"), @@ -586,6 +587,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([]))), @@ -1388,6 +1390,7 @@ export const CloudSpeechCredentials = Schema.Struct({ openai: CloudSpeechCredential, xai: CloudSpeechCredential, openrouter: CloudSpeechCredential, + elevenlabs: CloudSpeechCredential, }); export const ServerSettings = Schema.Struct({ @@ -1429,7 +1432,9 @@ export const ServerSettings = Schema.Struct({ /** Lets clients reach this machine's loopback ports over `/api/preview/tunnel`. */ enablePreviewTunnel: 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")), @@ -1903,6 +1908,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), @@ -2177,6 +2183,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/contracts/src/speech.ts b/packages/contracts/src/speech.ts index 0784c92be4ab6..5d2c22c197800 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; diff --git a/packages/shared/package.json b/packages/shared/package.json index d888aebffe1df..73680560b4b58 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/HostProcess.ts b/packages/shared/src/HostProcess.ts index 50490bfb78b5f..9ea567da5e543 100644 --- a/packages/shared/src/HostProcess.ts +++ b/packages/shared/src/HostProcess.ts @@ -39,6 +39,24 @@ export const LinuxLibc = Context.Reference<"gnu" | "musl">( }, ); +/** 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 new file mode 100644 index 0000000000000..e05e00774bfba --- /dev/null +++ b/packages/shared/src/readAloud.test.ts @@ -0,0 +1,36 @@ +import { expect, it } from "vite-plus/test"; +import { readAloudText, splitReadAloudText } from "./readAloud.ts"; + +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.\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("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).", + ); +}); + +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..d54004d6abe57 --- /dev/null +++ b/packages/shared/src/readAloud.ts @@ -0,0 +1,61 @@ +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); + +// 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 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 : ""; + }; + 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) { + 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; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2bcfc58b15a64..06a033e77bc7a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -725,6 +725,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) @@ -858,6 +861,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.5.0 version: 1.5.0(patch_hash=7fe8889d7916196c56006cf15a39abba4099feb2c567b4030b82a09364cee500)(zod@4.6.7) @@ -951,6 +957,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) @@ -997,6 +1006,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 @@ -1495,6 +1507,15 @@ 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 + packages/client-runtime: dependencies: '@pierre/diffs': @@ -3416,6 +3437,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] @@ -9504,6 +9528,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: @@ -13987,6 +14016,8 @@ snapshots: dependencies: css-tree: 3.2.1 + '@breezystack/lamejs@1.2.7': {} + '@bruits/satteri-darwin-arm64@0.10.5': optional: true @@ -19599,6 +19630,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) 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 e7acbf1e76ff1..0f8d0da6ad73e 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",