From 6979a9c0b6e76a904f0b1dd38a6a84e50888517c Mon Sep 17 00:00:00 2001 From: shubhook Date: Tue, 20 Oct 2026 23:34:17 +0530 Subject: [PATCH 1/2] Remove voice from the product: UI, API, adapters, and stored credentials Voice mode is out of v0. This deletes the call/dictation/TTS surfaces and adapters, and adds a migration that drops voice tables and permanently deletes encrypted voice provider secrets. Co-authored-by: Cursor --- .env.example | 3 - AGENTS.md | 2 +- CHANGELOG.md | 5 +- apps/api/src/ai-consent.test.ts | 17 +- apps/api/src/ai-consent.ts | 22 +- apps/api/src/app.ts | 12 - apps/api/src/request-body-limit.test.ts | 6 +- apps/api/src/router.test.ts | 108 -- apps/api/src/router.ts | 210 +-- apps/api/src/thread-message-pages.test.ts | 36 - apps/api/src/thread-message-pages.ts | 3 +- apps/api/src/thread-target.test.ts | 61 - apps/api/src/thread-target.ts | 8 - apps/api/src/voice.test.ts | 483 ------ apps/api/src/voice.ts | 493 ------- apps/desktop/src/session-permissions.test.ts | 71 +- apps/desktop/src/session-permissions.ts | 12 - apps/mobile/.maestro/screenshots.yaml | 6 - apps/mobile/app.json | 17 +- apps/mobile/app/(tabs)/account/index.tsx | 3 +- apps/mobile/app/_layout.tsx | 1 - apps/mobile/app/bot-settings.tsx | 34 +- apps/mobile/app/thread.tsx | 238 +-- apps/mobile/app/voice.tsx | 414 ------ apps/mobile/components/CallCard.tsx | 252 ---- apps/mobile/components/VoiceChatCard.tsx | 95 -- apps/mobile/lib/android-permissions.test.ts | 15 +- apps/mobile/lib/api.test.ts | 22 - apps/mobile/lib/api.ts | 9 - apps/mobile/lib/auto-speak.test.ts | 95 -- apps/mobile/lib/auto-speak.ts | 45 - apps/mobile/lib/call-session.test.ts | 692 --------- apps/mobile/lib/call-session.ts | 688 --------- apps/mobile/lib/device-voice.test.ts | 53 - apps/mobile/lib/device-voice.ts | 12 - apps/mobile/lib/dictation.test.ts | 135 -- apps/mobile/lib/dictation.ts | 200 --- apps/mobile/lib/inbox-spaces.test.ts | 1 - apps/mobile/lib/locales/de.ts | 43 +- apps/mobile/lib/locales/ru.ts | 43 +- apps/mobile/lib/locales/zh.ts | 40 +- apps/mobile/lib/message-presentation.test.ts | 4 +- apps/mobile/lib/voice-call-entry.test.ts | 133 -- apps/mobile/lib/voice-call-entry.ts | 58 - apps/mobile/lib/voice.test.ts | 305 ---- apps/mobile/lib/voice.ts | 342 ----- apps/mobile/package.json | 3 - apps/web/e2e/bot-organization.spec.ts | 4 +- apps/web/e2e/golden.spec.ts | 5 - apps/web/e2e/group-chats.spec.ts | 17 - apps/web/e2e/helpers.ts | 10 +- apps/web/e2e/settings-shell.spec.ts | 9 +- apps/web/e2e/voice.spec.ts | 100 -- apps/web/scripts/translations-de.json | 22 - apps/web/scripts/translations-es.json | 22 - apps/web/scripts/translations-hi.json | 22 - apps/web/scripts/translations-ko.json | 22 - apps/web/scripts/translations-pt-BR.json | 22 - apps/web/scripts/translations-tr.json | 22 - apps/web/scripts/translations-zh-CN.json | 22 - apps/web/src/components/call/CallCard.tsx | 137 -- .../components/call/VoiceChatCard.test.tsx | 75 - .../web/src/components/call/VoiceChatCard.tsx | 85 -- apps/web/src/lib/call-session.test.ts | 825 ----------- apps/web/src/lib/call-session.ts | 496 ------- apps/web/src/lib/dictation.test.ts | 1296 ----------------- apps/web/src/lib/dictation.ts | 583 -------- apps/web/src/lib/thread-events.test.ts | 5 +- apps/web/src/lib/thread-events.ts | 2 - apps/web/src/lib/tts.test.ts | 150 -- apps/web/src/lib/tts.ts | 293 ---- apps/web/src/locales/de/messages.po | 167 --- apps/web/src/locales/en/messages.po | 167 --- apps/web/src/locales/es/messages.po | 167 --- apps/web/src/locales/fr/messages.po | 167 --- apps/web/src/locales/hi/messages.po | 167 --- apps/web/src/locales/ko/messages.po | 167 --- apps/web/src/locales/pt-BR/messages.po | 167 --- apps/web/src/locales/ru/messages.po | 167 --- apps/web/src/locales/tr/messages.po | 167 --- apps/web/src/locales/zh-CN/messages.po | 167 --- apps/web/src/pages/SettingsOverlay.test.tsx | 3 +- apps/web/src/pages/SettingsOverlay.tsx | 61 +- apps/web/src/pages/Shell.tsx | 170 +-- .../src/pages/VoiceSettingsOverlay.test.tsx | 155 -- apps/web/src/pages/VoiceSettingsOverlay.tsx | 406 ------ apps/web/src/pages/shell/bot-panel.test.tsx | 3 - apps/web/src/pages/shell/bot-panel.tsx | 46 +- docs/ai-data-sharing-review.md | 12 +- docs/self-host.md | 9 +- packages/adapter-kit/src/interfaces.ts | 14 - packages/adapter-kit/src/registry.ts | 1 - packages/adapter-kit/src/types.ts | 38 - packages/adapters/src/ai-consent.ts | 9 +- packages/adapters/src/builtin-tools.ts | 19 - packages/adapters/src/cartesia-voice.ts | 130 -- packages/adapters/src/elevenlabs-voice.ts | 113 -- .../src/executor-oauth-retire.test.ts | 3 - packages/adapters/src/executor.test.ts | 12 - packages/adapters/src/executor.ts | 116 +- packages/adapters/src/fish-audio-voice.ts | 310 ---- packages/adapters/src/index.ts | 6 - packages/adapters/src/openai-voice.ts | 104 -- packages/adapters/src/scripted-voice.ts | 62 - packages/adapters/src/voice-factory.test.ts | 693 --------- packages/adapters/src/voice-factory.ts | 97 -- packages/adapters/src/voice-http.test.ts | 152 -- packages/adapters/src/voice-http.ts | 155 -- packages/contracts/src/ai-consent.ts | 4 +- packages/contracts/src/domain.ts | 40 - packages/contracts/src/index.test.ts | 1 - packages/contracts/src/rpc.ts | 54 - packages/core/src/ai-consent.test.ts | 22 +- packages/core/src/ai-consent.ts | 1 - packages/core/src/barge-in.test.ts | 40 - packages/core/src/barge-in.ts | 32 - packages/core/src/call-nonce.test.ts | 30 - packages/core/src/call-nonce.ts | 26 - packages/core/src/echo.test.ts | 97 -- packages/core/src/echo.ts | 103 -- packages/core/src/farewell.test.ts | 27 - packages/core/src/farewell.ts | 55 - packages/core/src/index.ts | 6 - packages/core/src/speech-text.test.ts | 166 --- packages/core/src/speech-text.ts | 230 --- packages/core/src/voice-chat-groups.test.ts | 189 --- packages/core/src/voice-chat-groups.ts | 125 -- .../20261020120000_drop_voice/migration.sql | 18 + packages/db/prisma/schema.prisma | 38 - packages/db/src/credential-secrets.test.ts | 28 +- packages/db/src/credential-secrets.ts | 29 +- packages/db/src/events.ts | 4 - packages/db/src/index.ts | 1 - packages/db/src/repos.ts | 4 - packages/db/src/spaces.ts | 53 +- packages/db/src/voice-credentials.test.ts | 54 - packages/db/src/voice-credentials.ts | 108 -- packages/testkit/src/authorization.test.ts | 73 +- packages/testkit/src/cli/harness.ts | 1 - packages/testkit/src/voice.test.ts | 222 --- pnpm-lock.yaml | 46 - 141 files changed, 196 insertions(+), 16096 deletions(-) delete mode 100644 apps/api/src/voice.test.ts delete mode 100644 apps/api/src/voice.ts delete mode 100644 apps/mobile/app/voice.tsx delete mode 100644 apps/mobile/components/CallCard.tsx delete mode 100644 apps/mobile/components/VoiceChatCard.tsx delete mode 100644 apps/mobile/lib/auto-speak.test.ts delete mode 100644 apps/mobile/lib/auto-speak.ts delete mode 100644 apps/mobile/lib/call-session.test.ts delete mode 100644 apps/mobile/lib/call-session.ts delete mode 100644 apps/mobile/lib/device-voice.test.ts delete mode 100644 apps/mobile/lib/device-voice.ts delete mode 100644 apps/mobile/lib/dictation.test.ts delete mode 100644 apps/mobile/lib/dictation.ts delete mode 100644 apps/mobile/lib/voice-call-entry.test.ts delete mode 100644 apps/mobile/lib/voice-call-entry.ts delete mode 100644 apps/mobile/lib/voice.test.ts delete mode 100644 apps/mobile/lib/voice.ts delete mode 100644 apps/web/e2e/voice.spec.ts delete mode 100644 apps/web/src/components/call/CallCard.tsx delete mode 100644 apps/web/src/components/call/VoiceChatCard.test.tsx delete mode 100644 apps/web/src/components/call/VoiceChatCard.tsx delete mode 100644 apps/web/src/lib/call-session.test.ts delete mode 100644 apps/web/src/lib/call-session.ts delete mode 100644 apps/web/src/lib/dictation.test.ts delete mode 100644 apps/web/src/lib/dictation.ts delete mode 100644 apps/web/src/lib/tts.test.ts delete mode 100644 apps/web/src/lib/tts.ts delete mode 100644 apps/web/src/pages/VoiceSettingsOverlay.test.tsx delete mode 100644 apps/web/src/pages/VoiceSettingsOverlay.tsx delete mode 100644 packages/adapters/src/cartesia-voice.ts delete mode 100644 packages/adapters/src/elevenlabs-voice.ts delete mode 100644 packages/adapters/src/fish-audio-voice.ts delete mode 100644 packages/adapters/src/openai-voice.ts delete mode 100644 packages/adapters/src/scripted-voice.ts delete mode 100644 packages/adapters/src/voice-factory.test.ts delete mode 100644 packages/adapters/src/voice-factory.ts delete mode 100644 packages/adapters/src/voice-http.test.ts delete mode 100644 packages/adapters/src/voice-http.ts delete mode 100644 packages/core/src/barge-in.test.ts delete mode 100644 packages/core/src/barge-in.ts delete mode 100644 packages/core/src/call-nonce.test.ts delete mode 100644 packages/core/src/call-nonce.ts delete mode 100644 packages/core/src/echo.test.ts delete mode 100644 packages/core/src/echo.ts delete mode 100644 packages/core/src/farewell.test.ts delete mode 100644 packages/core/src/farewell.ts delete mode 100644 packages/core/src/speech-text.test.ts delete mode 100644 packages/core/src/speech-text.ts delete mode 100644 packages/core/src/voice-chat-groups.test.ts delete mode 100644 packages/core/src/voice-chat-groups.ts create mode 100644 packages/db/prisma/migrations/20261020120000_drop_voice/migration.sql delete mode 100644 packages/db/src/voice-credentials.test.ts delete mode 100644 packages/db/src/voice-credentials.ts delete mode 100644 packages/testkit/src/voice.test.ts diff --git a/.env.example b/.env.example index 8468c7be..58094bb6 100644 --- a/.env.example +++ b/.env.example @@ -105,9 +105,6 @@ PI_DEFAULT_MODEL=openai/gpt-6-luna # Below the confidence floor, Auto Review asks the user. # RAKAZO_AUTO_REVIEW_MODEL=jev-latest # RAKAZO_AUTO_REVIEW_MIN_CONFIDENCE=0.5 -# Optional Fish Audio speech model used when a connection does not set its own. -# Default is s2.1-pro. A Fish connection can override this in Voice settings. -# FISH_TTS_MODEL=s1 # Optional local OpenAI-compatible models. Leave blank to disable the provider. RAKAZO_LOCAL_MODELS= RAKAZO_LOCAL_MODELS_URL=http://127.0.0.1:11434/v1 diff --git a/AGENTS.md b/AGENTS.md index 4da785f8..3a8984c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ - This is a public repository: assume all tracked content and diffs are public. Never commit secrets, `.env` files, private URLs, personal/customer data, or real production data; use fake placeholders. Review `git status` and the staged diff before committing, and never force-add ignored files. If private data appears, stop and alert the maintainer. - Milo is one product across web, Electron desktop, and Expo mobile; Electron hosts the web UI. Put shared behavior, contracts, API logic, and reusable UI in packages. Keep only genuinely native navigation, storage, permissions, and interactions platform-specific. Core workflows must cover every applicable surface or degrade safely for an explicit reason. -- No hosted vendor is required to run the core product. Keep LLMs, sandboxes, memory, voice, integrations, and future external services optional and behind provider-neutral interfaces. Vendor SDKs, configuration, and translation belong only in adapters and composition roots. New providers must reuse shared contracts and deterministic offline conformance tests. +- No hosted vendor is required to run the core product. Keep LLMs, sandboxes, memory, integrations, and future external services optional and behind provider-neutral interfaces. Vendor SDKs, configuration, and translation belong only in adapters and composition roots. New providers must reuse shared contracts and deterministic offline conformance tests. - Keep UI and copy minimal. Show advanced capability progressively and only when it becomes relevant; do not add explainer text that repeats the interface. Frontends express intent and render state; the backend owns orchestration, authorization, validation, retries, recovery, and provider translation. Give controls concise accessible names when needed. - Treat every visible word as UI. Start UX work by asking what can be removed, and prefer progressive disclosure over persistent explanation or status chrome. If a PR adds user-facing copy, its description must quote the copy, explain why it is necessary, and say why removing it or revealing it only when relevant would not work. - Configure compatible providers and models through shared connection settings and standard protocol capabilities; never add provider- or model-specific environment variables when the generic connection can express the behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index 33b78cd5..02b16a08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed -- Fish Audio speech can use a model other than s2.1-pro. Each Fish connection can set Speech model in Voice settings; `FISH_TTS_MODEL` is the default only when that field is empty (unset still uses s2.1-pro). A failed speak, transcribe, or voice-list request logs the upstream Fish status and message, including when the error body cannot be read, and the message returned to the client does not include the API key. - A picture attached to an earlier message is now visible to the bot when a later turn asks about it, for a model that can see images. Only the current turn carried its images; older turns arrived as a text marker, so the bot asked for the picture again. The most recent user turns now keep their images, within a fixed turn, byte, and per-model image budget. A turn whose pictures exceed the byte budget keeps the newest ones that fit. If an earlier picture cannot be read, its history marker says it is unavailable. - A bot on a reasoning model could answer with "No response. Try again." on a harder question: thinking is billed against the same output ceiling as the reply, and the 4k default left nothing for the reply itself. Reasoning models now get a 32k output ceiling instead, still bounded by whatever the model itself allows. - A newly created bot's thread opened empty and stayed silent until given real work, so a misread `title`/`description`/`instructions` went unnoticed until it cost a run. Creating a bot now queues one turn where it states how it understood its role and asks for anything it needs. @@ -18,7 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - Pipedream exposed every tool of every connected app at once, so a handful of apps could fill a run's tool list. Above 20 tools the connector now offers the same lazy catalog the MCP connector uses (`pipedream_search_tools`, `pipedream_load_tool`, and `pipedream_execute_tool`), with names grouped by app. - The Needs you computer card in a thread now includes Open, which opens that bot's computer the same way the computer panel does, including from a group member bot. - Bots with more than 20 MCP tools failed on every Claude model behind a Claude Pro/Max/Team sign-in with "You're out of extra usage": Anthropic rejects Claude Code OAuth requests that carry a tool named `mcp_*`. The lazy catalog wrappers are now `connectors_search_tools`, `connectors_load_tool` and `connectors_execute_tool`. -- Changing a bot's model, thinking level or voice failed with a validation error once its instructions outgrew the description limit, and saving any other setting overwrote those instructions with the shorter description text. Bot settings now put the description and instructions on the wire only when that field was edited, clamped to each field's own limit. +- Changing a bot's model or thinking level failed with a validation error once its instructions outgrew the description limit, and saving any other setting overwrote those instructions with the shorter description text. Bot settings now put the description and instructions on the wire only when that field was edited, clamped to each field's own limit. ### Changed @@ -33,7 +32,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Sign in with ChatGPT, for a server on the same computer as the browser or desktop app. The same sign-in can run that person's bots on their ChatGPT plan in place of Claude Code. See [Sign in with ChatGPT](docs/self-host.md#sign-in-with-chatgpt). -- Voice mode: spoken replies, hold-to-talk dictation, and half-duplex calls with ElevenLabs, OpenAI, Cartesia, or Fish Audio. - Desktop owners using Docker can opt into running bot shell commands directly on their computer. This grants access under the owner's OS account; see [computer providers](docs/self-host.md#choosing-a-computer-provider). - GitHub Copilot and SuperGrok / X Premium sign-in for model access. - Spawn peer bots (each with its own thread and computer) and short-lived in-thread subagents. @@ -45,6 +43,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Removed +- Voice mode (spoken replies, hold-to-talk dictation, and provider calls). Voice settings, credentials, and related APIs are gone. - Model sign-in under `AGENT_RUNTIME=claude-code`. Every bot runs on the Claude Code CLI's own login, so web, desktop and mobile no longer show model settings or the per-bot model and thinking pickers there. - Sign in with Claude Pro/Max. Anthropic only allows Claude subscriptions inside Claude Code, so Milo no longer signs in to Claude or calls it with a subscription token. A Claude sign-in saved earlier stops working, and a subscription token (`sk-ant-oat…`) pasted as an Anthropic key is refused. Anthropic API keys still work. To run on a Claude subscription, use `AGENT_RUNTIME=claude-code`. - Nonfunctional Grant folder picker in the desktop app. diff --git a/apps/api/src/ai-consent.test.ts b/apps/api/src/ai-consent.test.ts index cea07eca..43898ce8 100644 --- a/apps/api/src/ai-consent.test.ts +++ b/apps/api/src/ai-consent.test.ts @@ -17,10 +17,6 @@ function setup() { spaceModelPreference: { findMany: vi.fn(async () => []), findFirst: vi.fn(async () => null) }, secret: { findMany: vi.fn(async () => []) }, bot: { findMany: vi.fn(async () => []) }, - spaceVoicePreference: { - findFirst: vi.fn(async () => ({ credential: { provider: "openai" }, voiceId: "alloy" })), - findMany: vi.fn(async () => [{ credential: { provider: "openai" } }]), - }, deploymentSettings: { findUnique: vi.fn(async () => null) }, aiDataConsent: { findMany: vi.fn(async () => []), upsert }, $transaction: vi.fn(async (queries) => Promise.all(queries)), @@ -43,7 +39,6 @@ describe("consent grants", () => { expect(status.recipients.map((recipient) => recipient.name)).toEqual( expect.arrayContaining(["Anthropic"]), ); - expect(deps.prisma.spaceVoicePreference.findMany).not.toHaveBeenCalled(); expect(deps.prisma.bot.findMany).toHaveBeenCalledWith( expect.objectContaining({ where: expect.objectContaining({ id: { in: ["bot"] } }) }), ); @@ -55,17 +50,6 @@ describe("consent grants", () => { expect(status.recipients.map((recipient) => recipient.name)).toEqual(["Claude Code"]); expect(status.recipients[0]?.privacyUrl).toBe("https://www.anthropic.com/legal/privacy"); }); - it("discloses only the selected voice provider before a voice action", async () => { - const { deps, actor } = setup(); - vi.mocked(deps.prisma.spaceVoicePreference.findMany).mockResolvedValue([ - { credential: { provider: "openai" } }, - { credential: { provider: "elevenlabs" } }, - ] as never); - const status = await aiConsentStatus(deps, actor, { uses: ["voice"] }); - expect(status.recipients).toHaveLength(1); - expect(status.recipients[0]?.name).toBe("OpenAI"); - expect(deps.prisma.spaceVoicePreference.findMany).not.toHaveBeenCalled(); - }); it("returns an operator policy without requiring a hosted provider", async () => { const { deps, actor } = setup(); deps.env.privacyPolicyUrl = "https://example.com/privacy"; @@ -73,6 +57,7 @@ describe("consent grants", () => { }); it("rejects stale disclosures, unknown recipients, and a changed account or Space", async () => { const { deps, actor, upsert } = setup(); + deps.env.agentRuntime = "claude-code"; const current = await aiConsentStatus(deps, actor); const input = { scope: current.scope, diff --git a/apps/api/src/ai-consent.ts b/apps/api/src/ai-consent.ts index d3cf3f0e..31b867bc 100644 --- a/apps/api/src/ai-consent.ts +++ b/apps/api/src/ai-consent.ts @@ -8,11 +8,7 @@ import { } from "@milo/adapters"; import type { Actor, AiConsentQuery, AiConsentStatus, AiRecipient } from "@milo/contracts"; import { AI_DISCLOSURE_VERSION, AI_PRIVACY_URL } from "@milo/contracts"; -import { - findDefaultModelCredential, - findDefaultVoiceCredential, - findModelCredential, -} from "@milo/db"; +import { findDefaultModelCredential, findModelCredential } from "@milo/db"; import { ORPCError } from "@orpc/server"; import type { RouterDeps } from "./router.js"; import { resolveThreadTarget } from "./thread-target.js"; @@ -22,7 +18,7 @@ export async function aiConsentStatus( actor: Actor, query: AiConsentQuery = {}, ): Promise { - const uses = query.uses ?? ["model", "voice"]; + const uses = query.uses ?? ["model"]; const modelsEnabled = uses.includes("model") && deps.env.agentRuntime !== "scripted"; const target = query.botId || query.groupId ? await resolveThreadTarget(deps.prisma, actor, query) : null; @@ -31,7 +27,7 @@ export async function aiConsentStatus( ? [target.botId] : target.memberBotIds : undefined; - const [preferences, defaultCredential, bots, voices, settings, consents] = await Promise.all([ + const [preferences, defaultCredential, bots, settings, consents] = await Promise.all([ modelsEnabled ? deps.prisma.spaceModelPreference.findMany({ where: { userId: actor.userId, spaceId: actor.spaceId }, @@ -50,16 +46,6 @@ export async function aiConsentStatus( select: { modelProvider: true, modelId: true, thinkingLevel: true }, }) : [], - uses.includes("voice") - ? query.uses - ? findDefaultVoiceCredential(deps.prisma, actor).then((credential) => - credential ? [{ credential }] : [], - ) - : deps.prisma.spaceVoicePreference.findMany({ - where: { userId: actor.userId, spaceId: actor.spaceId }, - include: { credential: true }, - }) - : [], modelsEnabled ? deps.prisma.deploymentSettings.findUnique({ where: { id: "default" } }) : null, deps.prisma.aiDataConsent.findMany({ where: { userId: actor.userId, spaceId: actor.spaceId, version: AI_DISCLOSURE_VERSION }, @@ -148,8 +134,6 @@ export async function aiConsentStatus( ); } } - for (const voice of voices) - add(aiRecipient({ provider: voice.credential.provider, use: "voice" })); return { scope: createHash("sha256") .update(JSON.stringify([actor.userId, actor.spaceId])) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index ea051302..b865373f 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -86,7 +86,6 @@ import { mountApiRequestBodyLimits } from "./request-body-limit.js"; import type { RouterDeps } from "./router.js"; import { createRouter, saveChatGptPlan } from "./router.js"; import { mountScreenTarget } from "./screen-proxy.js"; -import { mountVoiceHttpRoutes } from "./voice.js"; import { mountWebhookHttpRoutes } from "./webhook.js"; /** @@ -514,17 +513,6 @@ export async function createApp( if (matched) return c.newResponse(response.body, response); await next(); }); - mountVoiceHttpRoutes(app, { prisma, secrets }, async (c) => { - const session = await auth.api.getSession({ headers: sessionHeaders(c.req.raw) }); - if (!session?.user) return null; - const actor = await requireMembership( - prisma, - session.user.id, - c.req.header("x-rakazo-space-id"), - ).catch(() => null); - if (actor) enrichLogContext({ "user.id": actor.userId, "space.id": actor.spaceId }); - return actor; - }); mountWebhookHttpRoutes(app, { prisma, secrets, events, jobs }); app.route( diff --git a/apps/api/src/request-body-limit.test.ts b/apps/api/src/request-body-limit.test.ts index 7fa089fe..61822637 100644 --- a/apps/api/src/request-body-limit.test.ts +++ b/apps/api/src/request-body-limit.test.ts @@ -27,7 +27,7 @@ describe("API request body limits", () => { mountApiRequestBodyLimits(app); app.post("/api/auth/sign-in/email", async (c) => c.json(await parse(c.req.raw))); app.post("/rpc/test", async (c) => c.json(await parse(c.req.raw))); - app.post("/api/voice/speak", async (c) => c.json(await parse(c.req.raw))); + app.post("/api/webhooks/inbound", async (c) => c.json(await parse(c.req.raw))); const request = (path: string, contentLength: number) => app.request(path, { @@ -40,11 +40,11 @@ describe("API request body limits", () => { }); const auth = await request("/api/auth/sign-in/email", MAX_AUTH_REQUEST_BYTES + 1); const rpc = await request("/rpc/test", MAX_RPC_REQUEST_BYTES + 1); - const voice = await request("/api/voice/speak", MAX_RPC_REQUEST_BYTES + 1); + const webhook = await request("/api/webhooks/inbound", MAX_RPC_REQUEST_BYTES + 1); expect(auth.status).toBe(413); expect(rpc.status).toBe(413); - expect(voice.status).toBe(200); + expect(webhook.status).toBe(200); expect(parse).toHaveBeenCalledOnce(); }); diff --git a/apps/api/src/router.test.ts b/apps/api/src/router.test.ts index 5a36539f..527f7493 100644 --- a/apps/api/src/router.test.ts +++ b/apps/api/src/router.test.ts @@ -2825,8 +2825,6 @@ describe("bot model auth on save", () => { parentBotId: null, createdAt: now, updatedAt: now, - voiceId: null, - autoSpeak: false, modelProvider: "openai-codex", modelId, thinkingLevel: null, @@ -3191,112 +3189,6 @@ describe("routines.update", () => { }); }); -describe("threads.endCall", () => { - function fixture(duplicateMarker?: boolean) { - const created: { blocks?: unknown; clientNonce?: string }[] = []; - const events: { type: string; payload: Record }[] = []; - const tx = { - thread: { update: vi.fn().mockResolvedValue({ nextMessageSeq: 3, nextEventSeq: 5 }) }, - message: { - create: vi.fn(async ({ data }: { data: { blocks: unknown; clientNonce?: string } }) => { - if (duplicateMarker) throw Object.assign(new Error("unique"), { code: "P2002" }); - created.push({ blocks: data.blocks, clientNonce: data.clientNonce }); - return { id: "message-1" }; - }), - }, - event: vi.fn(), - task: { create: vi.fn().mockResolvedValue({ id: "task-1" }) }, - run: { - create: vi.fn().mockResolvedValue({ id: "run-1" }), - findUnique: vi.fn().mockResolvedValue({ status: "queued", startedAt: null }), - }, - }; - tx.event = { - create: vi.fn(async ({ data }: { data: { type: string; payload: never } }) => { - events.push({ type: data.type, payload: data.payload }); - return { seq: 4, threadId: "thread-1" }; - }), - } as never; - const prisma = { - bot: { - findFirst: vi - .fn() - .mockResolvedValue({ id: "bot-1", thread: { id: "thread-1" }, computer: null }), - }, - taughtSkill: { findFirst: vi.fn().mockResolvedValue(null) }, - $transaction: vi.fn(async (run: (client: typeof tx) => unknown) => run(tx)), - } as unknown as PrismaClient; - const enqueue = vi.fn().mockResolvedValue(undefined); - const deps = { - prisma, - events: { notify: vi.fn().mockResolvedValue(undefined) }, - jobs: { enqueue }, - env: { sandboxProvider: "fake" }, - } as unknown as RouterDeps; - const actor = { - spaceId: "space-1", - userId: "user-1", - email: "user@rakazo.test", - isDeploymentOwner: true, - } satisfies Actor; - const handler = new RPCHandler(createRouter(deps)); - return { - tx, - created, - events, - enqueue, - call: () => - handler.handle( - new Request("http://127.0.0.1/rpc/threads/endCall", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ json: { botId: "bot-1", callId: "call-1" } }), - }), - { prefix: "/rpc", context: { actor } }, - ), - }; - } - - it("closes the card and queues a call_end run", async () => { - const { call, created, events, tx, enqueue } = fixture(); - const { response } = await call(); - expect(response.status).toBe(200); - await expect(response.json()).resolves.toEqual({ json: { ok: true } }); - expect(created[0]?.blocks).toEqual([ - { kind: "voice_call", callId: "call-1", title: "", farewell: "" }, - ]); - expect(created[0]?.clientNonce).toBe("call:call-1:marker"); - expect(events.map((event) => event.type)).toEqual([ - "thread.message.created", - "thread.call.ended", - ]); - expect(events[1]?.payload).toMatchObject({ - callId: "call-1", - title: "", - messageId: "message-1", - }); - expect(events[0]?.payload).toMatchObject({ callId: "call-1", messageId: "message-1" }); - expect(tx.run.create).toHaveBeenCalledWith( - expect.objectContaining({ - data: expect.objectContaining({ trigger: "call_end", taskId: "task-1" }), - }), - ); - expect(String(tx.run.create.mock.calls[0]?.[0]?.data?.clientNonce)).toMatch(/^call:call-1:/); - expect(enqueue).toHaveBeenCalledOnce(); - }); - - it("is a no-op when a concurrent hang-up already wrote the marker", async () => { - const { call, created, events, tx, enqueue } = fixture(true); - const { response } = await call(); - expect(response.status).toBe(200); - await expect(response.json()).resolves.toEqual({ json: { ok: true } }); - expect(created).toEqual([]); - expect(events).toEqual([]); - expect(tx.run.create).not.toHaveBeenCalled(); - expect(enqueue).not.toHaveBeenCalled(); - }); -}); - describe("groups.archive", () => { async function archiveGroup(archivedAt: Date | null) { const calls: string[] = []; diff --git a/apps/api/src/router.ts b/apps/api/src/router.ts index 62df81ea..35d61aa5 100644 --- a/apps/api/src/router.ts +++ b/apps/api/src/router.ts @@ -53,7 +53,6 @@ import { computerSupportsTerminal, computerSupportsUpdate, computerUpdateView, - createVoiceProvider, defaultCatalogModelId, deletePushToken, deploymentAutoReviewDefault, @@ -147,8 +146,6 @@ import { import { ACTIVE_RUN_STATUSES, AttachmentValidationError, - CALL_CLIENT_NONCE_PREFIX, - callClientNonce, clampCatalogThinkingLevel, containsSecret, expandSkillReferencesInPrompt, @@ -173,13 +170,11 @@ import { deleteEmptySpaceForMember, deleteUnreferencedCredentialSecret, findDefaultModelCredential, - findDefaultVoiceCredential, findModelCredential, InvalidSpaceNameError, IsolationError, lockOwnedGroup, newestModelCredentialOrder, - newestVoiceCredentialOrder, Prisma, parseComputerMode, releaseSpaceDeletionClaim, @@ -192,7 +187,6 @@ import { SpaceNotEmptyError, SpaceNotFoundError, selectSpaceModelPreference, - selectSpaceVoicePreference, touchGroupUpdatedAt, } from "@milo/db"; import { getLogger } from "@milo/logging"; @@ -259,18 +253,6 @@ import { threadHead, threadSnapshot, } from "./thread-target.js"; -import { - disconnectVoiceCredential, - listVoiceCatalog, - loadDefaultVoiceCredential, - loadVoiceCredential, - persistVoiceCredential, - prepareVoice, - toVoiceCredential, - toVoiceStatus, - updateVoiceSpeechModel, - voiceContext, -} from "./voice.js"; const MAX_COMPUTER_TEXT_FILE_BYTES = 2 * 1024 * 1024; /** Each command writes a running and a done event, so this keeps about 100 commands. */ @@ -591,17 +573,6 @@ const SPACE_TEARDOWN_TIMEOUT_MS = 120_000; /** Catalog for helpers outside `createRouter` when the deps bring none. */ const sharedCodexCatalog = new CodexCatalogCache(); -/** The card is closed by a marker; the run that follows finishes whatever the call left open. */ -/** Deterministic nonce for a call's marker message. The unique (threadId, clientNonce) - * index makes it the hang-up idempotency key, and the "call:" prefix lets clients derive - * the marker's callId. User turns carry a uuid suffix, so they never collide. */ -export function callMarkerClientNonce(callId: string): string { - return `${CALL_CLIENT_NONCE_PREFIX}${callId}:marker`; -} - -const HANG_UP_PROMPT = - "The voice call just ended because the user hung up. First call end_call with a short title for the call (leave farewell empty). Then, if anything the user asked for during the call is still unfinished, complete it now as a normal chat reply with full formatting. If nothing is pending, reply with one short sentence."; - function spaceTeardownTimeoutMs(): number { const override = Number(process.env.SPACE_TEARDOWN_TIMEOUT_MS ?? ""); return Number.isFinite(override) && override > 0 ? override : SPACE_TEARDOWN_TIMEOUT_MS; @@ -1367,8 +1338,8 @@ export function createRouter(deps: RouterDeps) { if (existing.length === 0) return; const ids = existing.map((row) => row.id); // Credentials belong to the account, not the space — disconnecting - // removes them everywhere, matching voice.disconnect. Linked - // preferences in other spaces go with their credential. + // removes them everywhere. Linked preferences in other spaces go + // with their credential. await tx.spaceModelPreference.deleteMany({ where: { userId: context.actor.userId, credentialId: { in: ids } }, }); @@ -1574,8 +1545,6 @@ export function createRouter(deps: RouterDeps) { color: input.color, pinned: input.pinned, sectionId: input.sectionId, - voiceId: input.voiceId, - autoSpeak: input.autoSpeak, ...(input.modelProvider !== undefined ? { modelProvider: input.modelProvider, modelId: input.modelId ?? null } : {}), @@ -2111,86 +2080,6 @@ export function createRouter(deps: RouterDeps) { } return { ok: true as const }; }), - endCall: authed.threads.endCall.handler(async ({ context, input }) => { - const target = await resolveThreadTarget(deps.prisma, context.actor, input); - if (target.kind !== "bot") throw new IsolationError(); - await assertTeachingSendAllowed(deps.prisma, context.actor.spaceId, target.botId); - const { botId, threadId } = target; - const blocks = [ - { kind: "voice_call" as const, callId: input.callId, title: "", farewell: "" }, - ]; - const committed = await deps.prisma - .$transaction(async (tx) => { - // The marker's deterministic nonce is the idempotency key: the unique - // (threadId, clientNonce) index rejects a second hang-up, concurrent or not. - const message = await createThreadMessageInTransaction(tx, { - threadId, - role: "bot", - botId, - blocks, - clientNonce: callMarkerClientNonce(input.callId), - }); - await appendEventInTransaction(tx, { - spaceId: context.actor.spaceId, - threadId, - botId, - type: "thread.message.created", - payload: { messageId: message.id, role: "bot", blocks, callId: input.callId }, - }); - const task = await tx.task.create({ - data: { - spaceId: context.actor.spaceId, - botId, - threadId, - userId: context.actor.userId, - prompt: HANG_UP_PROMPT, - status: "queued", - }, - }); - const run = await tx.run.create({ - data: { - spaceId: context.actor.spaceId, - botId, - threadId, - taskId: task.id, - userId: context.actor.userId, - status: "queued", - trigger: "call_end", - clientNonce: callClientNonce(input.callId), - }, - select: { id: true }, - }); - const ended = await appendEventInTransaction(tx, { - spaceId: context.actor.spaceId, - threadId, - botId, - type: "thread.call.ended", - runId: run.id, - payload: { - botId, - threadId, - callId: input.callId, - title: "", - farewell: "", - messageId: message.id, - }, - }); - return { runId: run.id, eventSeq: ended.seq }; - }) - .catch((error) => { - if (!isUniqueViolation(error)) throw error; - return null; - }); - if (!committed) return { ok: true as const }; - await deps.events.notify(threadId, committed.eventSeq).catch((error) => { - getLogger().error("call end realtime notification", error); - }); - // The queued run is durable; a missed wake is repaired by the reconciler. - await deps.jobs.enqueue(runContinueJob(committed.runId)).catch((error) => { - getLogger().error("call end enqueue", error); - }); - return { ok: true as const }; - }), answer: authed.threads.answer.handler(async ({ context, input }) => { const target = await resolveThreadTarget(deps.prisma, context.actor, input); const answered = await deps.events.answerRunInput({ @@ -5195,97 +5084,6 @@ export function createRouter(deps: RouterDeps) { runs: await listSpaceRuns(deps.prisma, context.actor, input.filter), })), }, - voice: { - catalog: authed.voice.catalog.handler(async () => listVoiceCatalog()), - status: authed.voice.status.handler(async ({ context }) => { - const cred = await findDefaultVoiceCredential(deps.prisma, context.actor); - return toVoiceStatus(cred); - }), - credentials: authed.voice.credentials.handler(async ({ context }) => { - const rows = await deps.prisma.userVoiceCredential.findMany({ - where: { userId: context.actor.userId }, - include: { - preferences: { - where: { userId: context.actor.userId, spaceId: context.actor.spaceId }, - }, - }, - orderBy: newestVoiceCredentialOrder, - }); - return rows.map((row) => { - const preference = row.preferences[0]; - return toVoiceCredential({ - ...row, - isDefault: preference?.isDefault ?? false, - voiceId: preference?.voiceId ?? "", - speechModel: preference?.speechModel ?? "", - }); - }); - }), - connect: authed.voice.connect.handler(async ({ context, input }) => - persistVoiceCredential(deps, context.actor, { - provider: input.provider, - plaintext: input.apiKey, - voiceId: input.voiceId, - speechModel: input.speechModel, - signal: context.signal, - }), - ), - disconnect: authed.voice.disconnect.handler(async ({ context, input }) => - disconnectVoiceCredential(deps, context.actor, { provider: input.provider }), - ), - setVoice: authed.voice.setVoice.handler(async ({ context, input }) => { - const cred = await withSerializableRetry(() => - deps.prisma.$transaction( - async (tx) => { - const found = input.provider - ? await tx.userVoiceCredential.findFirst({ - where: { userId: context.actor.userId, provider: input.provider }, - orderBy: newestVoiceCredentialOrder, - }) - : ( - await tx.spaceVoicePreference.findFirst({ - where: { - userId: context.actor.userId, - spaceId: context.actor.spaceId, - isDefault: true, - }, - include: { credential: true }, - orderBy: [{ updatedAt: "desc" }, { id: "desc" }], - }) - )?.credential; - if (!found) { - throw new ORPCError("BAD_REQUEST", { message: "Connect a voice provider first." }); - } - // Picking a voice also makes its provider the one speak/transcribe use. - await selectSpaceVoicePreference(tx, context.actor, found.id, input.voiceId); - return { ...found, voiceId: input.voiceId, isDefault: true }; - }, - { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, - ), - ); - return toVoiceStatus(cred); - }), - setSpeechModel: authed.voice.setSpeechModel.handler(async ({ context, input }) => - updateVoiceSpeechModel(deps, context.actor, input), - ), - voices: authed.voice.voices.handler(async ({ context, input }) => { - const loaded = await loadDefaultVoiceCredential(deps, context.actor); - if (!loaded) return []; - const providerId = input.provider ?? loaded.cred.provider; - const row = - providerId === loaded.cred.provider - ? loaded - : await loadVoiceCredential(deps, context.actor, providerId); - if (!row) return []; - return createVoiceProvider(row.cred.provider).listVoices( - row.apiKey, - voiceContext(context.actor, context.signal), - ); - }), - prepare: authed.voice.prepare.handler(async ({ context, input }) => - prepareVoice(deps, context.actor, input), - ), - }, }); } @@ -6110,10 +5908,6 @@ function duplicateBotName(name: string) { return `${name.slice(0, 75)} copy`; } -function isUniqueViolation(error: unknown): boolean { - return Boolean(error && typeof error === "object" && "code" in error && error.code === "P2002"); -} - function isRecordNotFound(error: unknown): boolean { return Boolean(error && typeof error === "object" && "code" in error && error.code === "P2025"); } diff --git a/apps/api/src/thread-message-pages.test.ts b/apps/api/src/thread-message-pages.test.ts index c5108aa4..50c7ddfc 100644 --- a/apps/api/src/thread-message-pages.test.ts +++ b/apps/api/src/thread-message-pages.test.ts @@ -552,40 +552,4 @@ describe("thread message pages", () => { expect(messages.map((message) => message.seq)).toEqual([0, 1, 2, 3, 4]); expect(findMany.mock.calls.map(([query]) => query.where.seq?.lt)).toEqual([undefined, 3, 1]); }); - - it("derives callId from a call client nonce and leaves plain messages without one", async () => { - const findMany = vi.fn(async () => [ - { - id: "message-call", - threadId: "thread-1", - seq: 2, - role: "user", - blocks: [{ kind: "text", text: "Hey" }], - botId: null, - replyToMessageId: null, - replyQuote: null, - runId: null, - clientNonce: "call:call-1:abc", - createdAt: new Date("2026-08-16T00:00:02.000Z"), - }, - { - id: "message-plain", - threadId: "thread-1", - seq: 1, - role: "user", - blocks: [{ kind: "text", text: "Typed" }], - botId: null, - replyToMessageId: null, - replyQuote: null, - runId: null, - clientNonce: "plain-nonce", - createdAt: new Date("2026-08-16T00:00:01.000Z"), - }, - ]); - const prisma = { message: { findMany } } as unknown as PrismaClient; - - const page = await loadMessagePage(prisma, "thread-1", undefined, 2); - - expect(page.messages.map((message) => message.callId)).toEqual([undefined, "call-1"]); - }); }); diff --git a/apps/api/src/thread-message-pages.ts b/apps/api/src/thread-message-pages.ts index 894eee8a..179c7904 100644 --- a/apps/api/src/thread-message-pages.ts +++ b/apps/api/src/thread-message-pages.ts @@ -1,5 +1,5 @@ import type { MessageBlock, ThreadMessage, ThreadMessagePage } from "@milo/contracts"; -import { callIdFromClientNonce, isPeerReceiptBlocks } from "@milo/core"; +import { isPeerReceiptBlocks } from "@milo/core"; import type { Prisma, PrismaClient } from "@milo/db"; type MessageDb = PrismaClient | Prisma.TransactionClient; @@ -190,7 +190,6 @@ function toThreadMessage(row: { replyToMessageId: row.replyToMessageId ?? undefined, replyQuote: row.replyQuote ?? undefined, runId: row.runId ?? undefined, - callId: callIdFromClientNonce(row.clientNonce), createdAt: row.createdAt.toISOString(), }; } diff --git a/apps/api/src/thread-target.test.ts b/apps/api/src/thread-target.test.ts index 253d3f41..089ea918 100644 --- a/apps/api/src/thread-target.test.ts +++ b/apps/api/src/thread-target.test.ts @@ -1,6 +1,5 @@ import type { SandboxProvider } from "@milo/adapter-kit"; import type { Actor, MessageBlock } from "@milo/contracts"; -import { callClientNonce } from "@milo/core"; import type * as MessageQuoteModule from "@milo/core/message-quote"; import type { PrismaClient } from "@milo/db"; import { describe, expect, it, vi } from "vitest"; @@ -2249,66 +2248,6 @@ describe("sendThreadMessage", () => { }); }); - it("stamps the call id on the live event so the bubble joins the call card at once", async () => { - let messageSeq = 0; - let eventSeq = 0; - const clientNonce = callClientNonce("call-7"); - const tx = { - thread: { - update: vi.fn(async ({ data }: { data: { nextMessageSeq?: unknown } }) => - data.nextMessageSeq ? { nextMessageSeq: ++messageSeq } : { nextEventSeq: ++eventSeq }, - ), - }, - message: { - findFirst: vi.fn().mockResolvedValue(null), - update: vi.fn(), - create: vi.fn().mockResolvedValue({ - id: "msg-1", - threadId: "thread-1", - seq: 1, - role: "user", - blocks: [{ kind: "text", text: "book the flight" }], - botId: null, - runId: null, - clientNonce, - createdAt: new Date(), - }), - }, - run: { - findMany: vi.fn().mockResolvedValue([]), - findUnique: vi.fn().mockResolvedValue({ status: "queued", startedAt: null }), - create: vi.fn().mockResolvedValue({ id: "run-1", taskId: "task-1", status: "queued" }), - }, - task: { create: vi.fn().mockResolvedValue({ id: "task-1" }) }, - event: { - create: vi.fn().mockResolvedValue({ id: "event-1", seq: 1, createdAt: new Date() }), - }, - steeringMessage: { create: vi.fn() }, - }; - const prisma = { - message: { findUnique: vi.fn().mockResolvedValue(null) }, - $transaction: vi.fn(async (callback: (client: typeof tx) => unknown) => callback(tx)), - } as unknown as PrismaClient; - - await sendThreadMessage( - { - prisma, - events: { notify: vi.fn().mockResolvedValue(undefined) } as never, - jobs: { enqueue: vi.fn().mockResolvedValue(undefined) } as never, - }, - { spaceId: "workspace-1", userId: "user-1" } as Actor, - { kind: "bot", botId: "bot-1", threadId: "thread-1" } as ThreadTarget, - { text: "book the flight", clientNonce }, - ); - - expect(tx.event.create).toHaveBeenCalledWith({ - data: expect.objectContaining({ - type: "thread.message.created", - payload: expect.objectContaining({ callId: "call-7" }), - }), - }); - }); - it("drops a quote excerpt when the parent's persisted blocks are malformed", async () => { let messageSeq = 0; let eventSeq = 0; diff --git a/apps/api/src/thread-target.ts b/apps/api/src/thread-target.ts index f4964ba1..ff655ad6 100644 --- a/apps/api/src/thread-target.ts +++ b/apps/api/src/thread-target.ts @@ -12,7 +12,6 @@ import { } from "@milo/contracts"; import { ACTIVE_RUN_STATUSES, - callIdFromClientNonce, isActive, isConversationalRun, projectMessages, @@ -617,9 +616,6 @@ export async function sendThreadMessage( ) { const existing = await replayExistingSend(deps, target.threadId, input.clientNonce); if (existing) return existing; - // Live events carry the call id so a spoken turn joins the call card on first - // paint; without it the bubble shows loose until a refetch reads the nonce. - const callId = callIdFromClientNonce(input.clientNonce); const requestedReplyQuote = input.replyQuote?.trim() || undefined; if (requestedReplyQuote && !input.replyToMessageId) { throw new ORPCError("BAD_REQUEST", { message: "replyQuote requires replyToMessageId." }); @@ -725,7 +721,6 @@ export async function sendThreadMessage( messageId: message.id, role: "user", blocks, - callId, runIds: answered.map((run) => run.id), replyToMessageId, replyQuote, @@ -763,7 +758,6 @@ export async function sendThreadMessage( messageId: message.id, role: "user", blocks, - callId, replyToMessageId, replyQuote, }, @@ -809,7 +803,6 @@ export async function sendThreadMessage( messageId: message.id, role: "user", blocks, - callId, runIds: [run.id], replyToMessageId, replyQuote, @@ -969,7 +962,6 @@ export async function sendThreadMessage( messageId: message.id, role: "user", blocks, - callId, runIds: runs.map((run) => run.id), replyToMessageId, replyQuote, diff --git a/apps/api/src/voice.test.ts b/apps/api/src/voice.test.ts deleted file mode 100644 index 7190fe50..00000000 --- a/apps/api/src/voice.test.ts +++ /dev/null @@ -1,483 +0,0 @@ -import * as adapters from "@milo/adapters"; -import type { Actor } from "@milo/contracts"; -import type { PrismaClient } from "@milo/db"; -import { Hono } from "hono"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { - disconnectVoiceCredential, - fishSpeechModelValue, - MAX_SPEAK_REQUEST_BYTES, - MAX_TRANSCRIBE_REQUEST_BYTES, - mountVoiceHttpRoutes, - synthesizeVoice, - toVoiceStatus, - updateVoiceSpeechModel, - type VoiceDeps, -} from "./voice.js"; - -describe("toVoiceStatus", () => { - it("treats a saved key without a voice as configured but not ready", () => { - expect(toVoiceStatus({ provider: "elevenlabs", voiceId: "" })).toEqual({ - configured: true, - ready: false, - transcribe: true, - provider: "elevenlabs", - voiceId: "", - }); - }); - - it("is ready once a voice is chosen", () => { - expect(toVoiceStatus({ provider: "cartesia", voiceId: "katie" }).ready).toBe(true); - expect(toVoiceStatus({ provider: "cartesia", voiceId: "katie" }).transcribe).toBe(false); - }); - - it("is off when nothing is connected", () => { - expect(toVoiceStatus(null)).toEqual({ - configured: false, - ready: false, - transcribe: false, - provider: null, - voiceId: "", - }); - }); -}); - -describe("voice HTTP routes", () => { - it("rejects unauthenticated speak and transcribe", async () => { - const app = new Hono(); - mountVoiceHttpRoutes(app, {} as VoiceDeps, async () => null); - const speak = await app.request("/api/voice/speak", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ text: "hello" }), - }); - const transcribe = await app.request("/api/voice/transcribe", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ audioBase64: "AAAA", mimeType: "audio/webm" }), - }); - expect(speak.status).toBe(401); - expect(transcribe.status).toBe(401); - }); - - it.each([ - ["/api/voice/speak", MAX_SPEAK_REQUEST_BYTES], - ["/api/voice/transcribe", MAX_TRANSCRIBE_REQUEST_BYTES], - ])( - "rejects a declared oversized body on %s without waiting for cancellation", - async (path, max) => { - const cancel = vi.fn(() => new Promise(() => undefined)); - const request = new Request(`http://localhost${path}`, { - method: "POST", - headers: { - "content-type": "application/json", - "content-length": String(max + 1), - }, - body: new ReadableStream({ cancel }), - duplex: "half", - } as RequestInit & { duplex: "half" }); - const app = new Hono(); - mountVoiceHttpRoutes( - app, - {} as VoiceDeps, - async () => ({ userId: "user", spaceId: "space" }) as Actor, - ); - - const response = await app.request(request); - - expect(response.status).toBe(413); - await expect(response.json()).resolves.toEqual({ error: "Request body is too large." }); - expect(cancel).toHaveBeenCalledOnce(); - }, - ); - - it("stops reading a streamed oversized speak body", async () => { - const cancel = vi.fn(() => new Promise(() => undefined)); - const request = new Request("http://localhost/api/voice/speak", { - method: "POST", - headers: { "content-type": "application/json" }, - body: new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(MAX_SPEAK_REQUEST_BYTES + 1)); - }, - cancel, - }), - duplex: "half", - } as RequestInit & { duplex: "half" }); - const app = new Hono(); - mountVoiceHttpRoutes( - app, - {} as VoiceDeps, - async () => ({ userId: "user", spaceId: "space" }) as Actor, - ); - - const response = await app.request(request); - - expect(response.status).toBe(413); - expect(cancel).toHaveBeenCalledOnce(); - }); -}); - -const actor = { userId: "user-1", spaceId: "space-1" } as Actor; - -function makeDisconnectDeps( - overrides: { - existing?: Array<{ id: string; secretId: string; userId: string; provider: string }>; - modelReferences?: number; - voiceReferences?: number; - } = {}, -) { - const rows = overrides.existing ?? []; - const findMany = vi.fn().mockResolvedValue(rows); - const preferenceDeleteMany = vi.fn().mockResolvedValue({ count: rows.length }); - const credentialDeleteMany = vi.fn().mockResolvedValue({ count: rows.length }); - const modelCount = vi.fn().mockResolvedValue(overrides.modelReferences ?? 0); - const voiceCount = vi.fn().mockResolvedValue(overrides.voiceReferences ?? 0); - const secretDeleteMany = vi.fn().mockResolvedValue({ count: 1 }); - const prisma = { - userVoiceCredential: { - findMany, - deleteMany: credentialDeleteMany, - count: voiceCount, - }, - spaceVoicePreference: { deleteMany: preferenceDeleteMany }, - userModelCredential: { count: modelCount }, - secret: { deleteMany: secretDeleteMany }, - $transaction: vi.fn(), - }; - prisma.$transaction.mockImplementation(async (callback: (tx: typeof prisma) => unknown) => - callback(prisma), - ); - const deps = { - prisma: prisma as unknown as PrismaClient, - secrets: { put: vi.fn(), load: vi.fn() }, - } as unknown as VoiceDeps; - return { - deps, - findMany, - preferenceDeleteMany, - credentialDeleteMany, - secretDeleteMany, - transaction: prisma.$transaction, - }; -} - -describe("disconnectVoiceCredential", () => { - it("removes the actor credential, clears its default, and deletes an unreferenced secret", async () => { - const existing = { - id: "cred-1", - secretId: "secret-1", - userId: actor.userId, - provider: "scripted", - }; - const { deps, findMany, preferenceDeleteMany, credentialDeleteMany, secretDeleteMany } = - makeDisconnectDeps({ existing: [existing] }); - - await expect(disconnectVoiceCredential(deps, actor, { provider: "scripted" })).resolves.toEqual( - { - ok: true, - }, - ); - - expect(findMany).toHaveBeenCalledWith({ - where: { userId: actor.userId, provider: "scripted" }, - }); - expect(preferenceDeleteMany).toHaveBeenCalledWith({ - where: { userId: actor.userId, credentialId: { in: ["cred-1"] } }, - }); - expect(credentialDeleteMany).toHaveBeenCalledWith({ - where: { userId: actor.userId, id: { in: ["cred-1"] } }, - }); - expect(secretDeleteMany).toHaveBeenCalledWith({ where: { id: "secret-1" } }); - }); - - it("removes every actor credential for that provider", async () => { - const { deps, preferenceDeleteMany, credentialDeleteMany, secretDeleteMany } = - makeDisconnectDeps({ - existing: [ - { - id: "cred-new", - secretId: "secret-new", - userId: actor.userId, - provider: "scripted", - }, - { - id: "cred-old", - secretId: "secret-old", - userId: actor.userId, - provider: "scripted", - }, - ], - }); - - await expect(disconnectVoiceCredential(deps, actor, { provider: "scripted" })).resolves.toEqual( - { - ok: true, - }, - ); - - expect(preferenceDeleteMany).toHaveBeenCalledWith({ - where: { userId: actor.userId, credentialId: { in: ["cred-new", "cred-old"] } }, - }); - expect(credentialDeleteMany).toHaveBeenCalledWith({ - where: { userId: actor.userId, id: { in: ["cred-new", "cred-old"] } }, - }); - expect(secretDeleteMany).toHaveBeenCalledWith({ where: { id: "secret-new" } }); - expect(secretDeleteMany).toHaveBeenCalledWith({ where: { id: "secret-old" } }); - }); - - it("keeps a secret while another credential still references it", async () => { - const { deps, credentialDeleteMany, secretDeleteMany } = makeDisconnectDeps({ - existing: [ - { - id: "cred-1", - secretId: "secret-shared", - userId: actor.userId, - provider: "scripted", - }, - ], - voiceReferences: 1, - }); - - await expect(disconnectVoiceCredential(deps, actor, { provider: "scripted" })).resolves.toEqual( - { - ok: true, - }, - ); - - expect(credentialDeleteMany).toHaveBeenCalled(); - expect(secretDeleteMany).not.toHaveBeenCalled(); - }); - - it("does not delete another actor's credential", async () => { - const { deps, findMany, preferenceDeleteMany, credentialDeleteMany, secretDeleteMany } = - makeDisconnectDeps(); - - await expect( - disconnectVoiceCredential(deps, { ...actor, userId: "intruder" }, { provider: "scripted" }), - ).resolves.toEqual({ ok: true }); - - expect(findMany).toHaveBeenCalledWith({ - where: { userId: "intruder", provider: "scripted" }, - }); - expect(preferenceDeleteMany).not.toHaveBeenCalled(); - expect(credentialDeleteMany).not.toHaveBeenCalled(); - expect(secretDeleteMany).not.toHaveBeenCalled(); - }); - - it("rejects a blank provider before opening a transaction", async () => { - const { deps, transaction } = makeDisconnectDeps(); - - await expect(disconnectVoiceCredential(deps, actor, { provider: " " })).rejects.toMatchObject( - { - code: "BAD_REQUEST", - }, - ); - expect(transaction).not.toHaveBeenCalled(); - }); -}); - -describe("fishSpeechModelValue", () => { - it("trims a Fish model id and treats blank as no override", () => { - expect(fishSpeechModelValue(" s1 ")).toBe("s1"); - expect(fishSpeechModelValue(" ")).toBeNull(); - }); - - it("rejects a model id that cannot be a Fish header", () => { - expect(() => fishSpeechModelValue("s1\ninjected")).toThrow( - "That speech model id is not valid.", - ); - }); -}); - -describe("updateVoiceSpeechModel", () => { - function speechDeps(preference: { id: string; voiceId: string; isDefault: boolean } | null) { - const credential = { - id: "cred-1", - userId: actor.userId, - provider: "fish-audio", - secretId: "secret-1", - }; - const update = vi - .fn() - .mockImplementation(async ({ data }: { data: { speechModel: string | null } }) => ({ - speechModel: data.speechModel, - })); - const create = vi.fn(); - const prisma = { - userVoiceCredential: { findFirst: vi.fn().mockResolvedValue(credential) }, - spaceVoicePreference: { - findUnique: vi.fn().mockResolvedValue(preference), - create, - update, - updateMany: vi.fn(), - upsert: vi.fn(), - }, - $transaction: vi.fn(), - }; - prisma.$transaction.mockImplementation(async (callback: (tx: typeof prisma) => unknown) => - callback(prisma), - ); - return { - deps: { prisma, secrets: { put: vi.fn(), load: vi.fn() } } as unknown as VoiceDeps, - create, - update, - updateMany: prisma.spaceVoicePreference.updateMany, - }; - } - - it("stores the override without changing the selected voice", async () => { - const { deps, update, updateMany } = speechDeps({ - id: "pref-1", - voiceId: "voice-1", - isDefault: false, - }); - - await expect( - updateVoiceSpeechModel(deps, actor, { provider: "fish-audio", speechModel: " s1 " }), - ).resolves.toMatchObject({ - provider: "fish-audio", - voiceId: "voice-1", - speechModel: "s1", - isDefault: false, - }); - expect(update).toHaveBeenCalledWith({ - where: { id: "pref-1" }, - data: { speechModel: "s1" }, - }); - expect(updateMany).not.toHaveBeenCalled(); - }); - - it("clears the override when the model is blank", async () => { - const { deps, update } = speechDeps({ id: "pref-1", voiceId: "voice-1", isDefault: true }); - - await expect( - updateVoiceSpeechModel(deps, actor, { provider: "fish-audio", speechModel: " " }), - ).resolves.toMatchObject({ speechModel: "" }); - expect(update).toHaveBeenCalledWith({ - where: { id: "pref-1" }, - data: { speechModel: null }, - }); - }); - - it("stores a model before a voice is chosen without replacing the default", async () => { - const { deps, create, update, updateMany } = speechDeps(null); - create.mockResolvedValue({ - isDefault: false, - voiceId: "", - speechModel: "s1", - }); - - await expect( - updateVoiceSpeechModel(deps, actor, { provider: "fish-audio", speechModel: "s1" }), - ).resolves.toMatchObject({ - provider: "fish-audio", - voiceId: "", - speechModel: "s1", - isDefault: false, - }); - expect(create).toHaveBeenCalledWith({ - data: { - spaceId: actor.spaceId, - userId: actor.userId, - credentialId: "cred-1", - speechModel: "s1", - }, - }); - expect(update).not.toHaveBeenCalled(); - expect(updateMany).not.toHaveBeenCalled(); - }); - - it("rejects speech models for other providers before writing", async () => { - const { deps, update } = speechDeps({ id: "pref-1", voiceId: "voice-1", isDefault: true }); - - await expect( - updateVoiceSpeechModel(deps, actor, { provider: "elevenlabs", speechModel: "s1" }), - ).rejects.toThrow("Speech model applies to Fish Audio."); - expect(update).not.toHaveBeenCalled(); - }); -}); - -describe("synthesizeVoice", () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("sends the speech model stored on that connection", async () => { - const synthesize = vi - .fn() - .mockResolvedValue({ bytes: new Uint8Array(), mimeType: "audio/mpeg" }); - vi.spyOn(adapters, "createVoiceProvider").mockReturnValue({ synthesize } as never); - const prisma = { - spaceVoicePreference: { - findFirst: vi.fn().mockResolvedValue({ - isDefault: true, - voiceId: "voice-1", - speechModel: "s1", - credential: { - id: "cred-1", - userId: actor.userId, - provider: "fish-audio", - secretId: "secret-1", - createdAt: new Date(0), - updatedAt: new Date(0), - }, - }), - }, - secret: { - findFirst: vi.fn().mockResolvedValue({ id: "secret-1", ciphertext: "cipher" }), - }, - }; - const deps = { - prisma, - secrets: { load: vi.fn().mockReturnValue("fish-key"), put: vi.fn() }, - } as unknown as VoiceDeps; - - await synthesizeVoice(deps, actor, { text: "Hello" }); - - expect(synthesize).toHaveBeenCalledWith( - expect.objectContaining({ - text: "Hello", - voiceId: "voice-1", - apiKey: "fish-key", - model: "s1", - }), - expect.anything(), - ); - }); - - it("omits the model when the connection has no override", async () => { - const synthesize = vi - .fn() - .mockResolvedValue({ bytes: new Uint8Array(), mimeType: "audio/mpeg" }); - vi.spyOn(adapters, "createVoiceProvider").mockReturnValue({ synthesize } as never); - const prisma = { - spaceVoicePreference: { - findFirst: vi.fn().mockResolvedValue({ - isDefault: true, - voiceId: "voice-1", - speechModel: null, - credential: { - id: "cred-1", - userId: actor.userId, - provider: "fish-audio", - secretId: "secret-1", - createdAt: new Date(0), - updatedAt: new Date(0), - }, - }), - }, - secret: { - findFirst: vi.fn().mockResolvedValue({ id: "secret-1", ciphertext: "cipher" }), - }, - }; - const deps = { - prisma, - secrets: { load: vi.fn().mockReturnValue("fish-key"), put: vi.fn() }, - } as unknown as VoiceDeps; - - await synthesizeVoice(deps, actor, { text: "Hello" }); - - expect(synthesize.mock.calls[0]?.[0]).toMatchObject({ model: undefined }); - }); -}); diff --git a/apps/api/src/voice.ts b/apps/api/src/voice.ts deleted file mode 100644 index cb14e203..00000000 --- a/apps/api/src/voice.ts +++ /dev/null @@ -1,493 +0,0 @@ -import type { AdapterContext } from "@milo/adapter-kit"; -import { - createVoiceProvider, - type EncryptedSecretStore, - isFishSpeechModelId, - isVoiceProviderId, - listVoiceCatalog, - MAX_SPEAK_CHARS, - MAX_TRANSCRIBE_BYTES, - NoVoiceConfigured, - voiceCatalogEntry, -} from "@milo/adapters"; -import type { Actor, VoiceCredential, VoiceStatus } from "@milo/contracts"; -import { toUtterances } from "@milo/core"; -import { - deleteUnreferencedCredentialSecret, - findDefaultVoiceCredential, - findVoiceCredential, - IsolationError, - newestVoiceCredentialOrder, - Prisma, - type PrismaClient, - selectSpaceVoicePreference, -} from "@milo/db"; -import { getLogger } from "@milo/logging"; -import { ORPCError } from "@orpc/server"; -import type { Context, Hono } from "hono"; -import { readBoundedBody } from "./http-body.js"; -import { withSerializableRetry } from "./serializable-retry.js"; - -export interface VoiceDeps { - prisma: PrismaClient; - secrets: EncryptedSecretStore; -} - -export { listVoiceCatalog }; - -const SPEAK_TIMEOUT_MS = 60_000; -export const MAX_SPEAK_REQUEST_BYTES = 16 * 1024; -export const MAX_TRANSCRIBE_REQUEST_BYTES = 4 * Math.ceil(MAX_TRANSCRIBE_BYTES / 3) + 1024; - -export function voiceContext(actor: Actor, signal?: AbortSignal): AdapterContext { - return { - operationId: "voice", - traceId: "voice", - spaceId: actor.spaceId, - userId: actor.userId, - signal: signal ?? new AbortController().signal, - }; -} - -export function catalogEntry(provider: string) { - return voiceCatalogEntry(provider); -} - -export function toVoiceStatus(cred: { provider: string; voiceId: string } | null): VoiceStatus { - const entry = cred ? catalogEntry(cred.provider) : undefined; - return { - configured: Boolean(cred), - ready: Boolean(cred?.voiceId), - transcribe: Boolean(entry?.transcribe && cred), - provider: cred?.provider ?? null, - voiceId: cred?.voiceId ?? "", - }; -} - -export function toVoiceCredential(row: { - id: string; - provider: string; - isDefault: boolean; - voiceId: string; - speechModel?: string | null; -}): VoiceCredential { - return { - id: row.id, - provider: row.provider, - hasKey: true, - isDefault: row.isDefault, - voiceId: row.voiceId, - speechModel: row.speechModel ?? "", - transcribe: Boolean(catalogEntry(row.provider)?.transcribe), - }; -} - -const FISH_AUDIO_PROVIDER = "fish-audio"; - -/** Empty clears the Fish override. Anything else must be a header-safe model id. */ -export function fishSpeechModelValue(speechModel: string): string | null { - const trimmed = speechModel.trim(); - if (!trimmed) return null; - if (!isFishSpeechModelId(trimmed)) { - throw new ORPCError("BAD_REQUEST", { message: "That speech model id is not valid." }); - } - return trimmed; -} - -export async function loadDefaultVoiceCredential(deps: VoiceDeps, actor: Actor) { - return loadVoiceCredential(deps, actor); -} - -export async function loadVoiceCredential(deps: VoiceDeps, actor: Actor, provider?: string) { - const cred = provider - ? await findVoiceCredential(deps.prisma, actor, provider) - : await findDefaultVoiceCredential(deps.prisma, actor); - if (!cred) return null; - const secret = await deps.prisma.secret.findFirst({ - where: { id: cred.secretId, userId: actor.userId, spaceId: null }, - }); - if (!secret) return null; - return { cred, apiKey: deps.secrets.load(secret.ciphertext, secret.id) }; -} - -export async function resolveVoiceTarget( - deps: VoiceDeps, - actor: Actor, - input: { botId?: string; voiceId?: string }, -) { - let botVoiceId: string | null = null; - if (input.botId) { - const bot = await deps.prisma.bot.findFirst({ - where: { id: input.botId, spaceId: actor.spaceId, userId: actor.userId }, - select: { voiceId: true }, - }); - if (!bot) throw new IsolationError(); - botVoiceId = bot.voiceId; - } - const loaded = await loadDefaultVoiceCredential(deps, actor); - if (!loaded) throw new NoVoiceConfigured("key"); - const voiceId = input.voiceId || botVoiceId || loaded.cred.voiceId; - if (!voiceId) throw new NoVoiceConfigured("voice"); - return { ...loaded, voiceId }; -} - -export async function persistVoiceCredential( - deps: VoiceDeps, - actor: Actor, - input: { - provider: string; - plaintext: string; - voiceId?: string; - speechModel?: string; - signal?: AbortSignal; - }, -): Promise { - if (!isVoiceProviderId(input.provider)) { - throw new ORPCError("BAD_REQUEST", { message: "Unknown voice provider." }); - } - const requestedSpeechModel = - input.provider === FISH_AUDIO_PROVIDER && input.speechModel !== undefined - ? fishSpeechModelValue(input.speechModel) - : undefined; - const provider = createVoiceProvider(input.provider); - const verified = await provider.verify(input.plaintext, voiceContext(actor, input.signal)); - if (!verified.ok) { - throw new ORPCError("BAD_REQUEST", { message: verified.message ?? "That key was rejected." }); - } - let voiceId = input.voiceId?.trim() ?? ""; - if (!voiceId) { - const voices = await provider.listVoices(input.plaintext, voiceContext(actor, input.signal)); - voiceId = voices[0]?.id ?? ""; - } - const stored = await deps.secrets.put(input.plaintext, voiceContext(actor, input.signal)); - const cred = await withSerializableRetry(() => - deps.prisma.$transaction( - async (tx) => { - const existing = await tx.userVoiceCredential.findFirst({ - where: { userId: actor.userId, provider: input.provider }, - orderBy: newestVoiceCredentialOrder, - }); - const secret = await tx.secret.create({ - data: { - id: stored.id, - userId: actor.userId, - spaceId: null, - kind: "voice", - ciphertext: stored.ciphertext, - }, - }); - const credential = !existing - ? await tx.userVoiceCredential.create({ - data: { - userId: actor.userId, - provider: input.provider, - secretId: secret.id, - }, - }) - : await tx.userVoiceCredential.update({ - where: { id: existing.id }, - data: { secretId: secret.id }, - }); - const previousPreference = existing - ? await tx.spaceVoicePreference.findUnique({ - where: { - spaceId_userId_credentialId: { - spaceId: actor.spaceId, - userId: actor.userId, - credentialId: existing.id, - }, - }, - }) - : null; - const selectedVoiceId = voiceId || previousPreference?.voiceId || ""; - const speechModel = - requestedSpeechModel !== undefined - ? requestedSpeechModel - : previousPreference?.speechModel; - await selectSpaceVoicePreference(tx, actor, credential.id, selectedVoiceId, speechModel); - if (existing) { - await deleteUnreferencedCredentialSecret(tx, { - credentialKind: "voice", - credentialId: existing.id, - secretId: existing.secretId, - }); - } - return { - ...credential, - isDefault: true, - voiceId: selectedVoiceId, - speechModel: speechModel ?? "", - }; - }, - { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, - ), - ); - return toVoiceCredential(cred); -} - -export async function disconnectVoiceCredential( - deps: VoiceDeps, - actor: Actor, - input: { provider: string }, -): Promise<{ ok: true }> { - const provider = input.provider.trim(); - if (!provider) { - throw new ORPCError("BAD_REQUEST", { message: "Unknown voice provider." }); - } - await withSerializableRetry(() => - deps.prisma.$transaction( - async (tx) => { - const existing = await tx.userVoiceCredential.findMany({ - where: { userId: actor.userId, provider }, - }); - if (existing.length === 0) return; - const ids = existing.map((row) => row.id); - await tx.spaceVoicePreference.deleteMany({ - where: { userId: actor.userId, credentialId: { in: ids } }, - }); - await tx.userVoiceCredential.deleteMany({ - where: { userId: actor.userId, id: { in: ids } }, - }); - for (const row of existing) { - await deleteUnreferencedCredentialSecret(tx, { - credentialKind: "voice", - credentialId: row.id, - secretId: row.secretId, - }); - } - }, - { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, - ), - ); - return { ok: true as const }; -} - -export async function updateVoiceSpeechModel( - deps: VoiceDeps, - actor: Actor, - input: { provider: string; speechModel: string }, -): Promise { - if (input.provider !== FISH_AUDIO_PROVIDER) { - throw new ORPCError("BAD_REQUEST", { message: "Speech model applies to Fish Audio." }); - } - const speechModel = fishSpeechModelValue(input.speechModel); - return withSerializableRetry(() => - deps.prisma.$transaction( - async (tx) => { - const found = await tx.userVoiceCredential.findFirst({ - where: { userId: actor.userId, provider: input.provider }, - orderBy: newestVoiceCredentialOrder, - }); - if (!found) { - throw new ORPCError("BAD_REQUEST", { message: "Connect a voice provider first." }); - } - const where = { - spaceId_userId_credentialId: { - spaceId: actor.spaceId, - userId: actor.userId, - credentialId: found.id, - }, - }; - const preference = await tx.spaceVoicePreference.findUnique({ where }); - if (!preference) { - // Remember the model without taking the default. Another provider may - // already be selected, and this row still has no voice. - if (speechModel === null) { - return toVoiceCredential({ ...found, isDefault: false, voiceId: "", speechModel: "" }); - } - const created = await tx.spaceVoicePreference.create({ - data: { - spaceId: actor.spaceId, - userId: actor.userId, - credentialId: found.id, - speechModel, - }, - }); - return toVoiceCredential({ - ...found, - isDefault: created.isDefault, - voiceId: created.voiceId, - speechModel: created.speechModel, - }); - } - const updated = await tx.spaceVoicePreference.update({ - where: { id: preference.id }, - data: { speechModel }, - }); - return toVoiceCredential({ - ...found, - isDefault: preference.isDefault, - voiceId: preference.voiceId, - speechModel: updated.speechModel, - }); - }, - { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, - ), - ); -} - -export async function prepareVoice( - deps: VoiceDeps, - actor: Actor, - input: { text: string; voiceId?: string; botId?: string }, -) { - try { - await resolveVoiceTarget(deps, actor, input); - } catch (error) { - if (error instanceof NoVoiceConfigured) { - return { ready: false, utterances: [] as string[] }; - } - throw error; - } - return { ready: true, utterances: toUtterances(input.text) }; -} - -export async function synthesizeVoice( - deps: VoiceDeps, - actor: Actor, - input: { text: string; voiceId?: string; botId?: string; signal?: AbortSignal }, -) { - const target = await resolveVoiceTarget(deps, actor, input); - const text = input.text.trim(); - if (!text) throw new ORPCError("BAD_REQUEST", { message: "Nothing to speak." }); - if (text.length > MAX_SPEAK_CHARS) { - throw new ORPCError("BAD_REQUEST", { message: "That utterance is too long to speak." }); - } - const provider = createVoiceProvider(target.cred.provider); - return provider.synthesize( - { - text, - voiceId: target.voiceId, - apiKey: target.apiKey, - model: target.cred.speechModel || undefined, - signal: input.signal, - }, - voiceContext(actor, input.signal), - ); -} - -export async function transcribeVoice( - deps: VoiceDeps, - actor: Actor, - input: { audio: Uint8Array; mimeType: string; signal?: AbortSignal }, -) { - const loaded = await loadDefaultVoiceCredential(deps, actor); - if (!loaded) throw new NoVoiceConfigured("key"); - const provider = createVoiceProvider(loaded.cred.provider); - if (!provider.transcribe) { - throw new ORPCError("BAD_REQUEST", { - message: "This voice provider does not transcribe audio. Use on-device dictation instead.", - }); - } - if (input.audio.byteLength === 0 || input.audio.byteLength > MAX_TRANSCRIBE_BYTES) { - throw new ORPCError("BAD_REQUEST", { message: "That recording is empty or too large." }); - } - return provider.transcribe( - { - audio: input.audio, - mimeType: input.mimeType || "audio/webm", - apiKey: loaded.apiKey, - signal: input.signal, - }, - voiceContext(actor, input.signal), - ); -} - -export function mountVoiceHttpRoutes( - app: Hono, - deps: VoiceDeps, - authenticate: (c: Context) => Promise, -) { - app.post("/api/voice/speak", async (c) => { - const actor = await authenticate(c); - if (!actor) return c.json({ error: "Unauthorized" }, 401); - const raw = await readBoundedBody(c.req.raw, MAX_SPEAK_REQUEST_BYTES); - if (raw === null) return c.json({ error: "Request body is too large." }, 413); - const body = parseVoiceRequestBody(raw); - try { - const clip = await synthesizeVoice(deps, actor, { - text: String((body as { text?: unknown }).text ?? ""), - voiceId: optionalString((body as { voiceId?: unknown }).voiceId), - botId: optionalString((body as { botId?: unknown }).botId), - signal: AbortSignal.any( - [c.req.raw.signal, AbortSignal.timeout(SPEAK_TIMEOUT_MS)].filter( - Boolean, - ) as AbortSignal[], - ), - }); - // Copy into a fresh ArrayBuffer-backed view: DOM-lib BodyInit rejects - // Uint8Array since TS 5.7. - return new Response(new Uint8Array(clip.bytes), { - headers: { - "content-type": clip.mimeType, - "cache-control": "no-store", - }, - }); - } catch (error) { - return voiceHttpError(c, error); - } - }); - - app.post("/api/voice/transcribe", async (c) => { - const actor = await authenticate(c); - if (!actor) return c.json({ error: "Unauthorized" }, 401); - const raw = await readBoundedBody(c.req.raw, MAX_TRANSCRIBE_REQUEST_BYTES); - if (raw === null) return c.json({ error: "Request body is too large." }, 413); - const body = parseVoiceRequestBody(raw); - const audioBase64 = String((body as { audioBase64?: unknown }).audioBase64 ?? ""); - try { - const audio = decodeAudioBase64(audioBase64); - const result = await transcribeVoice(deps, actor, { - audio, - mimeType: String((body as { mimeType?: unknown }).mimeType ?? "audio/webm"), - signal: c.req.raw.signal, - }); - return c.json({ text: result.text }); - } catch (error) { - return voiceHttpError(c, error); - } - }); -} - -function parseVoiceRequestBody(raw: string): Record { - try { - const parsed: unknown = JSON.parse(raw); - return parsed && typeof parsed === "object" && !Array.isArray(parsed) - ? (parsed as Record) - : {}; - } catch { - return {}; - } -} - -function optionalString(value: unknown): string | undefined { - return typeof value === "string" && value.trim() ? value.trim() : undefined; -} - -function decodeAudioBase64(value: string): Uint8Array { - if (!value.trim()) throw new ORPCError("BAD_REQUEST", { message: "Recording is empty." }); - try { - return new Uint8Array(Buffer.from(value, "base64")); - } catch { - throw new ORPCError("BAD_REQUEST", { message: "Recording is not valid audio." }); - } -} - -function voiceHttpError(c: Context, error: unknown) { - if (error instanceof IsolationError) { - return c.json({ error: "Resource not found" }, 404); - } - if (error instanceof NoVoiceConfigured) { - return c.json({ error: error.message }, 409); - } - if (error instanceof ORPCError) { - const code = String(error.code ?? "BAD_REQUEST"); - const status = - code === "UNAUTHORIZED" ? 401 : code === "NOT_FOUND" ? 404 : code === "CONFLICT" ? 409 : 400; - return c.json({ error: error.message }, status); - } - const message = error instanceof Error ? error.message : "Voice request failed."; - // Message only: request bodies, keys and audio never reach the log. - getLogger().warn("voice request failed", { route: c.req.path, reason: message }); - return c.json({ error: message }, 502); -} diff --git a/apps/desktop/src/session-permissions.test.ts b/apps/desktop/src/session-permissions.test.ts index c5fe0f23..d7b81e9b 100644 --- a/apps/desktop/src/session-permissions.test.ts +++ b/apps/desktop/src/session-permissions.test.ts @@ -70,12 +70,14 @@ describe("desktop session permissions", () => { "http://localhost:5173/chat", "http://[::1]:5173/chat", "https://192.168.1.20:3100/chat", - ])("preserves microphone, notifications and copy in the connected app at %s", (url) => { + ])("preserves notifications and copy in the connected app at %s", (url) => { const policy = policyFixture(url); - for (const permission of ["media", "notifications", "clipboard-sanitized-write"] as const) { + for (const permission of ["notifications", "clipboard-sanitized-write"] as const) { expect(policy.request(permission)).toBe(true); expect(policy.check(permission)).toBe(true); } + expect(policy.request("media")).toBe(false); + expect(policy.check("media")).toBe(false); }); it.each([ @@ -114,9 +116,11 @@ describe("desktop session permissions", () => { it("denies both same-origin and third-party subframes", () => { const policy = policyFixture(); for (const requestingUrl of [appUrl, providerUrl]) { - expect(policy.request("media", { requestingUrl, isMainFrame: false })).toBe(false); - expect(policy.check("media", { requestingUrl, isMainFrame: false })).toBe(false); - expect(policy.check("media", { requestingUrl, isMainFrame: false }, null)).toBe(false); + expect(policy.request("notifications", { requestingUrl, isMainFrame: false })).toBe(false); + expect(policy.check("notifications", { requestingUrl, isMainFrame: false })).toBe(false); + expect(policy.check("notifications", { requestingUrl, isMainFrame: false }, null)).toBe( + false, + ); } }); @@ -135,34 +139,15 @@ describe("desktop session permissions", () => { ])("rejects untrusted or opaque requesting origins: %s", (url) => { const policy = policyFixture(); expect(policy.request("media", { requestingUrl: url })).toBe(false); - expect(policy.request("media", { securityOrigin: url })).toBe(false); + expect(policy.request("notifications", { requestingUrl: url })).toBe(false); expect(policy.check("media", {}, policy.contents, url)).toBe(false); - expect(policy.check("media", { requestingUrl: url })).toBe(false); - expect(policy.check("media", { securityOrigin: url })).toBe(false); - expect(policy.check("media", { embeddingOrigin: url })).toBe(false); - }); - - it.each([undefined, [], ["video"], ["audio", "video"], ["unknown"]])( - "rejects camera and ambiguous media requests: %j", - (mediaTypes) => { - expect(policyFixture().request("media", { mediaTypes })).toBe(false); - }, - ); - - it.each([undefined, "video", "unknown"])("rejects media checks for %s", (mediaType) => { - expect(policyFixture().check("media", { mediaType })).toBe(false); - }); - - it("fails closed when frame or media origin metadata is missing", () => { - const policy = policyFixture(); - expect(policy.request("media", { securityOrigin: undefined })).toBe(false); - expect(policy.request("media", { requestingUrl: undefined })).toBe(false); - expect(policy.request("media", { isMainFrame: undefined })).toBe(false); - expect(policy.check("media", { requestingUrl: undefined })).toBe(false); - expect(policy.check("media", { isMainFrame: undefined })).toBe(false); + expect(policy.check("notifications", {}, policy.contents, url)).toBe(false); + expect(policy.check("notifications", { requestingUrl: url })).toBe(false); + expect(policy.check("notifications", { embeddingOrigin: url })).toBe(false); }); it.each([ + "media", "clipboard-read", "display-capture", "geolocation", @@ -201,20 +186,20 @@ describe("desktop session permissions", () => { it("denies setup and storage probes before an app exists", () => { const policy = policyFixture(); policy.setApp(null); - expect(policy.request()).toBe(false); - expect(policy.check()).toBe(false); + expect(policy.request("notifications")).toBe(false); + expect(policy.check("notifications")).toBe(false); expect(policy.check("notifications", { embeddingOrigin: appUrl }, null)).toBe(false); }); it("revokes grants if the app is destroyed or navigates to another origin", () => { const policy = policyFixture(); vi.mocked(policy.contents.getURL).mockReturnValue(providerUrl); - expect(policy.request()).toBe(false); - expect(policy.check()).toBe(false); + expect(policy.request("notifications")).toBe(false); + expect(policy.check("notifications")).toBe(false); vi.mocked(policy.contents.getURL).mockReturnValue(appUrl); vi.mocked(policy.contents.isDestroyed).mockReturnValue(true); - expect(policy.request()).toBe(false); - expect(policy.check()).toBe(false); + expect(policy.request("notifications")).toBe(false); + expect(policy.check("notifications")).toBe(false); }); it.each(["data:text/html,example", "file:///example.html", "not a url"])( @@ -223,8 +208,8 @@ describe("desktop session permissions", () => { const policy = policyFixture(); policy.setApp({ webContents: policy.contents, url }); vi.mocked(policy.contents.getURL).mockReturnValue(url); - expect(policy.request()).toBe(false); - expect(policy.check()).toBe(false); + expect(policy.request("notifications")).toBe(false); + expect(policy.check("notifications")).toBe(false); }, ); @@ -232,20 +217,20 @@ describe("desktop session permissions", () => { const policy = policyFixture(); const nextContents = { ...policy.contents, getURL: () => providerUrl } as WebContents; policy.setApp({ webContents: nextContents, url: providerUrl }); - expect(policy.request()).toBe(false); - expect(policy.check()).toBe(false); + expect(policy.request("notifications")).toBe(false); + expect(policy.check("notifications")).toBe(false); expect(policy.check("notifications", { embeddingOrigin: appUrl }, null)).toBe(false); policy.setApp({ webContents: policy.contents, url: appUrl }); - expect(policy.request()).toBe(true); - expect(policy.check()).toBe(true); + expect(policy.request("notifications")).toBe(true); + expect(policy.check("notifications")).toBe(true); }); it("does not grant permissions through a different session partition", () => { const policy = policyFixture(); const other = policyFixture(); policy.setApp({ webContents: other.contents, url: appUrl }); - expect(policy.request("media", {}, other.contents)).toBe(false); - expect(policy.check("media", {}, other.contents)).toBe(false); + expect(policy.request("notifications", {}, other.contents)).toBe(false); + expect(policy.check("notifications", {}, other.contents)).toBe(false); expect(policy.check("notifications", { embeddingOrigin: appUrl }, null)).toBe(false); }); }); diff --git a/apps/desktop/src/session-permissions.ts b/apps/desktop/src/session-permissions.ts index 0f51fbee..a258e852 100644 --- a/apps/desktop/src/session-permissions.ts +++ b/apps/desktop/src/session-permissions.ts @@ -46,17 +46,6 @@ export function installSessionPermissions( return; } - if (permission === "media") { - // Dictation needs only the microphone. OS consent still applies after this grant. - callback( - "securityOrigin" in details && - httpOrigin(details.securityOrigin) === app.origin && - "mediaTypes" in details && - (details.mediaTypes?.length ?? 0) > 0 && - details.mediaTypes?.every((type) => type === "audio") === true, - ); - return; - } callback(permission === "notifications" || permission === "clipboard-sanitized-write"); }); @@ -84,7 +73,6 @@ export function installSessionPermissions( return false; } - if (permission === "media") return details.mediaType === "audio"; return permission === "notifications" || permission === "clipboard-sanitized-write"; }); } diff --git a/apps/mobile/.maestro/screenshots.yaml b/apps/mobile/.maestro/screenshots.yaml index c59b074c..b3c49b59 100644 --- a/apps/mobile/.maestro/screenshots.yaml +++ b/apps/mobile/.maestro/screenshots.yaml @@ -107,12 +107,6 @@ tags: direction: DOWN - takeScreenshot: "11b-all-providers" -- openLink: "rakazo:///voice" -- extendedWaitUntil: - visible: "Scripted" - timeout: 10000 -- takeScreenshot: "12-voice" - - openLink: "rakazo:///integrations" - extendedWaitUntil: visible: "Search apps" diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 20849a13..bfc21eb5 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -19,20 +19,6 @@ ], "expo-router", "expo-secure-store", - [ - "expo-audio", - { - "enableBackgroundPlayback": false, - "microphonePermission": "Milo uses the microphone for voice calls with your bots." - } - ], - [ - "expo-speech-recognition", - { - "speechRecognitionPermission": "Milo turns your speech into messages during voice calls.", - "microphonePermission": "Milo uses the microphone for voice calls with your bots." - } - ], "expo-localization", "@react-native-vector-icons/ionicons", "@react-native-vector-icons/material-design-icons", @@ -47,8 +33,7 @@ "expo-image-picker", { "photosPermission": "Milo uses your photo library so you can attach images to a bot message.", - "cameraPermission": "Milo uses the camera so you can attach photos to a bot message.", - "microphonePermission": "Milo uses the microphone for voice calls with your bots." + "cameraPermission": "Milo uses the camera so you can attach photos to a bot message." } ], "expo-sharing", diff --git a/apps/mobile/app/(tabs)/account/index.tsx b/apps/mobile/app/(tabs)/account/index.tsx index 130730e3..b2eee775 100644 --- a/apps/mobile/app/(tabs)/account/index.tsx +++ b/apps/mobile/app/(tabs)/account/index.tsx @@ -32,7 +32,7 @@ import { native, useResolvedAppearance, useThemedStyles } from "../../../lib/nat import type { AccountUiLocale } from "../../../lib/ui-locale"; import { ACCOUNT_UI_LOCALES, UI_LOCALE_LABELS } from "../../../lib/ui-locale"; -/** Settings is Usage, General, Allow list and Updates. Voice stays until thread C removes it. */ +/** Settings is Usage, General, Allow list and Updates. */ export default function Account() { const { t, locale } = useI18n(); const colorScheme = useResolvedAppearance(); @@ -127,7 +127,6 @@ export default function Account() { onPress={() => router.push("/allow-list")} styles={styles} /> - router.push("/voice")} styles={styles} /> {t("General")} diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index 73de6702..ef93c03a 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -113,7 +113,6 @@ export default function Layout() { - ([]); const [catalog, setCatalog] = useState([]); const [me, setMe] = useState(null); @@ -80,7 +74,6 @@ export default function BotSettingsScreen() { : "", ); setThinkingLevel(next.thinkingLevel ?? ""); - setAutoSpeak(next.autoSpeak); }) .catch((err) => setError(err instanceof Error ? err.message : t("Could not load bot"))); }, [botId]); @@ -243,7 +236,6 @@ export default function BotSettingsScreen() { modelProvider?: string | null; modelId?: string | null; thinkingLevel?: ThinkingLevel | null; - autoSpeak?: boolean; } = { botId }; if (profile.name !== bot.name) input.name = profile.name; if (profile.title !== bot.title) input.title = profile.title; @@ -266,7 +258,6 @@ export default function BotSettingsScreen() { ? ((thinkingLevel || null) as ThinkingLevel | null) : null; } - if (autoSpeak !== bot.autoSpeak) input.autoSpeak = autoSpeak; if (computerMode !== bot.computerMode) { await rpc( "bots/setComputer", @@ -380,25 +371,6 @@ export default function BotSettingsScreen() { ))} - - - {t("Read replies aloud")} - - - {/* Advanced only picks a model, which the agent runtime may supply itself. */} {me?.modelManaged ? null : ( <> diff --git a/apps/mobile/app/thread.tsx b/apps/mobile/app/thread.tsx index 2acc1548..1f5b70ed 100644 --- a/apps/mobile/app/thread.tsx +++ b/apps/mobile/app/thread.tsx @@ -7,13 +7,11 @@ import type { Routine, } from "@milo/contracts"; import { canReactToThreadMessage, MESSAGE_REACTIONS, type MessageReaction } from "@milo/contracts"; -import type { ThreadItem } from "@milo/core"; +import type { ComposerMention, SlashActionId } from "@milo/core"; import { abortableDelay, attachmentsForThread, buildComposerMentionOptions, - type ComposerMention, - groupVoiceChats, isApprovalAskBlock, isRunTerminalEvent, isSecretAskBlock, @@ -23,7 +21,6 @@ import { projectMessageReactions, resolveComposerSendPlan, SLASH_ACTIONS, - type SlashActionId, selectedAskActionLabel, serializeComposerPrompt, truncateSlashDescription, @@ -81,19 +78,20 @@ import { } from "../components/markdown-artifact-preview"; import { NativeSymbol } from "../components/native-symbol"; import { UsageLimitNotice } from "../components/usage-limit-notice"; -import { VoiceChatCard } from "../components/VoiceChatCard"; import { WorkingIndicator } from "../components/WorkingIndicator"; +import type { + MobileBot, + MobileGroup, + MobileMessage, + MobileMessagePage, + MobileSnapshot, +} from "../lib/api"; import { applyMobileThreadEvent, blockText, copyableMobileMessageText, currentApiBase, loadSessionToken, - type MobileBot, - type MobileGroup, - type MobileMessage, - type MobileMessagePage, - type MobileSnapshot, mergeMobileSnapshot, mobileThreadRefreshResult, prependMobileMessagePage, @@ -103,12 +101,9 @@ import { subscribeThread, } from "../lib/api"; import { mobileTokens } from "../lib/appearance"; -import { type MobileArtifactTarget, openMobileArtifact } from "../lib/artifact-open"; -import { nextAutoSpeakAction } from "../lib/auto-speak"; +import type { MobileArtifactTarget } from "../lib/artifact-open"; +import { openMobileArtifact } from "../lib/artifact-open"; import { confirmDeleteBot } from "../lib/bot-lifecycle"; -import { setCallProviderTranscribe, startCall, useCallSession } from "../lib/call-session"; -import { loadDeviceVoiceEnabled } from "../lib/device-voice"; -import { available as dictationAvailable } from "../lib/dictation"; import { dateLocaleForUi, t, useI18n } from "../lib/i18n"; import { saveLastBotId } from "../lib/last-bot"; import { @@ -130,24 +125,15 @@ import { threadSpaceRequest, threadSpaceSwitchResult, } from "../lib/notification-open"; -import { - type PickedAttachment, - pickDocuments, - pickFromLibrary, - takePhoto, -} from "../lib/pick-attachments"; +import type { PickedAttachment } from "../lib/pick-attachments"; +import { pickDocuments, pickFromLibrary, takePhoto } from "../lib/pick-attachments"; import { threadRefreshDelayMs } from "../lib/refresh"; import { getCachedResponseStreamingEnabled, subscribeResponseStreaming, } from "../lib/response-streaming"; -import { - type ThreadScrollAction, - ThreadScrollBehavior, - type ThreadScrollState, -} from "../lib/thread-scroll"; -import { speakText } from "../lib/voice"; -import { probeProviderTranscribe, resolveVoiceCallPlan } from "../lib/voice-call-entry"; +import type { ThreadScrollAction, ThreadScrollState } from "../lib/thread-scroll"; +import { ThreadScrollBehavior } from "../lib/thread-scroll"; type PendingAttachment = PickedAttachment & { threadKey: string }; type AskAction = NonNullable["actions"]>[number]; @@ -294,10 +280,7 @@ function Thread() { }>(); const requestedThreadId = typeof threadId === "string" && threadId ? threadId : undefined; const inGroup = Boolean(groupId); - const call = useCallSession(); - const onCall = Boolean(botId) && call?.botId === botId; - const voiceCallStarting = useRef(false); - const scroll = useRef>>(null); + const scroll = useRef>(null); const pinnedScroll = useRef(null); const scrollBehavior = useRef(new ThreadScrollBehavior()); const userDragging = useRef(false); @@ -326,8 +309,6 @@ function Thread() { const mentionBotsRefreshGeneration = useRef(0); const mentionBotsAppliedGeneration = useRef(0); const readVisibleTarget = useRef(null); - const autoSpoken = useRef(null); - const autoSpokenBotId = useRef(null); const threadKey = groupId ?? botId; const [threadScrollState, setThreadScrollState] = useState(() => scrollBehavior.current.state(), @@ -482,35 +463,6 @@ function Thread() { }, [inGroup, snap?.activeRuns, snap?.members, snap?.run]); const working = inGroup ? workingGroupBots.length > 0 : isWorkingStatus(currentBotStatus); - const speakFinishedReply = useCallback(() => { - if (!botId || inGroup || !currentBot) return; - const decision = nextAutoSpeakAction({ - botId: currentBot.id, - autoSpeak: currentBot.autoSpeak, - focused: AppState.currentState === "active" && navigation.isFocused(), - snapshotReady: snap?.botId === currentBot.id, - lastSpokenBotId: autoSpokenBotId.current, - lastSpokenMessageId: autoSpoken.current, - runStatus: snap?.run?.status, - messages: snap?.messages ?? [], - }); - if (decision.action === "seed") { - autoSpokenBotId.current = currentBot.id; - autoSpoken.current = decision.messageId; - return; - } - if (decision.action !== "speak") return; - autoSpokenBotId.current = currentBot.id; - autoSpoken.current = decision.messageId; - void speakText(decision.text, { botId: currentBot.id }).catch(() => undefined); - }, [botId, inGroup, currentBot, navigation, snap?.botId, snap?.messages, snap?.run?.status]); - - useEffect(() => { - speakFinishedReply(); - const appState = AppState.addEventListener("change", speakFinishedReply); - return () => appState.remove(); - }, [speakFinishedReply]); - useEffect(() => { void rpc("agentSkills/list") .then(setAgentSkills) @@ -932,11 +884,10 @@ function Thread() { } void refreshMentionBots(); markReadIfVisible(); - speakFinishedReply(); return () => { void setOpenNotificationThread(null).catch(() => undefined); }; - }, [botId, markReadIfVisible, notificationThreadId, refreshMentionBots, speakFinishedReply]), + }, [botId, markReadIfVisible, notificationThreadId, refreshMentionBots]), ); useEffect(() => { @@ -1149,14 +1100,6 @@ function Thread() { }); } - // An empty composer offers a call in the send button's place; typing swaps it back. - const showCall = - Boolean(botId) && - !onCall && - draft.trim().length === 0 && - !selectedSkill && - selectedMentions.length === 0 && - activePendingAttachments.length === 0; const canSend = Boolean(draft.trim()) || selectedSkill !== null || @@ -1339,62 +1282,6 @@ function Thread() { [router], ); - const speak = useCallback( - (message: MobileMessage) => - void speakMessage(message.botId ?? botId ?? snap?.members?.[0]?.botId ?? "", message).catch( - (err) => - Alert.alert(t("Could not speak"), err instanceof Error ? err.message : t("Try again.")), - ), - [botId, snap?.members], - ); - - async function startVoiceCall() { - const targetBotId = botId; - if (!targetBotId || voiceCallStarting.current) return; - voiceCallStarting.current = true; - const loadVoiceStatus = () => rpc<{ ready: boolean; transcribe: boolean }>("voice/status"); - try { - const plan = await resolveVoiceCallPlan({ - loadDeviceVoiceEnabled, - dictationAvailable, - loadVoiceStatus, - }); - if (activeBotId.current !== targetBotId) return; - if (plan.kind === "settings") { - router.push("/voice"); - return; - } - if (plan.kind === "dictation") { - Alert.alert( - t("Calls need transcription"), - t("Allow speech recognition in Settings, or connect ElevenLabs, OpenAI, or Fish Audio."), - [ - { text: t("Not now"), style: "cancel" }, - { text: t("Open Voice"), onPress: () => router.push("/voice") }, - ], - ); - return; - } - const startedCallId = startCall({ - botId: targetBotId, - botName: displayName ?? t("Bot"), - botColor: mentionBots.find((bot) => bot.id === targetBotId)?.color, - transcribe: plan.transcribe, - }); - if (plan.kind === "device") { - void probeProviderTranscribe(loadVoiceStatus) - .then((enabled) => { - if (enabled) setCallProviderTranscribe(true, startedCallId); - }) - .catch(() => undefined); - } - } catch { - if (activeBotId.current === targetBotId) router.push("/voice"); - } finally { - voiceCallStarting.current = false; - } - } - function showAttachMenu() { Alert.alert(t("Attach"), undefined, [ { @@ -1446,8 +1333,7 @@ function Thread() { ) ? (snap.run.error ?? null) : null; - // Group calls in reading order, then reverse for the inverted list. - const liveItems = useMemo(() => groupVoiceChats(visibleMessages).reverse(), [visibleMessages]); + const liveItems = useMemo(() => [...visibleMessages].reverse(), [visibleMessages]); const messagesById = useMemo( () => new Map((snap?.messages ?? []).map((message) => [message.id, message])), [snap?.messages], @@ -1525,10 +1411,6 @@ function Thread() { }, ] : []), - // The call already reads replies aloud; a second voice would talk over it. - ...(message.role === "bot" && !onCall && blockText(message) - ? [{ name: "speak", text: t("Speak message"), onPress: () => void speak(message) }] - : []), { name: "copy", text: t("Copy"), @@ -1772,7 +1654,7 @@ function Thread() { ref={scroll} data={liveItems} inverted - keyExtractor={(item) => (item.kind === "voiceChat" ? item.key : item.message.id)} + keyExtractor={(item) => item.id} extraData={answerableAskMessageId} style={{ flex: 1, marginTop: 8 }} maintainVisibleContentPosition={{ minIndexForVisible: 0 }} @@ -1807,15 +1689,7 @@ function Thread() { }} ListFooterComponent={loadEarlierControl} ListHeaderComponent={workingFooter} - renderItem={({ item }) => - item.kind === "voiceChat" ? ( - - - - ) : ( - renderMessageRow(item.message) - ) - } + renderItem={({ item }) => renderMessageRow(item)} /> )} {!showPinnedPage && threadScrollState.detached ? ( @@ -2228,51 +2102,27 @@ function Thread() { }} /> - {showCall ? ( - void startVoiceCall()} - style={{ - width: 44, - height: 44, - borderRadius: 22, - borderWidth: 1, - borderColor: tokens.border, - alignItems: "center", - justifyContent: "center", - }} - > - - - ) : null} - {showCall ? null : ( - void send()} - style={{ - backgroundColor: tokens.primary, - borderRadius: 22, - width: 44, - height: 44, - alignItems: "center", - justifyContent: "center", - opacity: sending || !canSend ? 0.5 : 1, - }} - > - - - )} + void send()} + style={{ + backgroundColor: tokens.primary, + borderRadius: 22, + width: 44, + height: 44, + alignItems: "center", + justifyContent: "center", + opacity: sending || !canSend ? 0.5 : 1, + }} + > + + {working ? ( member.botId === botId)?.name; } -async function speakMessage(botId: string, message: MobileMessage) { - const text = blockText(message); - if (!text.trim()) return; - if (!(await speakText(text, { botId }))) { - throw new Error(t("Add a voice provider in Voice settings.")); - } -} - type MessageActionProps = Pick< TextProps, "onLongPress" | "accessibilityActions" | "onAccessibilityAction" diff --git a/apps/mobile/app/voice.tsx b/apps/mobile/app/voice.tsx deleted file mode 100644 index fc845052..00000000 --- a/apps/mobile/app/voice.tsx +++ /dev/null @@ -1,414 +0,0 @@ -import { useFocusEffect } from "expo-router"; -import { useCallback, useRef, useState } from "react"; -import { - ActivityIndicator, - Pressable, - ScrollView, - StyleSheet, - Text, - TextInput, - View, -} from "react-native"; -import { SafeAreaView } from "react-native-safe-area-context"; -import { rpc } from "../lib/api"; -import { mobileTokens } from "../lib/appearance"; -import { loadDeviceVoiceEnabled, saveDeviceVoiceEnabled } from "../lib/device-voice"; -import { useI18n } from "../lib/i18n"; -import { native, useThemedStyles } from "../lib/native"; -import { speakText } from "../lib/voice"; - -type VoiceCatalogEntry = { - id: string; - name: string; - description: string; - transcribe: boolean; -}; -type VoiceCredential = { - id: string; - provider: string; - voiceId: string; - speechModel?: string; -}; -type VoiceStatus = { - configured: boolean; - ready: boolean; - provider: string | null; - voiceId: string; -}; -type VoiceInfo = { id: string; label: string; description?: string }; - -export default function VoiceSettings() { - const styles = useThemedStyles(createVoiceStyles); - const { t } = useI18n(); - const [catalog, setCatalog] = useState([]); - const [credentials, setCredentials] = useState([]); - const [status, setStatus] = useState(null); - const [voices, setVoices] = useState([]); - const [provider, setProvider] = useState(""); - const [apiKey, setApiKey] = useState(""); - const [voiceId, setVoiceId] = useState(""); - const [speechModel, setSpeechModel] = useState(""); - const speechModelSave = useRef(null); - const [deviceVoice, setDeviceVoice] = useState(false); - const [deviceVoiceReady, setDeviceVoiceReady] = useState(false); - const [loading, setLoading] = useState(true); - const [pending, setPending] = useState< - "connect" | "disconnect" | "voice" | "speech" | "test" | "device-voice" | null - >(null); - const [error, setError] = useState(null); - const [notice, setNotice] = useState(null); - const deviceVoiceRevision = useRef(0); - const deviceVoiceSaveInFlight = useRef(false); - - const load = useCallback(async (nextProvider?: string) => { - const [nextCatalog, nextCredentials, nextStatus] = await Promise.all([ - rpc("voice/catalog"), - rpc("voice/credentials"), - rpc("voice/status"), - ]); - const selected = nextProvider || nextStatus.provider || nextCatalog[0]?.id || ""; - setCatalog(nextCatalog); - setCredentials(nextCredentials); - setStatus(nextStatus); - setProvider(selected); - const cred = nextCredentials.find((entry) => entry.provider === selected); - setVoiceId(cred?.voiceId ?? ""); - setSpeechModel(cred?.speechModel ?? ""); - if (cred) { - setVoices(await rpc("voice/voices", { provider: selected })); - } else { - setVoices([]); - } - }, []); - - useFocusEffect( - useCallback(() => { - setLoading(true); - const revision = ++deviceVoiceRevision.current; - void loadDeviceVoiceEnabled() - .then((value) => { - if (deviceVoiceSaveInFlight.current) return; - if (deviceVoiceRevision.current !== revision) return; - setDeviceVoice(value); - setDeviceVoiceReady(true); - }) - .catch((err: unknown) => { - if (deviceVoiceSaveInFlight.current) return; - if (deviceVoiceRevision.current !== revision) return; - setDeviceVoiceReady(true); - setError(err instanceof Error ? err.message : t("Could not load voice settings")); - }); - void load() - .catch((err: unknown) => - setError(err instanceof Error ? err.message : t("Could not load voice settings")), - ) - .finally(() => setLoading(false)); - }, [load, t]), - ); - - async function toggleDeviceVoice() { - if (pending !== null || !deviceVoiceReady) return; - const next = !deviceVoice; - deviceVoiceSaveInFlight.current = true; - deviceVoiceRevision.current++; - setDeviceVoice(next); - setPending("device-voice"); - setError(null); - try { - await saveDeviceVoiceEnabled(next); - } catch { - setDeviceVoice(!next); - setError(t("Could not save that preference")); - } finally { - deviceVoiceSaveInFlight.current = false; - deviceVoiceRevision.current++; - setPending(null); - } - } - - const selected = catalog.find((entry) => entry.id === provider); - const credential = credentials.find((entry) => entry.provider === provider); - - async function connect() { - if (!selected || apiKey.trim().length < 8) return; - setPending("connect"); - setError(null); - try { - await rpc("voice/connect", { - provider: selected.id, - apiKey: apiKey.trim(), - voiceId: voiceId || undefined, - ...(selected.id === "fish-audio" ? { speechModel: speechModel.trim() } : {}), - }); - setApiKey(""); - await load(selected.id); - setNotice(t("Connected {name}.", { name: selected.name })); - } catch (err) { - setError(err instanceof Error ? err.message : t("Could not connect")); - } finally { - setPending(null); - } - } - - async function disconnect() { - if (!credential) return; - setPending("disconnect"); - setError(null); - setNotice(null); - try { - await rpc("voice/disconnect", { provider: credential.provider }); - setApiKey(""); - await load(credential.provider); - } catch (err) { - setError(err instanceof Error ? err.message : t("Could not disconnect")); - } finally { - setPending(null); - } - } - - async function saveSpeechModel() { - if (!credential || selected?.id !== "fish-audio" || pending !== null) return; - const next = speechModel.trim(); - if (next === (credential.speechModel ?? "")) return; - if (speechModelSave.current === next) return; - speechModelSave.current = next; - setPending("speech"); - setError(null); - try { - const saved = await rpc("voice/setSpeechModel", { - provider: selected.id, - speechModel: next, - }); - setSpeechModel(saved.speechModel ?? ""); - setCredentials((current) => - current.map((entry) => (entry.id === saved.id ? { ...entry, ...saved } : entry)), - ); - } catch (err) { - setError(err instanceof Error ? err.message : t("Could not save that speech model")); - } finally { - speechModelSave.current = null; - setPending(null); - } - } - - async function chooseVoice(nextVoiceId: string) { - setVoiceId(nextVoiceId); - setPending("voice"); - try { - await rpc("voice/setVoice", { voiceId: nextVoiceId, provider: selected?.id }); - await load(selected?.id); - } catch (err) { - setError(err instanceof Error ? err.message : t("Could not save that voice")); - } finally { - setPending(null); - } - } - - async function testVoice() { - setPending("test"); - setError(null); - try { - const ready = await speakText(t("Hi, this is how I'll sound when I read replies out loud.")); - if (!ready) { - throw new Error(t("Connect a voice provider first.")); - } - } catch (err) { - setError(err instanceof Error ? err.message : t("Could not play a sample")); - } finally { - setPending(null); - } - } - - return ( - - - {loading ? : null} - {error ? {error} : null} - {notice ? {notice} : null} - void toggleDeviceVoice()} - style={[ - styles.card, - deviceVoice && styles.cardActive, - (pending !== null || !deviceVoiceReady) && styles.disabled, - ]} - > - {t("This device")} - - {deviceVoice - ? t("On · Free, works offline") - : t("Your phone's built-in voice. Free, no account needed")} - - - {catalog.map((entry) => { - const connected = credentials.some((cred) => cred.provider === entry.id); - return ( - { - setProvider(entry.id); - setPending("voice"); - void load(entry.id) - .catch((err: unknown) => - setError( - err instanceof Error ? err.message : t("Could not load voice settings"), - ), - ) - .finally(() => setPending(null)); - }} - style={[ - styles.card, - provider === entry.id && styles.cardActive, - pending !== null && styles.disabled, - ]} - > - {entry.name} - - {connected - ? t("Connected") - : entry.transcribe - ? t("Speak + transcribe") - : t("Speak only")} - - - ); - })} - {selected ? ( - <> - - void connect()} - style={[ - styles.button, - (pending !== null || apiKey.trim().length < 8) && styles.disabled, - ]} - > - {credential ? t("Replace key") : t("Connect")} - - {credential ? ( - void disconnect()} - style={[styles.secondary, pending !== null && styles.disabled]} - > - - {pending === "disconnect" ? t("Disconnecting…") : t("Disconnect")} - - - ) : null} - {credential && selected.id === "fish-audio" ? ( - <> - {t("Speech model")} - void saveSpeechModel()} - onSubmitEditing={() => void saveSpeechModel()} - placeholder={t("Optional")} - placeholderTextColor={native.tertiaryLabel} - style={styles.input} - /> - - ) : null} - {voices.length ? ( - - {voices.map((voice) => ( - void chooseVoice(voice.id)} - style={[styles.voiceRow, pending !== null && styles.disabled]} - > - {voice.label} - {voiceId === voice.id ? ✓ : null} - - ))} - - ) : null} - - ) : null} - {deviceVoice || status?.ready ? ( - void testVoice()} - style={styles.secondary} - > - {t("Hear a sample")} - - ) : null} - - - ); -} - -function createVoiceStyles() { - const tokens = mobileTokens(); - return StyleSheet.create({ - screen: { flex: 1, backgroundColor: native.page }, - content: { padding: 20, gap: 10 }, - error: { color: tokens.destructive, marginBottom: 8 }, - notice: { color: tokens.success, marginBottom: 8 }, - card: { - borderRadius: 14, - borderWidth: 1, - borderColor: tokens.border, - padding: 14, - backgroundColor: tokens.card, - }, - cardActive: { borderColor: tokens.ring, backgroundColor: tokens.muted }, - cardTitle: { color: native.label, fontSize: 16 }, - cardMeta: { color: native.tertiaryLabel, marginTop: 4, fontSize: 12 }, - fieldLabel: { color: native.label, marginTop: 16 }, - input: { - marginTop: 8, - borderRadius: 12, - borderWidth: 1, - borderColor: tokens.border, - color: native.label, - paddingHorizontal: 14, - paddingVertical: 12, - }, - button: { - marginTop: 8, - backgroundColor: tokens.primary, - borderRadius: 12, - paddingVertical: 12, - alignItems: "center", - }, - disabled: { opacity: 0.4 }, - buttonLabel: { color: tokens.primaryForeground, fontWeight: "600" }, - voices: { marginTop: 12, borderRadius: 12, borderWidth: 1, borderColor: tokens.border }, - voiceRow: { - flexDirection: "row", - justifyContent: "space-between", - paddingHorizontal: 14, - paddingVertical: 12, - borderBottomWidth: 1, - borderBottomColor: tokens.border, - }, - voiceLabel: { color: native.label }, - check: { color: tokens.success }, - secondary: { marginTop: 16, alignItems: "center" }, - secondaryLabel: { color: native.secondaryLabel, fontSize: 15 }, - }); -} diff --git a/apps/mobile/components/CallCard.tsx b/apps/mobile/components/CallCard.tsx deleted file mode 100644 index c9369d1d..00000000 --- a/apps/mobile/components/CallCard.tsx +++ /dev/null @@ -1,252 +0,0 @@ -import { useRouter } from "expo-router"; -import type { ComponentProps } from "react"; -import { useEffect, useRef, useState } from "react"; -import { Animated, Pressable, StyleSheet, Text, View } from "react-native"; -import { useReducedMotion } from "react-native-reanimated"; -import { useSafeAreaInsets } from "react-native-safe-area-context"; -import type { MobileMe } from "../lib/api"; -import { rpc } from "../lib/api"; -import type { CallPhase } from "../lib/call-session"; -import { endCall, toggleMute, toggleTranscript, useCallSession } from "../lib/call-session"; -import { useI18n } from "../lib/i18n"; -import { useMobileTokens } from "../lib/native"; -import { BotAvatar } from "./bot-avatar"; -import { NativeSymbol } from "./native-symbol"; - -const BARS = [9, 15, 21, 15, 9]; -const TRANSCRIPT_LINES = 4; - -let cachedInitial: string | null = null; - -export function CallCard() { - const call = useCallSession(); - const { t } = useI18n(); - const tokens = useMobileTokens(); - const insets = useSafeAreaInsets(); - const router = useRouter(); - const [initial, setInitial] = useState(cachedInitial ?? ""); - const onCall = Boolean(call); - - useEffect(() => { - if (!onCall || cachedInitial !== null) return; - void rpc("me") - .then((me) => { - cachedInitial = (me.name ?? me.email ?? "").trim().slice(0, 1).toUpperCase(); - setInitial(cachedInitial); - }) - .catch(() => undefined); - }, [onCall]); - - if (!call) return null; - return ( - - - - - router.push({ pathname: "/thread", params: { botId: call.botId, name: call.botName } }) - } - > - - {call.botName} - - - - - {initial} - - - - router.push("/voice")} - /> - - - - - {call.transcriptOpen ? ( - - {call.exchanges.slice(-TRANSCRIPT_LINES).map((exchange, index) => ( - - {exchange.text} - - ))} - {call.caption || call.heard ? ( - - {call.caption || call.heard} - - ) : null} - - ) : null} - - ); -} - -function RoundButton({ - label, - ios, - android, - color, - border, - background, - selected, - onPress, -}: { - label: string; - ios: string; - android: ComponentProps["android"]; - color: string; - border: string; - background?: string; - selected?: boolean; - onPress: () => void; -}) { - return ( - - - - ); -} - -function Waveform({ phase }: { phase: CallPhase }) { - const tokens = useMobileTokens(); - const reduceMotion = useReducedMotion(); - const values = useRef(BARS.map(() => new Animated.Value(0.35))).current; - const still = phase === "thinking" || reduceMotion; - - useEffect(() => { - if (still) { - for (const value of values) value.setValue(0.35); - return; - } - const duration = phase === "speaking" ? 300 : 600; - const loops = values.map((value, index) => - Animated.loop( - Animated.sequence([ - Animated.delay(index * 90), - Animated.timing(value, { toValue: 1, duration, useNativeDriver: true }), - Animated.timing(value, { toValue: 0.35, duration, useNativeDriver: true }), - ]), - ), - ); - for (const loop of loops) loop.start(); - return () => { - for (const loop of loops) loop.stop(); - }; - }, [phase, still, values]); - - return ( - - {BARS.map((height, index) => ( - - ))} - - ); -} - -const styles = StyleSheet.create({ - card: { - position: "absolute", - alignSelf: "center", - width: 320, - borderRadius: 18, - borderWidth: StyleSheet.hairlineWidth, - padding: 12, - shadowOpacity: 0.18, - shadowRadius: 12, - shadowOffset: { width: 0, height: 4 }, - elevation: 6, - zIndex: 50, - }, - row: { flexDirection: "row", alignItems: "center", gap: 10 }, - name: { fontSize: 15, fontWeight: "500", maxWidth: 110, writingDirection: "auto" }, - waveform: { - flex: 1, - flexDirection: "row", - alignItems: "center", - justifyContent: "center", - gap: 3, - }, - initial: { - width: 28, - height: 28, - borderRadius: 14, - alignItems: "center", - justifyContent: "center", - }, - initialText: { fontSize: 13, fontWeight: "600" }, - actions: { flexDirection: "row", justifyContent: "center", gap: 12, marginTop: 12 }, - button: { - width: 44, - height: 44, - borderRadius: 22, - borderWidth: StyleSheet.hairlineWidth, - alignItems: "center", - justifyContent: "center", - }, - transcript: { marginTop: 12, paddingTop: 10, borderTopWidth: StyleSheet.hairlineWidth, gap: 5 }, - line: { fontSize: 13, writingDirection: "auto" }, -}); diff --git a/apps/mobile/components/VoiceChatCard.tsx b/apps/mobile/components/VoiceChatCard.tsx deleted file mode 100644 index 5ce52c2a..00000000 --- a/apps/mobile/components/VoiceChatCard.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import type { VoiceChatGroup } from "@milo/core"; -import { speechFromBlocks, voiceChatDuration, voiceChatSummary } from "@milo/core"; -import { useState } from "react"; -import { Pressable, StyleSheet, Text, View } from "react-native"; -import type { MobileMessage } from "../lib/api"; -import { useI18n } from "../lib/i18n"; -import { useMobileTokens } from "../lib/native"; -import { NativeSymbol } from "./native-symbol"; - -function clock(seconds: number): string { - return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; -} - -/** One call's exchange, collapsed to a card; expanding it shows the transcript. */ -export function VoiceChatCard({ group }: { group: VoiceChatGroup }) { - const { t } = useI18n(); - const tokens = useMobileTokens(); - const [open, setOpen] = useState(false); - const summary = voiceChatSummary(group); - return ( - - setOpen((wasOpen) => !wasOpen)} - style={styles.header} - > - - {t("Voice chat")} - - {clock(voiceChatDuration(group))} - - - - - - {open ? ( - - {group.messages.map((message) => { - // The marker is the card's summary line, never a transcript turn. - if (message === group.marker) return null; - const text = speechFromBlocks(message.blocks).trim(); - if (!text) return null; - return message.role === "user" ? ( - - {text} - - ) : ( - - {text} - - ); - })} - - ) : summary ? ( - - {summary} - - ) : null} - - ); -} - -const styles = StyleSheet.create({ - card: { - alignSelf: "flex-start", - maxWidth: "88%", - borderRadius: 18, - borderWidth: StyleSheet.hairlineWidth, - }, - header: { flexDirection: "row", alignItems: "center", gap: 8, paddingHorizontal: 12, height: 40 }, - title: { fontSize: 15, fontWeight: "500" }, - duration: { fontSize: 13, fontVariant: ["tabular-nums"] }, - chevron: { marginStart: "auto", paddingStart: 8 }, - summary: { paddingHorizontal: 12, paddingBottom: 10, fontSize: 14, writingDirection: "auto" }, - transcript: { paddingHorizontal: 12, paddingBottom: 12, gap: 6 }, - user: { alignSelf: "flex-end", fontSize: 14, textAlign: "right", writingDirection: "auto" }, - bot: { - fontSize: 14, - borderRadius: 12, - paddingHorizontal: 10, - paddingVertical: 7, - overflow: "hidden", - writingDirection: "auto", - }, -}); diff --git a/apps/mobile/lib/android-permissions.test.ts b/apps/mobile/lib/android-permissions.test.ts index 69baa733..cb40a429 100644 --- a/apps/mobile/lib/android-permissions.test.ts +++ b/apps/mobile/lib/android-permissions.test.ts @@ -16,15 +16,24 @@ function readMobileAppConfig(): MobileAppConfig { } describe("Android permission config", () => { - it("does not block microphone permission through expo-image-picker", () => { + it("does not declare voice-only microphone or speech recognition permissions", () => { const plugins = readMobileAppConfig().expo.plugins; const imagePicker = plugins.find( (plugin): plugin is [string, Record] => Array.isArray(plugin) && plugin[0] === "expo-image-picker", ); + const audio = plugins.find( + (plugin) => plugin === "expo-audio" || (Array.isArray(plugin) && plugin[0] === "expo-audio"), + ); + const speechRecognition = plugins.find( + (plugin) => + plugin === "expo-speech-recognition" || + (Array.isArray(plugin) && plugin[0] === "expo-speech-recognition"), + ); expect(imagePicker).toBeDefined(); - expect(typeof imagePicker?.[1].microphonePermission).toBe("string"); - expect(imagePicker?.[1].microphonePermission).not.toBe(""); + expect(imagePicker?.[1].microphonePermission).toBeUndefined(); + expect(audio).toBeUndefined(); + expect(speechRecognition).toBeUndefined(); }); }); diff --git a/apps/mobile/lib/api.test.ts b/apps/mobile/lib/api.test.ts index 23725ce0..6ac2642f 100644 --- a/apps/mobile/lib/api.test.ts +++ b/apps/mobile/lib/api.test.ts @@ -2095,28 +2095,6 @@ describe("mobile thread event reduction", () => { }); }); - it("keeps a message in its call when an update leaves the call id out", () => { - const spoken: MobileMessage = { - ...mobileMessage("message-1", [{ kind: "text", text: "Hi" }]), - callId: "call-1", - }; - const initial = snapshot([spoken]); - - const next = applyMobileThreadEvent(initial, { - type: "thread.message.updated", - seq: 5, - payload: { - messageId: "message-1", - role: "bot", - blocks: [{ kind: "text", text: "Hi. Talk soon." }], - }, - }); - - expect(next?.messages.find((message) => message.id === "message-1")).toMatchObject({ - callId: "call-1", - }); - }); - it("prepends ordered history pages without duplicating the boundary message", () => { const initial = snapshot([mobileMessage("m-2", [], 2), mobileMessage("m-3", [], 3)], 2); diff --git a/apps/mobile/lib/api.ts b/apps/mobile/lib/api.ts index 1fa5a938..ca8658cc 100644 --- a/apps/mobile/lib/api.ts +++ b/apps/mobile/lib/api.ts @@ -805,7 +805,6 @@ export type MobileBot = Pick< | "modelProvider" | "modelId" | "thinkingLevel" - | "autoSpeak" > & Partial>; @@ -834,8 +833,6 @@ export type MobileMessage = { seq?: number; runId?: string; role: "user" | "bot" | "system"; - /** Set when the message was sent from a live voice call; groups one call's transcript. */ - callId?: string; botId?: string; replyToMessageId?: string; replyQuote?: string; @@ -1206,12 +1203,6 @@ export function applyMobileThreadEvent( id, runId: event.runId ? String(event.runId) : undefined, role: (event.payload?.role as MobileMessage["role"]) ?? "bot", - // An update can leave the call id out — the `end_call` marker does — so keep the one - // the message already carries instead of dropping it out of its call. - callId: - typeof event.payload?.callId === "string" - ? event.payload.callId - : prev.messages.find((message) => message.id === id)?.callId, blocks: (event.payload?.blocks as MobileMessage["blocks"]) ?? [], botId: event.botId ?? (event.payload?.botId ? String(event.payload.botId) : undefined), replyToMessageId: event.payload?.replyToMessageId diff --git a/apps/mobile/lib/auto-speak.test.ts b/apps/mobile/lib/auto-speak.test.ts deleted file mode 100644 index 344ffccf..00000000 --- a/apps/mobile/lib/auto-speak.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { readFileSync } from "node:fs"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; -import { nextAutoSpeakAction } from "./auto-speak"; - -const mobileRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); - -function textMessage(id: string, text: string) { - return { - id, - role: "bot" as const, - blocks: [{ kind: "text" as const, text }], - }; -} - -describe("nextAutoSpeakAction", () => { - const base = { - botId: "bot-1", - autoSpeak: true, - focused: true, - snapshotReady: true, - lastSpokenBotId: "bot-1", - lastSpokenMessageId: "msg-1", - runStatus: "completed" as string | null, - messages: [textMessage("msg-1", "Earlier."), textMessage("msg-2", "Hello from the bot.")], - }; - - it("seeds the latest reply when opening a bot so history is not spoken", () => { - expect( - nextAutoSpeakAction({ - ...base, - lastSpokenBotId: null, - lastSpokenMessageId: null, - }), - ).toEqual({ action: "seed", messageId: "msg-2" }); - }); - - it("waits until the thread snapshot belongs to this bot", () => { - expect(nextAutoSpeakAction({ ...base, snapshotReady: false })).toEqual({ action: "wait" }); - }); - - it("seeds when autoSpeak is off so enabling later does not dump the last reply", () => { - expect(nextAutoSpeakAction({ ...base, autoSpeak: false })).toEqual({ - action: "seed", - messageId: "msg-2", - }); - }); - - it("waits while the thread is not focused instead of speaking in the background", () => { - expect(nextAutoSpeakAction({ ...base, focused: false })).toEqual({ action: "wait" }); - }); - - it("waits while a run is still in flight", () => { - expect(nextAutoSpeakAction({ ...base, runStatus: "running" })).toEqual({ action: "wait" }); - expect(nextAutoSpeakAction({ ...base, runStatus: "queued" })).toEqual({ action: "wait" }); - expect(nextAutoSpeakAction({ ...base, runStatus: "leased" })).toEqual({ action: "wait" }); - }); - - it("speaks a finished reply that has not been spoken yet", () => { - expect(nextAutoSpeakAction(base)).toEqual({ - action: "speak", - messageId: "msg-2", - text: "Hello from the bot.", - }); - }); - - it("does not speak the same reply twice", () => { - expect(nextAutoSpeakAction({ ...base, lastSpokenMessageId: "msg-2" })).toEqual({ - action: "wait", - }); - }); - - it("marks an empty reply spoken without playing it", () => { - expect( - nextAutoSpeakAction({ - ...base, - messages: [textMessage("msg-2", " ")], - }), - ).toEqual({ action: "seed", messageId: "msg-2" }); - }); -}); - -describe("mobile autoSpeak wiring", () => { - it("exposes Read replies aloud on bot settings and speaks from the thread", () => { - const settings = readFileSync(resolve(mobileRoot, "app/bot-settings.tsx"), "utf8"); - const thread = readFileSync(resolve(mobileRoot, "app/thread.tsx"), "utf8"); - const api = readFileSync(resolve(mobileRoot, "lib/api.ts"), "utf8"); - expect(api).toContain('"autoSpeak"'); - expect(settings).toContain('t("Read replies aloud")'); - expect(settings).toContain("autoSpeak"); - expect(thread).toContain("nextAutoSpeakAction"); - expect(thread).toContain("speakText("); - }); -}); diff --git a/apps/mobile/lib/auto-speak.ts b/apps/mobile/lib/auto-speak.ts deleted file mode 100644 index d8397259..00000000 --- a/apps/mobile/lib/auto-speak.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { MessageBlock } from "@milo/contracts"; -import { speechFromBlocks } from "@milo/core"; - -const IN_PROGRESS_RUN_STATUSES = new Set(["running", "queued", "leased"]); - -export type AutoSpeakMessage = { - id: string; - role: string; - blocks: MessageBlock[]; -}; - -export type AutoSpeakDecision = - | { action: "seed"; messageId: string | null } - | { action: "wait" } - | { action: "speak"; messageId: string; text: string }; - -/** Same speak-on-finish gate as web Shell: skip history, wait out in-flight runs. */ -export function nextAutoSpeakAction(input: { - botId: string; - autoSpeak: boolean; - focused: boolean; - snapshotReady: boolean; - lastSpokenBotId: string | null; - lastSpokenMessageId: string | null; - runStatus?: string | null; - messages: ReadonlyArray; -}): AutoSpeakDecision { - if (!input.snapshotReady) return { action: "wait" }; - const lastBot = [...input.messages].reverse().find((message) => message.role === "bot"); - const lastBotId = lastBot?.id ?? null; - if (input.lastSpokenBotId !== input.botId) { - return { action: "seed", messageId: lastBotId }; - } - if (!input.autoSpeak) { - return { action: "seed", messageId: lastBotId }; - } - if (!input.focused) return { action: "wait" }; - if (input.runStatus && IN_PROGRESS_RUN_STATUSES.has(input.runStatus)) { - return { action: "wait" }; - } - if (!lastBot || lastBot.id === input.lastSpokenMessageId) return { action: "wait" }; - const text = speechFromBlocks(lastBot.blocks).trim(); - if (!text) return { action: "seed", messageId: lastBot.id }; - return { action: "speak", messageId: lastBot.id, text }; -} diff --git a/apps/mobile/lib/call-session.test.ts b/apps/mobile/lib/call-session.test.ts deleted file mode 100644 index b424d0a0..00000000 --- a/apps/mobile/lib/call-session.test.ts +++ /dev/null @@ -1,692 +0,0 @@ -import { AiConsentBlocked, callIdFromClientNonce, INTERIM_BARGE_IN_MS } from "@milo/core"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { CallClip, CallDeps, CallEnded, DictationHandlers } from "./call-session"; -import { - endCall, - getSnapshot, - setCallProviderTranscribe, - startCall, - subscribe, - toggleMute, -} from "./call-session"; - -vi.mock("expo-file-system", () => ({ File: class {}, Paths: {} })); -vi.mock("./voice", () => ({ speakText: vi.fn(), stopSpeaking: vi.fn() })); -vi.mock("./api", () => ({ - applyMobileThreadEvent: vi.fn(), - blockText: vi.fn(), - captureApiRequestContext: vi.fn(), - rpc: vi.fn(), - subscribeThread: vi.fn(), -})); - -type Deferred = { - promise: Promise; - resolve: (value: T) => void; - reject: (reason?: unknown) => void; -}; - -function deferred(): Deferred { - let resolve!: (value: T) => void; - let reject!: (reason?: unknown) => void; - const promise = new Promise((done, fail) => { - resolve = done; - reject = fail; - }); - return { promise, resolve, reject }; -} - -const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); - -function fakes(opts: { onDevice?: boolean } = {}) { - const recordings: Array> = []; - const signals: AbortSignal[] = []; - const speeches: Array> = []; - const send = vi.fn( - async (_botId: string, _text: string, _clientNonce: string): Promise => - "run-1", - ); - const closeCall = vi.fn(async (_botId: string, _callId: string) => undefined); - const unwatch = vi.fn(); - let reply: (messageId: string, text: string, runId?: string) => void = () => undefined; - let ended: (ended: CallEnded) => void = () => undefined; - const spoken: string[] = []; - let handlers: DictationHandlers | null = null; - const stopSpeaking = vi.fn(() => { - speeches[speeches.length - 1]?.resolve(); - }); - const deps: CallDeps = { - dictate: async (next, signal) => { - signals.push(signal); - if (!opts.onDevice) return false; - handlers = next; - return true; - }, - stopSpeaking, - record: (signal) => { - signals.push(signal); - const next = deferred(); - recordings.push(next); - return next.promise; - }, - // The fake clip carries the words, so transcription is the identity. - transcribe: async (clip) => clip.base64, - send, - endCall: closeCall, - speak: (_botId, text) => { - spoken.push(text); - const next = deferred(); - speeches.push(next); - return next.promise; - }, - watch: (_botId, onReply, onCallEnded) => { - reply = onReply; - ended = onCallEnded; - return unwatch; - }, - }; - return { - deps, - stopSpeaking, - interim: (text: string) => handlers?.onInterim(text), - hear: (text: string) => handlers?.onFinal(text), - recordings, - signals, - speeches, - spoken, - send, - closeCall, - unwatch, - say: (text: string) => - recordings[recordings.length - 1]?.resolve({ base64: text, mimeType: "audio/m4a" }), - replyWith: (messageId: string, text: string, runId?: string) => reply(messageId, text, runId), - endedCall: (callId: string | undefined, farewell?: string) => ended({ callId, farewell }), - }; -} - -afterEach(() => endCall()); - -describe("mobile call session", () => { - it("starts listening for the bot on the call", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - expect(getSnapshot()).toMatchObject({ botId: "bot-1", botName: "Ada", phase: "listening" }); - expect(fake.recordings).toHaveLength(1); - }); - - it("sends what it heard to the call's bot", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("how is the deploy going"); - await flush(); - expect(fake.send).toHaveBeenCalledWith( - "bot-1", - "how is the deploy going", - expect.stringMatching(/^call:/), - ); - expect(getSnapshot()).toMatchObject({ phase: "thinking", heard: "how is the deploy going" }); - }); - - it("mutes after a consent refusal instead of reopening the microphone or resending", async () => { - const fake = fakes({ onDevice: true }); - fake.send.mockRejectedValueOnce(new AiConsentBlocked("consent denied")); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await flush(); - - fake.hear("status please"); - await flush(); - - expect(fake.send).toHaveBeenCalledOnce(); - expect(fake.signals).toHaveLength(1); - expect(fake.recordings).toHaveLength(0); - expect(getSnapshot()).toMatchObject({ - phase: "listening", - muted: true, - caption: "consent denied", - }); - }); - - it("tags every message in one call with the same call id", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("how is the deploy going"); - await flush(); - fake.replyWith("message-1", "It is green."); - fake.speeches[0]?.resolve(); - await flush(); - fake.say("and the tests"); - await flush(); - - const nonces = fake.send.mock.calls.map((call) => call[2]); - expect(nonces).toHaveLength(2); - expect(callIdFromClientNonce(nonces[0])).toBe(callIdFromClientNonce(nonces[1])); - expect(nonces[0]).not.toBe(nonces[1]); - }); - - it("speaks a reply, then listens again", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - fake.replyWith("message-1", "It is green."); - expect(getSnapshot()?.phase).toBe("speaking"); - expect(getSnapshot()?.exchanges).toEqual([ - { role: "user", text: "status please" }, - { role: "bot", text: "It is green." }, - ]); - fake.speeches[0]?.resolve(); - await flush(); - expect(getSnapshot()?.phase).toBe("listening"); - expect(fake.recordings).toHaveLength(2); - }); - - it("mutes after a speech-provider consent refusal without recording another turn", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - fake.replyWith("message-1", "It is green."); - fake.speeches[0]?.reject(new AiConsentBlocked("voice consent denied")); - await flush(); - - expect(fake.recordings).toHaveLength(1); - expect(getSnapshot()).toMatchObject({ - phase: "listening", - muted: true, - caption: "voice consent denied", - }); - }); - - it("keeps retrying ordinary speech errors", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - fake.replyWith("message-1", "It is green."); - fake.speeches[0]?.reject(new Error("voice offline")); - await flush(); - - expect(fake.recordings).toHaveLength(2); - expect(getSnapshot()).toMatchObject({ phase: "listening", muted: false }); - }); - - it("stops recording while muted", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - toggleMute(); - await flush(); - expect(fake.signals[0]?.aborted).toBe(true); - expect(getSnapshot()).toMatchObject({ muted: true, phase: "listening" }); - expect(fake.recordings).toHaveLength(1); - }); - - it("hangs up once the bot has answered a goodbye", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("that's all, bye"); - await flush(); - expect(fake.send).toHaveBeenCalledWith( - "bot-1", - "that's all, bye", - expect.stringMatching(/^call:/), - ); - fake.replyWith("message-1", "Talk soon."); - expect(getSnapshot()?.phase).toBe("speaking"); - fake.speeches[0]?.resolve(); - await flush(); - expect(getSnapshot()).toBeNull(); - expect(fake.unwatch).toHaveBeenCalled(); - }); - - it("speaks the farewell and hangs up when the bot ends the call itself", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("end the call and make me a list"); - await flush(); - fake.endedCall(callIdFromClientNonce(fake.send.mock.calls[0]?.[2]), "Talk soon."); - expect(getSnapshot()?.phase).toBe("speaking"); - expect(fake.spoken).toEqual(["Talk soon."]); - fake.speeches[0]?.resolve(); - await flush(); - - expect(getSnapshot()).toBeNull(); - }); - - it("never speaks the work the bot files after it hung up", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("end the call and make me a list"); - await flush(); - fake.endedCall(callIdFromClientNonce(fake.send.mock.calls[0]?.[2]), "Talk soon."); - fake.replyWith("message-1", "Here is the list."); - - expect(fake.spoken).toEqual(["Talk soon."]); - }); - - it("ignores a call ended event from another call", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - fake.endedCall("someone-elses-call", "Talk soon."); - fake.replyWith("message-1", "It is green."); - fake.speeches[0]?.resolve(); - await flush(); - - expect(getSnapshot()?.phase).toBe("listening"); - }); - - it("reports a failed recording and retries, then hangs up cleanly", async () => { - const fake = fakes(); - let attempts = 0; - startCall( - { botId: "bot-1", botName: "Ada" }, - { - ...fake.deps, - record: (signal) => { - attempts += 1; - return attempts === 1 ? Promise.reject(new Error("mic busy")) : fake.deps.record(signal); - }, - }, - ); - const captions: string[] = []; - const stop = subscribe(() => { - const caption = getSnapshot()?.caption; - if (caption) captions.push(caption); - }); - await flush(); - stop(); - expect(captions).toContain("mic busy"); - expect(getSnapshot()?.phase).toBe("listening"); - expect(attempts).toBe(2); - endCall(); - expect(getSnapshot()).toBeNull(); - }); - - it("aborts the bot feed on hang up", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - endCall(); - expect(fake.unwatch).toHaveBeenCalledTimes(1); - expect(getSnapshot()).toBeNull(); - }); - - it("closes the call server-side when the caller presses hang up", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - const callId = callIdFromClientNonce(fake.send.mock.calls[0]?.[2]); - - endCall(); - - expect(fake.closeCall).toHaveBeenCalledWith("bot-1", callId); - }); - - it("drops a run id that lands after the same bot was called again", async () => { - const fake = fakes(); - const pending = deferred(); - fake.send.mockReturnValueOnce(pending.promise); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - - endCall(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - pending.resolve("run-1"); - await flush(); - - // The new call registered no run of its own, so nothing is filtered against the old one. - fake.replyWith("message-1", "All good.", "run-2"); - expect(fake.spoken).toEqual(["All good."]); - }); - - it("closes the call server-side once when the caller says goodbye", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("that's all, bye"); - await flush(); - const callId = callIdFromClientNonce(fake.send.mock.calls[0]?.[2]); - fake.replyWith("message-1", "Talk soon."); - fake.speeches[0]?.resolve(); - await flush(); - - expect(getSnapshot()).toBeNull(); - expect(fake.closeCall).toHaveBeenCalledTimes(1); - expect(fake.closeCall).toHaveBeenCalledWith("bot-1", callId); - }); - - it("does not close the call again when the bot ended it", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("end the call and make me a list"); - await flush(); - fake.endedCall(callIdFromClientNonce(fake.send.mock.calls[0]?.[2]), "Talk soon."); - fake.speeches[0]?.resolve(); - await flush(); - - expect(getSnapshot()).toBeNull(); - expect(fake.closeCall).not.toHaveBeenCalled(); - }); - - it("drops the reply leaking back into the microphone", async () => { - const fake = fakes({ onDevice: true }); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await flush(); - fake.hear("how is the deploy going"); - await flush(); - fake.replyWith("message-1", "The deploy is green and the tests pass."); - await flush(); - - fake.hear("the deploy is green and the tests pass"); - await flush(); - - expect(fake.send).toHaveBeenCalledTimes(1); - expect(getSnapshot()?.exchanges).toEqual([ - { role: "user", text: "how is the deploy going" }, - { role: "bot", text: "The deploy is green and the tests pass." }, - ]); - }); - - it("leaves a reply from another run out of the call", async () => { - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada" }, fake.deps); - await flush(); - fake.say("status please"); - await flush(); - - // A message typed into the thread mid-call is answered on its own run. - fake.replyWith("message-typed", "Here is that list.", "run-typed"); - expect(fake.spoken).toEqual([]); - expect(getSnapshot()).toMatchObject({ phase: "thinking" }); - - fake.replyWith("message-1", "It is green.", "run-1"); - expect(fake.spoken).toEqual(["It is green."]); - expect(getSnapshot()?.exchanges).toEqual([ - { role: "user", text: "status please" }, - { role: "bot", text: "It is green." }, - ]); - }); - - it("does not enable provider transcription when no call is active", async () => { - setCallProviderTranscribe(true); - const fake = fakes(); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await flush(); - expect(fake.recordings).toHaveLength(0); - }); - - it("uses provider transcription after it is enabled during an active call", async () => { - const gate = deferred(); - const fake = fakes(); - const startedCallId = startCall( - { botId: "bot-1", botName: "Ada", transcribe: false }, - { - ...fake.deps, - dictate: async () => { - await gate.promise; - return false; - }, - }, - ); - await flush(); - expect(fake.recordings).toHaveLength(0); - - setCallProviderTranscribe(true, startedCallId); - gate.resolve(); - await flush(); - expect(fake.recordings).toHaveLength(1); - }); - - it("ignores a transcribe probe for another call and resumes listening for this one", async () => { - const fake = fakes(); - const startedCallId = startCall( - { botId: "bot-1", botName: "Ada", transcribe: false }, - fake.deps, - ); - await flush(); - expect(fake.recordings).toHaveLength(0); - - setCallProviderTranscribe(true, "other-call"); - // Unmute listens again, so a probe that flipped this call would record. - toggleMute(); - toggleMute(); - await flush(); - expect(fake.recordings).toHaveLength(0); - - setCallProviderTranscribe(true, startedCallId); - await flush(); - expect(fake.recordings).toHaveLength(1); - }); - - it("does not apply a finished probe to a later speak-only call", async () => { - const fake = fakes(); - const firstCallId = startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await flush(); - const secondCallId = startCall( - { botId: "bot-1", botName: "Ada", transcribe: false }, - fake.deps, - ); - await flush(); - expect(secondCallId).not.toBe(firstCallId); - expect(fake.recordings).toHaveLength(0); - - setCallProviderTranscribe(true, firstCallId); - // Unmute listens again, so a probe that flipped this call would record. - toggleMute(); - toggleMute(); - await flush(); - expect(fake.recordings).toHaveLength(0); - - setCallProviderTranscribe(true, secondCallId); - await flush(); - expect(fake.recordings).toHaveLength(1); - }); - - it("speaks each reply once", async () => { - const fake = fakes({ onDevice: true }); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await flush(); - fake.hear("status please"); - await flush(); - fake.replyWith("message-1", "It is green."); - fake.replyWith("message-1", "It is green."); - - expect(fake.spoken).toEqual(["It is green."]); - }); - - it("does not let a stale speech refusal mute a newer call", async () => { - const fake = fakes({ onDevice: true }); - const firstCallId = startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await flush(); - fake.hear("status please"); - await flush(); - fake.replyWith("message-1", "It is green."); - - const secondCallId = startCall( - { botId: "bot-1", botName: "Ada", transcribe: false }, - fake.deps, - ); - await flush(); - fake.speeches[0]?.reject(new AiConsentBlocked("stale consent denied")); - await flush(); - - expect(secondCallId).not.toBe(firstCallId); - expect(getSnapshot()).toMatchObject({ botId: "bot-1", muted: false }); - }); -}); - -describe("mobile call session on a timer", () => { - beforeEach(() => vi.useFakeTimers()); - afterEach(() => { - endCall(); - vi.useRealTimers(); - }); - - const tick = (ms = 0) => vi.advanceTimersByTimeAsync(ms); - - it("cuts the reply short when the caller talks over it, and still sends that turn", async () => { - const fake = fakes({ onDevice: true }); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - fake.hear("status please"); - await tick(); - fake.replyWith("message-1", "It is green."); - await tick(); - - fake.interim("actually hang on"); - await tick(INTERIM_BARGE_IN_MS - 1); - expect(fake.stopSpeaking).not.toHaveBeenCalled(); - await tick(1); - expect(fake.stopSpeaking).toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("listening"); - - fake.hear("actually hang on"); - await tick(); - expect(fake.send).toHaveBeenLastCalledWith( - "bot-1", - "actually hang on", - expect.stringMatching(/^call:/), - ); - }); - - it("retries the first snapshot load instead of losing the feed", async () => { - const { rpc, subscribeThread } = await import("./api"); - vi.mocked(rpc) - .mockRejectedValueOnce(new Error("offline")) - .mockResolvedValue({ cursor: 3, messages: [], run: null } as never); - vi.mocked(subscribeThread).mockResolvedValue(undefined as never); - const fake = fakes(); - const { watch: _watch, ...deps } = fake.deps; - startCall({ botId: "bot-1", botName: "Ada" }, deps); - await tick(); - expect(subscribeThread).not.toHaveBeenCalled(); - - await tick(500); - expect(subscribeThread).toHaveBeenCalled(); - expect(vi.mocked(subscribeThread).mock.calls[0]?.[1]).toBe(3); - vi.mocked(rpc).mockReset(); - vi.mocked(subscribeThread).mockReset(); - }); - - it("does not hang up after a farewell whose send was blocked by consent", async () => { - const fake = fakes({ onDevice: true }); - fake.send.mockRejectedValueOnce(new AiConsentBlocked("consent denied")); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - - fake.hear("goodbye"); - await tick(); - expect(getSnapshot()).toMatchObject({ - phase: "listening", - muted: true, - caption: "consent denied", - }); - - await tick(20_000); - expect(fake.closeCall).not.toHaveBeenCalled(); - expect(getSnapshot()?.botId).toBe("bot-1"); - - toggleMute(); - await tick(); - expect(fake.closeCall).not.toHaveBeenCalled(); - expect(getSnapshot()).toMatchObject({ botId: "bot-1", muted: false, phase: "listening" }); - }); - - it("still ends a bot-ended call when farewell speech consent is refused", async () => { - const fake = fakes({ onDevice: true }); - const id = startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - fake.endedCall(id, "Talk soon."); - await tick(); - fake.speeches[0]?.reject(new AiConsentBlocked("voice consent denied")); - await tick(); - - expect(getSnapshot()).toBeNull(); - // Bot already closed server-side; local endCall must not re-hit threads/endCall. - expect(fake.closeCall).not.toHaveBeenCalled(); - }); - - it("ends immediately when speech consent is refused after a goodbye already sent", async () => { - const fake = fakes({ onDevice: true }); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - fake.hear("goodbye"); - await tick(); - fake.replyWith("message-1", "Talk soon."); - await tick(); - fake.speeches[0]?.reject(new AiConsentBlocked("voice consent denied")); - await tick(); - - expect(getSnapshot()).toBeNull(); - expect(fake.closeCall).toHaveBeenCalledOnce(); - }); - - it("does not start speech again after consent refuse until the caller unmutes", async () => { - const fake = fakes({ onDevice: true }); - fake.send.mockRejectedValueOnce(new AiConsentBlocked("consent denied")); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - fake.hear("status please"); - await tick(); - expect(getSnapshot()).toMatchObject({ muted: true }); - - fake.replyWith("message-1", "It is green."); - await tick(); - expect(fake.spoken).toEqual([]); - expect(getSnapshot()).toMatchObject({ muted: true, botId: "bot-1" }); - }); - - it("does not let an earlier farewell timer end the next call", async () => { - const fake = fakes({ onDevice: true }); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - fake.hear("that's all"); - await tick(); - fake.replyWith("message-1", "Talk soon."); - await tick(); - - fake.hear("see you"); - await tick(); - endCall(); - startCall({ botId: "bot-1", botName: "Ada", transcribe: false }, fake.deps); - await tick(); - await tick(20_000); - - expect(getSnapshot()?.botId).toBe("bot-1"); - }); - - it("reconnects the call feed when the live stream ends", async () => { - const { rpc, subscribeThread } = await import("./api"); - vi.mocked(rpc).mockResolvedValue({ cursor: 7, messages: [], run: null } as never); - vi.mocked(subscribeThread).mockResolvedValue(undefined as never); - const fake = fakes(); - const { watch: _watch, ...deps } = fake.deps; - startCall({ botId: "bot-1", botName: "Ada" }, deps); - await tick(); - expect(subscribeThread).toHaveBeenCalledTimes(1); - - await tick(250); - expect(subscribeThread).toHaveBeenCalledTimes(2); - expect(vi.mocked(subscribeThread).mock.calls[1]?.[1]).toBe(7); - vi.mocked(rpc).mockReset(); - vi.mocked(subscribeThread).mockReset(); - }); -}); diff --git a/apps/mobile/lib/call-session.ts b/apps/mobile/lib/call-session.ts deleted file mode 100644 index 54134536..00000000 --- a/apps/mobile/lib/call-session.ts +++ /dev/null @@ -1,688 +0,0 @@ -import { - ACTIVE_RUN_STATUSES, - AiConsentBlocked, - abortableDelay, - callClientNonce, - INTERIM_BARGE_IN_MS, - isCallBargeIn, - isFarewell, - isInterimCallBargeIn, - latestSpokenCallReply, - spokenMemory, -} from "@milo/core"; -import type { AudioRecorder } from "expo-audio"; -import { File } from "expo-file-system"; -import { useSyncExternalStore } from "react"; -import type { MobileSnapshot } from "./api"; -import { - applyMobileThreadEvent, - blockText, - captureApiRequestContext, - rpc, - subscribeThread, -} from "./api"; -import * as dictation from "./dictation"; -import { getActiveUiLocale, t } from "./i18n"; -import { speakText, stopSpeaking } from "./voice"; - -export type CallPhase = "listening" | "thinking" | "speaking"; -export type CallExchange = { role: "user" | "bot"; text: string }; - -export type CallState = { - botId: string; - botName: string; - botColor: string; - phase: CallPhase; - muted: boolean; - transcriptOpen: boolean; - caption: string; - heard: string; - exchanges: CallExchange[]; -}; - -export type CallClip = { base64: string; mimeType: string }; - -/** What one microphone session reports back: a running guess, then the finished turn. */ -export type DictationHandlers = { - onInterim: (text: string) => void; - onFinal: (text: string) => void; -}; - -/** Everything that touches the device or the server, so the loop stays testable. */ -export type CallDeps = { - /** On-device dictation for one turn. False when the device cannot recognise speech. */ - dictate: (handlers: DictationHandlers, signal: AbortSignal) => Promise; - /** Fallback when the device cannot: record a clip and send it to the voice provider. */ - record: (signal: AbortSignal) => Promise; - transcribe: (clip: CallClip, signal: AbortSignal) => Promise; - /** Resolves with the run the message started, so only that run's reply is spoken. */ - send: (botId: string, text: string, clientNonce: string) => Promise; - /** Tells the server the caller hung up, so it files the call marker and the wrap-up run. */ - endCall: (botId: string, callId: string) => Promise; - speak: (botId: string, text: string) => Promise; - /** Cuts the reply off when the caller talks over it. */ - stopSpeaking: () => void; - watch: ( - botId: string, - onReply: (messageId: string, text: string, runId?: string) => void, - onCallEnded: (ended: CallEnded) => void, - ) => () => void; -}; - -/** What the bot's own `end_call` carries: the call it ends and the goodbye to speak. */ -export type CallEnded = { callId?: string; farewell?: string }; - -/** How long a goodbye waits for a reply that may never come before hanging up anyway. */ -const FAREWELL_TIMEOUT_MS = 20_000; -/** A call that cannot reach the microphone or the server this many turns in a row hangs up. */ -const MAX_TURN_FAILURES = 3; - -/** A dropped live feed is reconnected from the last seq it saw, backing off as it retries. */ -const FEED_RETRY_MIN_MS = 250; -const FEED_RETRY_MAX_MS = 5_000; - -// ponytail: naive fixed-threshold endpointing on the fallback path only. Swap for a VAD -// model if rooms with steady background noise start cutting people off mid-sentence. -const SPEECH_LEVEL_DB = -35; -const SILENCE_HANG_MS = 1_200; -const METER_POLL_MS = 200; -const MAX_CLIP_MS = 30_000; - -let state: CallState | null = null; -/** Shared by every message this call sends, so the thread can group one call's exchange. */ -let callId = ""; -/** The run this call's last turn started: replies to anything else are not spoken. */ -let callRunId: string | null = null; -let deps: CallDeps = productionDeps(); -let turn: AbortController | null = null; -let unwatch: (() => void) | null = null; -let hangUpAfterReply = false; -/** Caller farewell send already resolved; speech consent refuse can finish the hang-up. */ -let farewellSent = false; -/** Disclosure was refused: do not start speech again until the caller unmutes. */ -let consentBlocked = false; -/** The bot hung up itself: its farewell is the last thing this call speaks. */ -let botEndedCall = false; -let hangUpTimer: ReturnType | null = null; -let spokenMessageId: string | null = null; -let failures = 0; -/** Whether the provider can transcribe, so the fallback path is worth trying at all. */ -let canTranscribe = true; -/** Whether this device does its own speech recognition; unknown until the first turn. */ -let onDevice: boolean | null = null; -/** A microphone session is running, so playback can leave it open instead of restarting it. */ -let micOpen = false; -/** The caller cut the reply off: the speaker going idle must not reopen the microphone. */ -let bargedIn = false; -/** Counting down a phrase heard over the reply, before it counts as cutting in. */ -let interimTimer: ReturnType | null = null; -const watchers = new Set<() => void>(); - -export function subscribe(watcher: () => void): () => void { - watchers.add(watcher); - return () => { - watchers.delete(watcher); - }; -} - -export function getSnapshot(): CallState | null { - return state; -} - -export function useCallSession(): CallState | null { - return useSyncExternalStore(subscribe, getSnapshot, getSnapshot); -} - -function emit() { - for (const watcher of [...watchers]) watcher(); -} - -function set(patch: Partial) { - if (!state) return; - state = { ...state, ...patch }; - emit(); -} - -export function startCall( - // `transcribe` says whether the voice provider can turn audio into text; a speak-only - // provider is fine as long as the device recognises speech itself. - call: { botId: string; botName: string; botColor?: string; transcribe?: boolean }, - overrides: Partial = {}, -): string { - endCall(); - deps = { ...productionDeps(), ...overrides }; - callId = randomId(); - callRunId = null; - canTranscribe = call.transcribe ?? true; - onDevice = null; - micOpen = false; - bargedIn = false; - spokenMemory.clear(); - state = { - botId: call.botId, - botName: call.botName, - botColor: call.botColor ?? "", - phase: "listening", - muted: false, - transcriptOpen: false, - caption: "", - heard: "", - exchanges: [], - }; - unwatch = deps.watch(call.botId, onReply, onCallEnded); - emit(); - void listen(); - return callId; -} - -/** A background voice/status result can enable provider fallback after the call has started. */ -export function setCallProviderTranscribe(enabled: boolean, forCallId?: string): void { - if (!state || (forCallId !== undefined && forCallId !== callId)) return; - canTranscribe = enabled; - // Dictation can fail before the probe returns, which leaves the mic closed. - if (enabled && state.phase === "listening" && !micOpen && !state.muted) void listen(); -} - -export function endCall(): void { - // The bot's own end_call already closed the call server-side; only a caller hang-up - // has to say so. Fire and forget: the card is going away either way. - if (state && !botEndedCall) void deps.endCall(state.botId, callId).catch(() => undefined); - turn?.abort(); - turn = null; - unwatch?.(); - unwatch = null; - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = null; - hangUpAfterReply = false; - farewellSent = false; - consentBlocked = false; - botEndedCall = false; - callRunId = null; - spokenMessageId = null; - failures = 0; - micOpen = false; - bargedIn = false; - clearInterim(); - spokenMemory.clear(); - if (!state) return; - state = null; - emit(); -} - -export function toggleMute(): void { - if (!state) return; - const muted = !state.muted; - set({ muted, heard: "" }); - if (muted) { - turn?.abort(); - turn = null; - micOpen = false; - clearInterim(); - return; - } - consentBlocked = false; - if (state.phase === "listening") void listen(); -} - -export function toggleTranscript(): void { - if (!state) return; - set({ transcriptOpen: !state.transcriptOpen }); -} - -async function listen(): Promise { - if (!state) return; - // The caller said goodbye: every path back to listening hangs up instead. - if (hangUpAfterReply) { - endCall(); - return; - } - set({ phase: "listening", heard: "", caption: "" }); - if (state.muted) return; - await openMic(); -} - -/** Opens one microphone session, unless one is already running or the call is muted. */ -async function openMic(): Promise { - if (!state || micOpen || state.muted) return; - micOpen = true; - const controller = new AbortController(); - turn = controller; - const { botId } = state; - const mine = () => !controller.signal.aborted && state?.botId === botId; - try { - if (onDevice !== false) { - // The session stays open until it delivers a turn, so the microphone is still the - // caller's while the reply plays and a barge-in can land. - const started = await deps.dictate( - { - onInterim: (text) => { - if (mine()) heardInterim(text); - }, - onFinal: (text) => { - if (mine()) void handleTranscript(text); - }, - }, - controller.signal, - ); - if (started) { - onDevice = true; - return; - } - onDevice = false; - } - // Muting or hanging up while the device was deciding: no microphone after all. - if (!mine() || !state || state.muted) { - micOpen = false; - return; - } - if (!canTranscribe) { - micOpen = false; - set({ - caption: t( - "Allow speech recognition in Settings, or connect ElevenLabs, OpenAI, or Fish Audio.", - ), - }); - return; - } - const clip = await deps.record(controller.signal); - if (!mine()) return; - const text = clip ? await deps.transcribe(clip, controller.signal) : ""; - if (!mine()) return; - micOpen = false; - await handleTranscript(text); - } catch (error) { - micOpen = false; - if (!mine()) return; - failTurn(error); - } -} - -/** One finished turn: drop the reply leaking back, cut in over playback, or send it. */ -async function handleTranscript(raw: string): Promise { - if (!state) return; - // The session stopped itself to deliver this. - micOpen = false; - failures = 0; - const text = raw.trim(); - if (!text) { - void listen(); - return; - } - if (state.phase === "speaking") { - if (!isCallBargeIn(text)) { - // The microphone caught the reply, not the caller: reopen so a real interruption - // still lands, and let the reply play out. - set({ heard: "" }); - void openMic(); - return; - } - // The caller talked over the reply: cut the audio, and never resume that message. - bargedIn = true; - clearInterim(); - deps.stopSpeaking(); - set({ phase: "thinking", caption: "" }); - } - if (spokenMemory.isEcho(text)) { - set({ heard: "" }); - void listen(); - return; - } - const { botId } = state; - // The call this turn belongs to: hanging up and calling the same bot again before - // send resolves must not hand the new call the old run. - const turnCallId = callId; - set({ - phase: "thinking", - heard: text, - exchanges: [...state.exchanges, { role: "user", text }], - }); - if (isFarewell(text)) { - hangUpAfterReply = true; - // A second goodbye replaces this timer. Clear the previous one or it can - // end the next call after this one has already hung up. - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = setTimeout(endCall, FAREWELL_TIMEOUT_MS); - } - try { - const runId = await deps.send(botId, text, callClientNonce(turnCallId)); - if (state?.botId === botId && callId === turnCallId) { - callRunId = runId ?? null; - if (hangUpAfterReply) farewellSent = true; - } - } catch (error) { - if (state?.botId !== botId || callId !== turnCallId) return; - if (error instanceof AiConsentBlocked) { - // Bot already closed server-side: do not clear its hang-up into a muted stuck call. - if (botEndedCall) { - endCall(); - return; - } - // Goodbye was not delivered; drop the armed hang-up so mute/retry can continue. - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = null; - hangUpAfterReply = false; - farewellSent = false; - blockForConsent(error); - return; - } - failTurn(error); - } -} - -function failTurn(error: unknown): void { - failures += 1; - if (failures >= MAX_TURN_FAILURES) { - endCall(); - return; - } - set({ phase: "listening", caption: errorText(error, t("Could not hear that.")) }); - void listen(); -} - -/** A denied disclosure is not a transient call failure: wait for an explicit retry. */ -function blockForConsent(error: AiConsentBlocked): void { - consentBlocked = true; - turn?.abort(); - turn = null; - micOpen = false; - clearInterim(); - set({ - phase: "listening", - muted: true, - heard: "", - caption: errorText(error, t("Could not hear that.")), - }); -} - -/** - * A running guess: it shows what the caller is saying, and over a reply it is the only - * signal that arrives while they are still talking. A phrase that stands for - * INTERIM_BARGE_IN_MS stops the audio at once; the session keeps running, so its silence - * window finishes the utterance and handleTranscript sends it as the next turn. - */ -function heardInterim(text: string): void { - if (!state) return; - if (state.phase !== "speaking") { - clearInterim(); - set({ heard: text }); - return; - } - if (!isInterimCallBargeIn(text)) { - clearInterim(); - return; - } - if (interimTimer) return; - interimTimer = setTimeout(() => { - interimTimer = null; - if (state?.phase !== "speaking") return; - bargedIn = true; - deps.stopSpeaking(); - set({ phase: "listening", caption: "" }); - }, INTERIM_BARGE_IN_MS); -} - -function clearInterim(): void { - if (interimTimer) clearTimeout(interimTimer); - interimTimer = null; -} - -function onReply(messageId: string, text: string, runId?: string): void { - // Work the bot files after hanging up belongs in the thread, not in the caller's ear. - if (!state || botEndedCall || messageId === spokenMessageId) return; - // A reply to something typed into the thread mid-call belongs on screen only. - if (callRunId && runId && runId !== callRunId) return; - spokenMessageId = messageId; - speakAndListen(text); -} - -function speakAndListen(text: string): void { - if (!state) return; - const { botId } = state; - const speakingCallId = callId; - let blockedByConsent = false; - bargedIn = false; - clearInterim(); - set({ exchanges: [...state.exchanges, { role: "bot", text }] }); - // A prior disclosure refuse stays muted until unmute; do not re-open speech consent. - if (consentBlocked) { - set({ phase: "listening", heard: "" }); - return; - } - spokenMemory.remember(text); - // Only the on-device path can hear the caller over the reply; the recorder would just - // record the speaker, so it stays shut until playback ends. - if (!onDevice) { - turn?.abort(); - turn = null; - micOpen = false; - } - set({ phase: "speaking", heard: "" }); - if (onDevice) void openMic(); - void deps - .speak(botId, text) - .catch((error: unknown) => { - if (state?.botId !== botId || callId !== speakingCallId) return; - if (error instanceof AiConsentBlocked) { - blockedByConsent = true; - // Hang-up already committed server-side or via a sent goodbye. - if (botEndedCall || farewellSent) { - endCall(); - return; - } - blockForConsent(error); - return; - } - set({ caption: errorText(error, t("Could not speak that.")) }); - }) - .finally(() => { - if (state?.botId !== botId || callId !== speakingCallId) return; - if (blockedByConsent) return; - // The caller cut in: the microphone is already theirs and their turn is on its way. - if (bargedIn) return; - void listen(); - }); -} - -/** The bot hung up: speak the goodbye it wrote, then end — the rest lands in the thread. */ -function onCallEnded(ended: CallEnded): void { - if (!state || ended.callId !== callId || botEndedCall) return; - hangUpAfterReply = true; - botEndedCall = true; - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = setTimeout(endCall, FAREWELL_TIMEOUT_MS); - const farewell = ended.farewell?.trim(); - // Nothing to say: hang up instead of waiting out the fallback. - if (!farewell) { - endCall(); - return; - } - speakAndListen(farewell); -} - -function errorText(error: unknown, fallback: string): string { - return error instanceof Error ? error.message : fallback; -} - -function productionDeps(): CallDeps { - return { - dictate: dictateTurn, - record: recordClip, - transcribe: transcribeClip, - send: sendHeard, - endCall: closeCall, - speak: speakReply, - stopSpeaking, - watch: watchReplies, - }; -} - -/** The device's own speech recognition, which works with a speak-only voice provider. */ -async function dictateTurn(handlers: DictationHandlers, signal: AbortSignal): Promise { - if (!(await dictation.available())) return false; - await dictation.listen({ ...handlers, signal, lang: getActiveUiLocale() }); - return true; -} - -/** Records one hands-free turn: wait for speech, stop once the speaker goes quiet. */ -async function recordClip(signal: AbortSignal): Promise { - const { AudioModule, RecordingPresets, setAudioModeAsync } = await import("expo-audio"); - const permission = await AudioModule.requestRecordingPermissionsAsync(); - if (!permission.granted) throw new Error(t("Allow microphone access to call a bot.")); - let recorder: AudioRecorder | undefined; - let heardSpeech = false; - try { - await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true }); - recorder = new AudioModule.AudioRecorder({ - ...RecordingPresets.HIGH_QUALITY, - isMeteringEnabled: true, - }); - await recorder.prepareToRecordAsync(); - recorder.record(); - let quietMs = 0; - for (let elapsed = 0; elapsed < MAX_CLIP_MS && !signal.aborted; elapsed += METER_POLL_MS) { - await abortableDelay(METER_POLL_MS, signal); - if (signal.aborted) break; - // Platforms without metering report nothing; keep recording to the cap. - const level = recorder.getStatus().metering ?? 0; - if (level > SPEECH_LEVEL_DB) { - heardSpeech = true; - quietMs = 0; - } else if (heardSpeech) { - quietMs += METER_POLL_MS; - if (quietMs >= SILENCE_HANG_MS) break; - } - } - await recorder.stop(); - const uri = recorder.uri; - if (!uri || !heardSpeech || signal.aborted) { - deleteQuietly(uri); - return null; - } - const file = new File(uri); - const base64 = await file.base64(); - deleteQuietly(uri); - return { base64, mimeType: "audio/m4a" }; - } finally { - recorder?.release(); - await setAudioModeAsync({ allowsRecording: false, playsInSilentMode: true }); - } -} - -function deleteQuietly(uri: string | null): void { - if (!uri) return; - try { - new File(uri).delete(); - } catch { - // The clip is disposable; a leftover in the cache is fine. - } -} - -async function transcribeClip(clip: CallClip, signal: AbortSignal): Promise { - const { apiBase, headers } = await captureApiRequestContext(); - const res = await fetch(`${apiBase}/api/voice/transcribe`, { - method: "POST", - headers: { "content-type": "application/json", origin: "rakazo://", ...headers }, - body: JSON.stringify({ audioBase64: clip.base64, mimeType: clip.mimeType }), - signal, - }); - const body = (await res.json().catch(() => ({}))) as { text?: string; error?: string }; - if (!res.ok) throw new Error(body.error ?? t("Could not transcribe that.")); - return body.text ?? ""; -} - -async function sendHeard( - botId: string, - text: string, - clientNonce: string, -): Promise { - const sent = await rpc<{ runId?: string }>("threads/send", { botId, clientNonce, text }); - return sent.runId; -} - -async function closeCall(botId: string, id: string): Promise { - await rpc("threads/endCall", { botId, callId: id }); -} - -async function speakReply(botId: string, text: string): Promise { - if (!(await speakText(text, { botId }))) { - throw new Error(t("Add a voice provider in Voice settings.")); - } -} - -/** Live feed for the bot on the call, independent of whichever thread is on screen. */ -function watchReplies( - botId: string, - onNewReply: (messageId: string, text: string, runId?: string) => void, - onEnded: (ended: CallEnded) => void, -): () => void { - const controller = new AbortController(); - const watchedCallId = callId; - void (async () => { - let snapshot: MobileSnapshot | null = null; - let lastSeen: string | null = null; - let cursor = 0; - let retry = FEED_RETRY_MIN_MS; - // The stream returns on an idle timeout as well as on a real failure, and a call - // outlives both: pick it back up from the last seq until the caller hangs up. The - // first snapshot is loaded in here too, so a failed load retries instead of - // leaving the call with an open microphone and no feed. - while (!controller.signal.aborted) { - try { - if (!snapshot) { - snapshot = await rpc( - "threads/get", - { botId }, - { signal: controller.signal }, - ); - lastSeen = latestSpokenCallReply(snapshot.messages, watchedCallId)?.id ?? null; - cursor = snapshot.cursor ?? 0; - } - await subscribeThread( - { botId }, - cursor, - (event) => { - if (typeof event.seq === "number") cursor = event.seq; - if (event.type === "thread.call.ended") { - onEnded({ - callId: asText(event.payload?.callId), - farewell: asText(event.payload?.farewell), - }); - return; - } - snapshot = applyMobileThreadEvent(snapshot, event) ?? snapshot; - if (!snapshot) return; - const message = latestSpokenCallReply(snapshot.messages, watchedCallId); - if (!message || message.id === lastSeen) return; - // Wait for the message's own run to settle so half-written blocks are never - // spoken; another run still working says nothing about this one. - const run = snapshot?.run; - const fromAnotherRun = Boolean(message.runId && message.runId !== run?.id); - if (!fromAnotherRun && run && ACTIVE_RUN_STATUSES.some((s) => s === run.status)) return; - const text = blockText(message).trim(); - if (!text) return; - lastSeen = message.id; - onNewReply(message.id, text, message.runId); - }, - controller.signal, - ); - retry = FEED_RETRY_MIN_MS; - } catch { - if (controller.signal.aborted) return; - retry = Math.min(FEED_RETRY_MAX_MS, retry * 2); - } - if (controller.signal.aborted) return; - await abortableDelay(retry, controller.signal); - } - })().catch(() => undefined); - return () => controller.abort(); -} - -function asText(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - -function randomId(): string { - const webCrypto = globalThis.crypto; - if (webCrypto && typeof webCrypto.randomUUID === "function") return webCrypto.randomUUID(); - return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; -} diff --git a/apps/mobile/lib/device-voice.test.ts b/apps/mobile/lib/device-voice.test.ts deleted file mode 100644 index c68a9700..00000000 --- a/apps/mobile/lib/device-voice.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import * as SecureStore from "expo-secure-store"; -import { beforeEach, describe, expect, it, vi } from "vitest"; - -const store = new Map(); -vi.mock("expo-secure-store", () => ({ - getItemAsync: vi.fn(async (key: string) => store.get(key) ?? null), - setItemAsync: vi.fn(async (key: string, value: string) => { - store.set(key, value); - }), - deleteItemAsync: vi.fn(async (key: string) => { - store.delete(key); - }), -})); - -describe("device voice preference", () => { - beforeEach(() => { - store.clear(); - vi.mocked(SecureStore.setItemAsync).mockImplementation(async (key: string, value: string) => { - store.set(key, value); - }); - vi.mocked(SecureStore.deleteItemAsync).mockImplementation(async (key: string) => { - store.delete(key); - }); - }); - - it("defaults to off", async () => { - const { loadDeviceVoiceEnabled } = await import("./device-voice"); - expect(await loadDeviceVoiceEnabled()).toBe(false); - }); - - it("persists on and off", async () => { - const { loadDeviceVoiceEnabled, saveDeviceVoiceEnabled } = await import("./device-voice"); - await saveDeviceVoiceEnabled(true); - expect(await loadDeviceVoiceEnabled()).toBe(true); - await saveDeviceVoiceEnabled(false); - expect(await loadDeviceVoiceEnabled()).toBe(false); - }); - - it("rejects when SecureStore cannot write, so callers can roll back", async () => { - vi.mocked(SecureStore.setItemAsync).mockRejectedValueOnce(new Error("device locked")); - const { saveDeviceVoiceEnabled, loadDeviceVoiceEnabled } = await import("./device-voice"); - - await expect(saveDeviceVoiceEnabled(true)).rejects.toThrow("device locked"); - expect(await loadDeviceVoiceEnabled()).toBe(false); - }); - - it("rejects when SecureStore cannot read, instead of treating the preference as off", async () => { - vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(new Error("device locked")); - const { loadDeviceVoiceEnabled } = await import("./device-voice"); - - await expect(loadDeviceVoiceEnabled()).rejects.toThrow("device locked"); - }); -}); diff --git a/apps/mobile/lib/device-voice.ts b/apps/mobile/lib/device-voice.ts deleted file mode 100644 index b9709078..00000000 --- a/apps/mobile/lib/device-voice.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as SecureStore from "expo-secure-store"; - -export const DEVICE_VOICE_KEY = "rakazo.device-voice"; - -export async function loadDeviceVoiceEnabled(): Promise { - return (await SecureStore.getItemAsync(DEVICE_VOICE_KEY)) === "1"; -} - -export async function saveDeviceVoiceEnabled(on: boolean): Promise { - if (on) await SecureStore.setItemAsync(DEVICE_VOICE_KEY, "1"); - else await SecureStore.deleteItemAsync(DEVICE_VOICE_KEY); -} diff --git a/apps/mobile/lib/dictation.test.ts b/apps/mobile/lib/dictation.test.ts deleted file mode 100644 index f2d5925f..00000000 --- a/apps/mobile/lib/dictation.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { SpeechRecognizer } from "./dictation"; -import { ENDPOINT_SILENCE_MS, listen, setSpeechRecognizer, stop } from "./dictation"; - -type Listener = (payload: never) => void; - -/** Longest restart delay the module backs off to. */ -const RESTART_CAP_MS = 2_000; - -function fakeRecognizer() { - const listeners = new Map>(); - const start = vi.fn(); - const abort = vi.fn(); - const recognizer: SpeechRecognizer = { - start, - stop: vi.fn(), - abort, - isRecognitionAvailable: () => true, - requestPermissionsAsync: async () => ({ granted: true }), - addListener: (event, listener) => { - const set = listeners.get(event) ?? new Set(); - set.add(listener as Listener); - listeners.set(event, set); - return { - remove: () => { - set.delete(listener as Listener); - }, - }; - }, - }; - const emit = (event: string, payload: unknown) => { - for (const listener of [...(listeners.get(event) ?? [])]) - (listener as (p: unknown) => void)(payload); - }; - return { - recognizer, - start, - abort, - hear: (transcript: string, isFinal = false) => - emit("result", { isFinal, results: [{ transcript, confidence: 0.9 }] }), - end: () => emit("end", null), - fail: (error: string) => emit("error", { error, message: error }), - }; -} - -let fake: ReturnType; - -beforeEach(() => { - vi.useFakeTimers(); - fake = fakeRecognizer(); - setSpeechRecognizer(fake.recognizer); -}); - -afterEach(() => { - stop(); - setSpeechRecognizer(null); - vi.useRealTimers(); -}); - -describe("mobile dictation", () => { - it("ends the turn only after the silence window, not on the recognizer's own final", async () => { - const onFinal = vi.fn(); - const interims: string[] = []; - await listen({ onFinal, onInterim: (text) => interims.push(text) }); - expect(fake.start).toHaveBeenCalledWith({ - lang: "en-US", - interimResults: true, - continuous: true, - }); - - fake.hear("how is the"); - fake.hear("how is the", true); - vi.advanceTimersByTime(ENDPOINT_SILENCE_MS - 400); - expect(onFinal).not.toHaveBeenCalled(); - - fake.hear("deploy going"); - vi.advanceTimersByTime(ENDPOINT_SILENCE_MS - 1); - expect(onFinal).not.toHaveBeenCalled(); - vi.advanceTimersByTime(1); - - expect(onFinal).toHaveBeenCalledTimes(1); - expect(onFinal).toHaveBeenCalledWith("how is the deploy going"); - expect(interims).toEqual(["how is the", "how is the", "how is the deploy going"]); - }); - - it("restarts a session that ended mid-turn and carries the words already heard", async () => { - const onFinal = vi.fn(); - await listen({ onFinal }); - fake.hear("hello there"); - - fake.end(); - expect(onFinal).not.toHaveBeenCalled(); - vi.advanceTimersByTime(250); - expect(fake.start).toHaveBeenCalledTimes(2); - - fake.hear("friend"); - vi.advanceTimersByTime(ENDPOINT_SILENCE_MS); - expect(onFinal).toHaveBeenCalledWith("hello there friend"); - }); - - it("gives up after restarts that hear nothing", async () => { - const onFinal = vi.fn(); - await listen({ onFinal }); - fake.hear("half a sentence"); - for (let attempt = 0; attempt < 6; attempt += 1) { - fake.end(); - vi.advanceTimersByTime(RESTART_CAP_MS); - } - expect(onFinal).toHaveBeenCalledTimes(1); - expect(onFinal).toHaveBeenCalledWith("half a sentence"); - }); - - it("never finalizes an aborted session", async () => { - const onFinal = vi.fn(); - const controller = new AbortController(); - await listen({ onFinal, signal: controller.signal }); - fake.hear("cancel this"); - - controller.abort(); - expect(fake.abort).toHaveBeenCalled(); - fake.hear("and this", true); - fake.end(); - vi.advanceTimersByTime(10_000); - - expect(onFinal).not.toHaveBeenCalled(); - }); - - it("ends the turn on a permission error instead of hanging on the mic", async () => { - const onFinal = vi.fn(); - await listen({ onFinal }); - fake.hear("open the door"); - fake.fail("not-allowed"); - expect(onFinal).toHaveBeenCalledWith("open the door"); - }); -}); diff --git a/apps/mobile/lib/dictation.ts b/apps/mobile/lib/dictation.ts deleted file mode 100644 index 376fd779..00000000 --- a/apps/mobile/lib/dictation.ts +++ /dev/null @@ -1,200 +0,0 @@ -/** - * On-device dictation for calls, mirroring the web store's endpoint mode: the recognizer - * reports words, and only a quiet gap measured here ends a turn. The recognizer's own - * `isFinal` / `end` is a breath or an OS timeout, never the caller finishing a sentence. - */ - -/** Quiet gap that ends an utterance. A natural breath is well under it, a finished turn well over. */ -export const ENDPOINT_SILENCE_MS = 1_200; -const RESTART_MIN_MS = 250; -const RESTART_MAX_MS = 2_000; -/** Restarts in a row that hear nothing: the recognizer is wedged, stop churning the mic. */ -const MAX_DEAD_RESTARTS = 5; -/** Errors that mean this turn cannot recover; the rest are routine and `end` restarts. */ -const FATAL_ERRORS = new Set(["not-allowed", "service-not-allowed", "audio-capture"]); - -type ResultEvent = { isFinal: boolean; results: { transcript: string }[] }; -type ErrorEvent = { error?: string }; -type DictationEventMap = { result: ResultEvent; end: null; error: ErrorEvent }; - -/** The slice of `expo-speech-recognition` this module needs, so tests can drive the events. */ -export type SpeechRecognizer = { - start(options: { lang: string; interimResults: boolean; continuous: boolean }): void; - stop(): void; - abort(): void; - isRecognitionAvailable(): boolean; - requestPermissionsAsync(): Promise<{ granted: boolean }>; - addListener( - event: Event, - listener: (payload: DictationEventMap[Event]) => void, - ): { remove: () => void }; -}; - -type Session = { - recognizer: SpeechRecognizer; - lang: string; - onInterim?: (text: string) => void; - onFinal: (text: string) => void; - subs: { remove: () => void }[]; - /** Text from earlier recognizer sessions of the same utterance. */ - carried: string; - /** Text of the recognizer session running now. */ - heard: string; - silence?: ReturnType; - restart?: ReturnType; - backoff: number; - deadRestarts: number; -}; - -let injected: SpeechRecognizer | null = null; -/** Test seam: an injected recognizer replaces the native module. */ -export function setSpeechRecognizer(recognizer: SpeechRecognizer | null): void { - injected = recognizer; -} - -async function load(): Promise { - if (injected) return injected; - const { ExpoSpeechRecognitionModule } = await import("expo-speech-recognition"); - return ExpoSpeechRecognitionModule as unknown as SpeechRecognizer; -} - -/** A session older than this one can never deliver a final. */ -let token = 0; -let active: Session | null = null; - -/** True when the device can recognise speech itself and the caller allowed it. */ -export async function available(): Promise { - try { - const recognizer = await load(); - if (!recognizer.isRecognitionAvailable()) return false; - return (await recognizer.requestPermissionsAsync()).granted; - } catch { - return false; - } -} - -export function stop(): void { - const session = active; - active = null; - token += 1; - if (!session) return; - clearTimeout(session.silence); - clearTimeout(session.restart); - for (const sub of session.subs) sub.remove(); - try { - session.recognizer.abort(); - } catch { - // already stopped - } -} - -/** Opens the microphone until a quiet gap ends the utterance, or `signal` aborts it. */ -export async function listen(opts: { - onInterim?: (text: string) => void; - onFinal: (text: string) => void; - signal?: AbortSignal; - lang?: string; -}): Promise { - stop(); - const mine = token; - if (opts.signal?.aborted) return; - const recognizer = await load(); - // A hang-up or a newer session landed while the native module was loading. - if (token !== mine) return; - const session: Session = { - recognizer, - lang: opts.lang || "en-US", - onInterim: opts.onInterim, - onFinal: opts.onFinal, - subs: [], - carried: "", - heard: "", - backoff: RESTART_MIN_MS, - deadRestarts: 0, - }; - active = session; - opts.signal?.addEventListener( - "abort", - () => { - if (active === session) stop(); - }, - { once: true }, - ); - session.subs = [ - recognizer.addListener("result", (event) => onResult(session, event)), - recognizer.addListener("end", () => onEnd(session)), - recognizer.addListener("error", (event) => onError(session, event)), - ]; - start(session); -} - -function start(session: Session): void { - if (active !== session) return; - session.recognizer.start({ lang: session.lang, interimResults: true, continuous: true }); -} - -function onResult(session: Session, event: ResultEvent): void { - if (active !== session) return; - const heard = event.results?.[0]?.transcript ?? ""; - session.backoff = RESTART_MIN_MS; - session.deadRestarts = 0; - // Android reports a phrase once and starts over, iOS grows one transcript: folding a - // final into the carried text and clearing the live one covers both. - if (event.isFinal) { - session.carried = join(session.carried, heard); - session.heard = ""; - } else { - session.heard = heard; - } - const text = join(session.carried, session.heard); - if (!text) return; - session.onInterim?.(text); - // Any result means the caller was just heard, so the quiet gap restarts here — including - // a phrase the recognizer finalises after repeating it, whose boundary is a breath. - clearTimeout(session.silence); - session.silence = setTimeout(() => finish(session), ENDPOINT_SILENCE_MS); -} - -function onEnd(session: Session): void { - if (active !== session) return; - // iOS ends a session on its own — on a pause, an interruption, or its own cap — and that - // says nothing about whether the caller finished. Pick the microphone straight back up. - session.carried = join(session.carried, session.heard); - session.heard = ""; - session.deadRestarts += 1; - if (session.deadRestarts > MAX_DEAD_RESTARTS) { - // ponytail: a wedged recognizer just ends the turn; the call opens the mic again next - // turn. Surface it as an error if callers ever need to tell it from a real endpoint. - finish(session); - return; - } - clearTimeout(session.restart); - const delay = session.backoff; - session.backoff = Math.min(RESTART_MAX_MS, session.backoff * 2); - session.restart = setTimeout(() => { - if (active !== session) return; - try { - start(session); - } catch { - finish(session); - } - }, delay); -} - -function onError(session: Session, event: ErrorEvent): void { - if (active !== session) return; - if (!event?.error || !FATAL_ERRORS.has(event.error)) return; - finish(session); -} - -function finish(session: Session): void { - if (active !== session) return; - const text = join(session.carried, session.heard).trim(); - const { onFinal } = session; - stop(); - if (text) onFinal(text); -} - -function join(left: string, right: string): string { - return `${left} ${right}`.replace(/\s+/g, " ").trim(); -} diff --git a/apps/mobile/lib/inbox-spaces.test.ts b/apps/mobile/lib/inbox-spaces.test.ts index 206740f4..9971c12c 100644 --- a/apps/mobile/lib/inbox-spaces.test.ts +++ b/apps/mobile/lib/inbox-spaces.test.ts @@ -54,7 +54,6 @@ const bot: MobileBot = { modelProvider: null, modelId: null, thinkingLevel: null, - autoSpeak: false, }; describe("spaceInboxItems", () => { diff --git a/apps/mobile/lib/locales/de.ts b/apps/mobile/lib/locales/de.ts index 7dc2929c..13ce8be9 100644 --- a/apps/mobile/lib/locales/de.ts +++ b/apps/mobile/lib/locales/de.ts @@ -36,7 +36,6 @@ export const DE_MESSAGES: Record = { Routine: "Routine", "Server integrations": "Server-Integrationen", Thread: "Thread", - Voice: "Stimme", // app/sign-in.tsx "Already have an account?": "Du hast bereits ein Konto?", "Back to sign in": "Zurück zur Anmeldung", @@ -92,7 +91,6 @@ export const DE_MESSAGES: Record = { unread: "ungelesen", // app/thread.tsx "@{name}": "@{name}", - "Add a voice provider in Voice settings.": "Füge unter Stimme einen Sprachanbieter hinzu.", Agent: "Agent", "Allowed once": "Einmal erlaubt", "Always allowed": "Immer erlaubt", @@ -125,7 +123,6 @@ export const DE_MESSAGES: Record = { "Could not open image": "Bild konnte nicht geöffnet werden", "Could not open message": "Nachricht konnte nicht geöffnet werden", "Could not send answer": "Antwort konnte nicht gesendet werden", - "Could not speak": "Vorlesen fehlgeschlagen", "Could not update reaction": "Reaktion konnte nicht aktualisiert werden", Created: "Erstellt", "Delete…": "Löschen…", @@ -166,7 +163,6 @@ export const DE_MESSAGES: Record = { "Show {label}": "{label} anzeigen", "Skill {name}": "Skill {name}", "Skipped {items}": "{items} übersprungen", - "Speak message": "Nachricht vorlesen", Stop: "Stoppen", "This removes every message and stops current work. The bot, computer, memory, and routines are kept.": "Das entfernt alle Nachrichten und stoppt die laufende Arbeit. Bot, Computer, Erinnerungen und Routinen bleiben erhalten.", @@ -302,7 +298,6 @@ export const DE_MESSAGES: Record = { "Model updated.": "Modell aktualisiert.", "No matching models": "Keine passenden Modelle", "Not connected": "Nicht verbunden", - "Not now": "Nicht jetzt", "Now using {label}.": "{label} ist jetzt aktiv.", "OpenAI-compatible server URL": "URL eines OpenAI-kompatiblen Servers", Optional: "Optional", @@ -411,33 +406,16 @@ export const DE_MESSAGES: Record = { "Project ID": "Projekt-ID", "Set up Executor on your server in the web app.": "Richte Executor auf deinem Server in der Web-App ein.", - // app/voice.tsx Connect: "Verbinden", - "Connect a voice provider first.": "Verbinde zuerst einen Sprachanbieter.", "Connected {name}.": "{name} verbunden.", "Could not disconnect": "Trennen fehlgeschlagen", - "Could not load voice settings": "Stimmeinstellungen konnten nicht geladen werden", - "Could not play a sample": "Beispiel konnte nicht abgespielt werden", "Could not save that preference": "Diese Einstellung konnte nicht gespeichert werden", - "Could not save that speech model": "Sprachmodell konnte nicht gespeichert werden", - "Could not save that voice": "Stimme konnte nicht gespeichert werden", "Disconnect {name}?": "{name} trennen?", Disconnect: "Trennen", "This removes the connection from every space.": "Die Verbindung wird in jedem Space entfernt.", "Disconnecting…": "Verbindung wird getrennt…", - "Hear a sample": "Beispiel anhören", - "Hi, this is how I'll sound when I read replies out loud.": - "Hallo, so klinge ich, wenn ich Antworten vorlese.", - "On · Free, works offline": "Ein · Kostenlos, funktioniert offline", - "Paste a replacement key": "Ersatzschlüssel einfügen", "Paste your API key": "Füge deinen API-Schlüssel ein", "Replace key": "Schlüssel ersetzen", - "Speak + transcribe": "Sprechen + transkribieren", - "Speak only": "Nur sprechen", - "Speech model": "Sprachmodell", - "This device": "Dieses Gerät", - "Your phone's built-in voice. Free, no account needed": - "Die eingebaute Stimme deines Telefons. Kostenlos, kein Konto nötig", // app/(tabs)/account/index.tsx "Agent messages": "Agent-Nachrichten", "Alerts from routines": "Meldungen von Routinen", @@ -465,6 +443,7 @@ export const DE_MESSAGES: Record = { "Needs attention": "Aufmerksamkeit erforderlich", "Notification settings": "Benachrichtigungseinstellungen", Notifications: "Benachrichtigungen", + "Not now": "Nicht jetzt", Organic: "Organisch", "Questions, approvals, takeover": "Fragen, Freigaben, Übernahme", "Replies and completed work": "Antworten und erledigte Arbeit", @@ -625,8 +604,6 @@ export const DE_MESSAGES: Record = { "Use an http or https URL": "Verwende eine http- oder https-URL", // lib/live-notifications.ts "Android blocked notifications.": "Android hat Benachrichtigungen blockiert.", - // lib/voice.ts - "Could not play that clip.": "Dieser Clip konnte nicht abgespielt werden.", // app/models.tsx "A sign-in page opened — enter this code there:": "Eine Anmeldeseite wurde geöffnet — gib dort diesen Code ein:", @@ -642,25 +619,7 @@ export const DE_MESSAGES: Record = { "Warte auf Anmeldung — der Code läuft in etwa {minutes} Minuten ab.", "Waiting for sign-in — the link expires in about {minutes} minutes.": "Warte auf Anmeldung — der Link läuft in etwa {minutes} Minuten ab.", - // call - "Allow microphone access to call a bot.": "Erlaube den Mikrofonzugriff, um einen Bot anzurufen.", - "Allow speech recognition in Settings, or connect ElevenLabs, OpenAI, or Fish Audio.": - "Erlaube die Spracherkennung in den Einstellungen oder verbinde ElevenLabs, OpenAI oder Fish Audio.", - Call: "Anrufen", - "Calls need transcription": "Anrufe brauchen eine Transkription", - "Could not hear that.": "Das war nicht zu verstehen.", - "Could not speak that.": "Das konnte nicht vorgelesen werden.", - "Could not transcribe that.": "Das konnte nicht transkribiert werden.", - "Hang up": "Auflegen", - "Hide transcript": "Transkript ausblenden", - Mute: "Stummschalten", - "On a call with {name}": "Im Gespräch mit {name}", - "Open Voice": "Sprache öffnen", Settings: "Einstellungen", - "Show transcript": "Transkript anzeigen", - Transcript: "Transkript", - Unmute: "Stummschaltung aufheben", - "Voice chat": "Sprachchat", // app/agent-models.tsx "Could not load models.": "Modelle konnten nicht geladen werden.", "In use": "Aktiv", diff --git a/apps/mobile/lib/locales/ru.ts b/apps/mobile/lib/locales/ru.ts index aba024d8..18c0d0ea 100644 --- a/apps/mobile/lib/locales/ru.ts +++ b/apps/mobile/lib/locales/ru.ts @@ -141,7 +141,6 @@ export const RU_MESSAGES: Record = { Back: "Назад", Bot: "Бот", "Bot actions": "Действия бота", - "Calls need transcription": "Для звонков нужна транскрипция", "Booting live desktop…": "Запуск рабочего стола…", Camera: "Камера", Cancel: "Отмена", @@ -171,9 +170,6 @@ export const RU_MESSAGES: Record = { "Computer is stopped": "Компьютер остановлен", "Configured by deployment": "Настроено развёртыванием", Connect: "Подключить", - "Allow speech recognition in Settings, or connect ElevenLabs, OpenAI, or Fish Audio.": - "Разрешите распознавание речи в Настройках или подключите ElevenLabs, OpenAI или Fish Audio.", - "Connect a voice provider first.": "Сначала подключите провайдера голосовой связи.", "Connect API key": "Подключить API-ключ", "Connect Executor": "Подключить Executor", "Connect MCP server {name}": "Подключение MCP-сервера {name}", @@ -222,13 +218,10 @@ export const RU_MESSAGES: Record = { "Could not load the desktop. This device cannot reach the screen URL.": "Не удалось загрузить рабочий стол. Это устройство не может получить доступ к URL-адресу экрана.", "Could not load this file.": "Не удалось загрузить этот файл.", - "Could not load voice settings": "Не удалось загрузить голосовые настройки.", "Could not open computer": "Не удалось открыть компьютер", "Could not open file": "Не удалось открыть файл", "Could not open image": "Не удалось открыть изображение", "Could not open message": "Не удалось открыть сообщение", - "Could not play a sample": "Не удалось воспроизвести сэмпл", - "Could not play that clip.": "Не удалось воспроизвести этот клип.", "Could not reach that server": "Не удалось связаться с этим сервером", "Could not reach this model server": "Не удалось связаться с сервером этой модели.", "Could not remove source": "Не удалось удалить источник", @@ -236,15 +229,12 @@ export const RU_MESSAGES: Record = { "Could not revoke connection": "Не удалось отменить соединение", "Could not save bot": "Не удалось сохранить бота", "Could not save group": "Не удалось сохранить группу", - "Could not save that speech model": "Не удалось сохранить речевую модель", - "Could not save that voice": "Не удалось сохранить этот голос", "Could not save the default space": "Не удалось сохранить пространство по умолчанию.", "Could not save the server URL": "Не удалось сохранить URL-адрес сервера.", "Could not send reset email": "Не удалось отправить электронное письмо для сброса", "Could not send answer": "Не удалось отправить ответ", "Could not share file": "Не удалось поделиться файлом", "Could not sign out": "Не удалось выйти", - "Could not speak": "Не удалось озвучить", "Could not start sign-in": "Не удалось начать вход", "Could not submit answer": "Не удалось отправить ответ", "Could not switch computer": "Не удалось переключить компьютер", @@ -313,13 +303,9 @@ export const RU_MESSAGES: Record = { "Group name": "Название группы", "Group not found": "Группа не найдена", "Group settings": "Настройки группы", - "Hear a sample": "Прослушать образец", Hide: "Скрыть", "Hide {label}": "Скрыть {label}", - "Hi, this is how I'll sound when I read replies out loud.": - "Привет, вот как я буду звучать, когда буду читать ответы вслух.", "I’m done": "Готово", - "If you heard that, voice is ready.": "Если вы это услышали, голос готов.", Integrations: "Интеграции", "If an account exists for that address, we sent a password reset link.": "Если для этого адреса существует учетная запись, мы отправили ссылку для сброса пароля.", @@ -375,7 +361,6 @@ export const RU_MESSAGES: Record = { "No messages yet": "Сообщений пока нет", "No results": "Нет результатов", "Not connected": "Не подключено", - "Not now": "Не сейчас", "Now using {label}.": "Сейчас используется {label}.", Now: "Сейчас", Notifications: "Уведомления", @@ -385,10 +370,10 @@ export const RU_MESSAGES: Record = { "notifications silenced": "уведомления отключены", "Open computer": "Открыть компьютер", "Open computer →": "Открыть компьютер →", - "Open Voice": "Открыть настройки голоса", "OpenAI-compatible server URL": "URL-адрес сервера, совместимого с OpenAI", Optional: "Необязательно", "Or connect an API key": "Или подключите API-ключ", + "Not now": "Не сейчас", Organic: "Органичный", "Other model…": "Другая модель…", Password: "Пароль", @@ -396,7 +381,6 @@ export const RU_MESSAGES: Record = { "Восстановление пароля не настроено для этого сервера", "Password updated": "Пароль обновлён", "Passwords do not match": "Пароли не совпадают", - "Paste a replacement key": "Вставьте запасной ключ", "Paste your API key": "Вставьте свой ключ API", Personal: "Личные", "Personal credential": "Личные учётные данные", @@ -481,11 +465,6 @@ export const RU_MESSAGES: Record = { "Space actions for {name}": "Действия пространства {name}", "Space created": "Пространство создано", "Read replies aloud": "Читать ответы вслух", - "Speak + transcribe": "Озвучить и расшифровать", - "Speak message": "Озвучить сообщение", - Speak: "Озвучить", - "Speak only": "Только озвучить", - "Speech model": "Речевая модель", Starting: "Запуск", "Starting…": "Запуск…", Stop: "Остановить", @@ -518,7 +497,6 @@ export const RU_MESSAGES: Record = { "Use an http or https URL": "Используйте URL-адрес http или https.", "Use default server": "Использовать сервер по умолчанию", "Use this model": "Использовать эту модель", - Voice: "Голос", Webhook: "Вебхук", "Waiting for sign-in…": "Ожидание входа в систему…", "Waiting for this bot’s response.": "Ожидание ответа этого бота.", @@ -536,8 +514,6 @@ export const RU_MESSAGES: Record = { Actions: "Действия", Active: "Активный", Add: "Добавить", - "Add a voice provider in Voice settings.": - "Добавьте провайдера голосовой связи в настройках голоса.", Advanced: "Расширенные", "Supports thinking": "Поддерживает рассуждения", "Reasoning effort": "Уровень рассуждений", @@ -628,10 +604,6 @@ export const RU_MESSAGES: Record = { "{name} (permission denied)": "{name} (в разрешении отказано)", "{name} (unsupported type)": "{name} (неподдерживаемый тип)", "Saved {name} locally": "{name} сохранен локально.", - "This device": "Это устройство", - "On · Free, works offline": "Включено · Бесплатно, работает офлайн", - "Your phone's built-in voice. Free, no account needed": - "Встроенный голос телефона. Бесплатно, без аккаунта", "Could not save that preference": "Не удалось сохранить эту настройку", Username: "Имя пользователя", // app/models.tsx @@ -649,20 +621,7 @@ export const RU_MESSAGES: Record = { "Ожидание входа — срок действия кода истекает примерно через {minutes} мин.", "Waiting for sign-in — the link expires in about {minutes} minutes.": "Ожидание входа — срок действия ссылки истекает примерно через {minutes} мин.", - "On a call with {name}": "Звонок с {name}", - Call: "Позвонить", Settings: "Настройки", - Transcript: "Расшифровка", - Mute: "Выключить микрофон", - Unmute: "Включить микрофон", - "Hang up": "Завершить", - "Allow microphone access to call a bot.": "Разрешите доступ к микрофону, чтобы звонить боту.", - "Could not hear that.": "Не удалось расслышать.", - "Could not transcribe that.": "Не удалось распознать речь.", - "Could not speak that.": "Не удалось озвучить.", - "Voice chat": "Голосовой чат", - "Show transcript": "Показать расшифровку", - "Hide transcript": "Скрыть расшифровку", // app/agent-models.tsx "Could not load models.": "Не удалось загрузить модели.", "In use": "Используется", diff --git a/apps/mobile/lib/locales/zh.ts b/apps/mobile/lib/locales/zh.ts index 2f94de30..b3038b86 100644 --- a/apps/mobile/lib/locales/zh.ts +++ b/apps/mobile/lib/locales/zh.ts @@ -128,7 +128,6 @@ export const ZH_MESSAGES: Record = { Back: "返回", Bot: "Bot", "Bot actions": "Bot 操作", - "Calls need transcription": "通话需要语音转文字", "Booting live desktop…": "正在启动实时桌面…", Camera: "相机", Cancel: "取消", @@ -157,9 +156,6 @@ export const ZH_MESSAGES: Record = { "Computer is stopped": "电脑已停止", "Configured by deployment": "由部署配置", Connect: "连接", - "Connect a voice provider first.": "请先连接语音提供商。", - "Allow speech recognition in Settings, or connect ElevenLabs, OpenAI, or Fish Audio.": - "请在“设置”中允许语音识别,或连接 ElevenLabs、OpenAI 或 Fish Audio。", "Connect API key": "连接 API 密钥", "Connect Executor": "连接 Executor", "Connect MCP server {name}": "连接 MCP 服务器 {name}", @@ -206,13 +202,10 @@ export const ZH_MESSAGES: Record = { "Could not load the desktop. This device cannot reach the screen URL.": "无法加载桌面。此设备无法访问屏幕地址。", "Could not load this file.": "无法加载此文件。", - "Could not load voice settings": "无法加载语音设置", "Could not open computer": "无法打开电脑", "Could not open file": "无法打开文件", "Could not open image": "无法打开图片", "Could not open message": "无法打开消息", - "Could not play a sample": "无法播放示例", - "Could not play that clip.": "无法播放该音频。", "Could not reach that server": "无法连接到该服务器", "Could not reach this model server": "无法连接到此模型服务器", "Could not remove source": "无法移除此来源", @@ -220,15 +213,12 @@ export const ZH_MESSAGES: Record = { "Could not revoke connection": "无法撤销连接", "Could not save bot": "无法保存 Bot", "Could not save group": "无法保存群组", - "Could not save that speech model": "无法保存该语音模型", - "Could not save that voice": "无法保存该语音", "Could not save the default space": "无法保存默认空间", "Could not save the server URL": "无法保存服务器地址", "Could not send reset email": "无法发送重置邮件", "Could not send answer": "无法发送回答", "Could not share file": "无法分享文件", "Could not sign out": "无法退出登录", - "Could not speak": "无法朗读", "Could not start sign-in": "无法开始登录", "Could not submit answer": "无法提交回答", "Could not switch computer": "无法切换电脑", @@ -296,12 +286,9 @@ export const ZH_MESSAGES: Record = { "Group name": "群组名称", "Group not found": "找不到群组", "Group settings": "群组设置", - "Hear a sample": "试听示例", Hide: "隐藏", "Hide {label}": "隐藏 {label}", - "Hi, this is how I'll sound when I read replies out loud.": "你好,这是我朗读回复时的声音。", "I’m done": "我完成了", - "If you heard that, voice is ready.": "如果你听到了,说明语音已就绪。", Integrations: "集成", "If an account exists for that address, we sent a password reset link.": "如果该地址已有账户,我们已发送密码重置链接。", @@ -357,7 +344,6 @@ export const ZH_MESSAGES: Record = { "No messages yet": "还没有消息", "No results": "没有结果", "Not connected": "未连接", - "Not now": "暂不", "Now using {label}.": "正在使用 {label}。", Now: "现在", Notifications: "通知", @@ -366,18 +352,17 @@ export const ZH_MESSAGES: Record = { "Notifications silenced": "通知已静音", "notifications silenced": "通知已静音", "Open computer": "打开电脑", - "Open Voice": "打开语音设置", "Open computer →": "打开电脑 →", "OpenAI-compatible server URL": "OpenAI 兼容服务器地址", Optional: "可选", "Or connect an API key": "或连接 API 密钥", + "Not now": "暂不", Organic: "有机", "Other model…": "其他模型…", Password: "密码", "Password recovery is not configured for this server": "此服务器未配置密码找回", "Password updated": "密码已更新", "Passwords do not match": "两次输入的密码不一致", - "Paste a replacement key": "粘贴替换密钥", "Paste your API key": "粘贴你的 API 密钥", Personal: "个人", "Personal credential": "个人凭证", @@ -462,11 +447,6 @@ export const ZH_MESSAGES: Record = { "Space created": "空间已创建", "Space default": "空间默认", "Read replies aloud": "朗读回复", - "Speak + transcribe": "朗读并转写", - "Speak message": "朗读消息", - Speak: "朗读", - "Speak only": "仅朗读", - "Speech model": "语音模型", Starting: "正在启动", "Starting…": "正在启动…", Stop: "停止", @@ -499,7 +479,6 @@ export const ZH_MESSAGES: Record = { "Use an http or https URL": "请使用 http 或 https 地址", "Use default server": "使用默认服务器", "Use this model": "使用此模型", - Voice: "语音", Webhook: "Webhook", "Waiting for sign-in…": "正在等待登录…", "Waiting for this bot’s response.": "正在等待这个 Bot 的回复。", @@ -516,7 +495,6 @@ export const ZH_MESSAGES: Record = { Actions: "操作", Active: "启用", Add: "添加", - "Add a voice provider in Voice settings.": "请先在语音设置中添加语音提供商。", Advanced: "高级", "Supports thinking": "支持思考", "Reasoning effort": "推理强度", @@ -610,9 +588,6 @@ export const ZH_MESSAGES: Record = { "Extra high": "超高", Low: "低", High: "高", - "This device": "本设备", - "On · Free, works offline": "已开启 · 免费,可离线使用", - "Your phone's built-in voice. Free, no account needed": "手机自带的语音。免费,无需账户", "Could not save that preference": "无法保存该设置", Username: "用户名", // app/models.tsx @@ -629,20 +604,7 @@ export const ZH_MESSAGES: Record = { "等待登录——代码将在约 {minutes} 分钟后过期。", "Waiting for sign-in — the link expires in about {minutes} minutes.": "等待登录——链接将在约 {minutes} 分钟后过期。", - "On a call with {name}": "正在与 {name} 通话", - Call: "通话", Settings: "设置", - Transcript: "字幕", - Mute: "静音", - Unmute: "取消静音", - "Hang up": "挂断", - "Allow microphone access to call a bot.": "请允许使用麦克风,以便与 Bot 通话。", - "Could not hear that.": "没有听清。", - "Could not transcribe that.": "无法转写。", - "Could not speak that.": "无法朗读。", - "Voice chat": "语音通话", - "Show transcript": "显示字幕", - "Hide transcript": "隐藏字幕", // app/agent-models.tsx "Could not load models.": "无法加载模型。", "In use": "使用中", diff --git a/apps/mobile/lib/message-presentation.test.ts b/apps/mobile/lib/message-presentation.test.ts index c805a7fb..cb32feb3 100644 --- a/apps/mobile/lib/message-presentation.test.ts +++ b/apps/mobile/lib/message-presentation.test.ts @@ -162,8 +162,8 @@ describe("truncateQuoteExcerpt", () => { }); it("does not split a surrogate pair at the boundary", () => { - const excerpt = "x".repeat(REPLY_QUOTE_MAX_LENGTH - 1) + "😀"; - const truncated = truncateQuoteExcerpt(excerpt + "tail"); + const excerpt = `${"x".repeat(REPLY_QUOTE_MAX_LENGTH - 1)}😀`; + const truncated = truncateQuoteExcerpt(`${excerpt}tail`); expect(truncated).toHaveLength(REPLY_QUOTE_MAX_LENGTH - 1); expect(truncated).toBe("x".repeat(REPLY_QUOTE_MAX_LENGTH - 1)); }); diff --git a/apps/mobile/lib/voice-call-entry.test.ts b/apps/mobile/lib/voice-call-entry.test.ts deleted file mode 100644 index 036bcf88..00000000 --- a/apps/mobile/lib/voice-call-entry.test.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import type { VoiceCallStatus } from "./voice-call-entry"; -import { probeProviderTranscribe, resolveVoiceCallPlan } from "./voice-call-entry"; - -function deps(options: { deviceVoice: boolean; dictation: boolean; status: VoiceCallStatus }) { - return { - loadDeviceVoiceEnabled: vi.fn(async () => options.deviceVoice), - dictationAvailable: vi.fn(async () => options.dictation), - loadVoiceStatus: vi.fn(async () => options.status), - }; -} - -describe("mobile voice call entry", () => { - it("starts a device-only call without asking the API for provider readiness", async () => { - const fakes = deps({ - deviceVoice: true, - dictation: true, - status: { ready: false, transcribe: false }, - }); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ - kind: "device", - transcribe: false, - }); - expect(fakes.loadVoiceStatus).not.toHaveBeenCalled(); - }); - - it("reports missing speech recognition instead of opening provider setup", async () => { - const fakes = deps({ - deviceVoice: true, - dictation: false, - status: { ready: false, transcribe: false }, - }); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ kind: "dictation" }); - expect(fakes.loadVoiceStatus).toHaveBeenCalledOnce(); - }); - - it("keeps the normal cloud provider path when device voice is off", async () => { - const fakes = deps({ - deviceVoice: false, - dictation: false, - status: { ready: true, transcribe: true }, - }); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ - kind: "provider", - transcribe: true, - }); - expect(fakes.dictationAvailable).not.toHaveBeenCalled(); - }); - - it("keeps provider setup when only on-device dictation is available", async () => { - const fakes = deps({ - deviceVoice: false, - dictation: true, - status: { ready: false, transcribe: false }, - }); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ kind: "settings" }); - expect(fakes.dictationAvailable).not.toHaveBeenCalled(); - }); - - it("falls back to provider transcription when local dictation is unavailable", async () => { - const fakes = deps({ - deviceVoice: true, - dictation: false, - status: { ready: true, transcribe: true }, - }); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ - kind: "provider", - transcribe: true, - }); - }); - - it("uses on-device dictation with a configured speak-only provider", async () => { - const fakes = deps({ - deviceVoice: false, - dictation: true, - status: { ready: true, transcribe: false }, - }); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ - kind: "provider", - transcribe: false, - }); - expect(fakes.dictationAvailable).toHaveBeenCalledOnce(); - }); - - it("fails closed to device voice if its preference cannot be read", async () => { - const fakes = deps({ - deviceVoice: true, - dictation: true, - status: { ready: false, transcribe: false }, - }); - fakes.loadDeviceVoiceEnabled.mockRejectedValueOnce(new Error("device locked")); - - await expect(resolveVoiceCallPlan(fakes)).resolves.toEqual({ - kind: "device", - transcribe: false, - }); - expect(fakes.loadVoiceStatus).not.toHaveBeenCalled(); - }); -}); - -describe("probeProviderTranscribe", () => { - it("is true only when the provider is ready to transcribe", async () => { - const loadVoiceStatus = vi.fn(async () => ({ ready: true, transcribe: true })); - - await expect(probeProviderTranscribe(loadVoiceStatus)).resolves.toBe(true); - }); - - it("is false when the provider is not ready", async () => { - const loadVoiceStatus = vi.fn(async () => ({ ready: false, transcribe: true })); - - await expect(probeProviderTranscribe(loadVoiceStatus)).resolves.toBe(false); - }); - - it("is false for a speak-only provider", async () => { - const loadVoiceStatus = vi.fn(async () => ({ ready: true, transcribe: false })); - - await expect(probeProviderTranscribe(loadVoiceStatus)).resolves.toBe(false); - }); - - it("is false when the status probe throws", async () => { - const loadVoiceStatus = vi.fn(async () => { - throw new Error("offline"); - }); - - await expect(probeProviderTranscribe(loadVoiceStatus)).resolves.toBe(false); - }); -}); diff --git a/apps/mobile/lib/voice-call-entry.ts b/apps/mobile/lib/voice-call-entry.ts deleted file mode 100644 index 4771aaa7..00000000 --- a/apps/mobile/lib/voice-call-entry.ts +++ /dev/null @@ -1,58 +0,0 @@ -export type VoiceCallStatus = { ready: boolean; transcribe: boolean }; - -export type VoiceCallPlan = - | { kind: "device"; transcribe: false } - | { kind: "provider"; transcribe: boolean } - | { kind: "settings" } - | { kind: "dictation" }; - -export type VoiceCallPlanDeps = { - loadDeviceVoiceEnabled: () => Promise; - dictationAvailable: () => Promise; - loadVoiceStatus: () => Promise; -}; - -/** - * Chooses the call input/output path before any provider setup is required. - * A device voice preference is fail-closed like speakText: a read failure must - * not turn a local-only reply into hosted voice traffic. - */ -export async function resolveVoiceCallPlan(deps: VoiceCallPlanDeps): Promise { - let deviceVoiceEnabled = false; - try { - deviceVoiceEnabled = await deps.loadDeviceVoiceEnabled(); - } catch { - deviceVoiceEnabled = true; - } - - const deviceDictationAvailable = deviceVoiceEnabled ? await deps.dictationAvailable() : false; - if (deviceVoiceEnabled && deviceDictationAvailable) { - return { kind: "device", transcribe: false }; - } - - const status = await deps.loadVoiceStatus(); - if (!status.ready) { - return deviceVoiceEnabled ? { kind: "dictation" } : { kind: "settings" }; - } - - if (!status.transcribe) { - const canDictate = deviceVoiceEnabled - ? deviceDictationAvailable - : await deps.dictationAvailable(); - if (!canDictate) return { kind: "dictation" }; - } - - return { kind: "provider", transcribe: status.transcribe }; -} - -/** True only when the provider is ready to transcribe. Any other outcome is false. */ -export async function probeProviderTranscribe( - loadVoiceStatus: () => Promise, -): Promise { - try { - const status = await loadVoiceStatus(); - return status.ready && status.transcribe; - } catch { - return false; - } -} diff --git a/apps/mobile/lib/voice.test.ts b/apps/mobile/lib/voice.test.ts deleted file mode 100644 index d47714f3..00000000 --- a/apps/mobile/lib/voice.test.ts +++ /dev/null @@ -1,305 +0,0 @@ -import * as SecureStore from "expo-secure-store"; -import * as Speech from "expo-speech"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { captureApiRequestContext, currentApiBase, rpc } from "./api"; -import { - MAX_VOICE_AUDIO_BYTES, - playMpeg, - speakText, - speakUtterance, - speakWithDeviceVoice, - VOICE_RESPONSE_TIMEOUT_MS, -} from "./voice"; - -vi.mock("./ai-consent", () => ({ promptAiConsent: vi.fn() })); -vi.mock("expo-file-system", () => ({ File: class {}, Paths: {} })); -vi.mock("expo-secure-store", () => ({ - getItemAsync: vi.fn(), - setItemAsync: vi.fn(), - deleteItemAsync: vi.fn(), -})); -vi.mock("expo-speech", () => ({ speak: vi.fn(), stop: vi.fn() })); -vi.mock("./api", () => ({ - aiConsentCoalesceKey: vi.fn(() => "test-consent-context"), - authHeaders: vi.fn(), - captureApiRequestContext: vi.fn(), - currentApiBase: vi.fn(() => "https://api.example"), - rpc: vi.fn(), -})); - -class FakeAudio { - onended: (() => void) | null = null; - onerror: (() => void) | null = null; - src = ""; - - async play() { - setTimeout(() => this.onended?.(), 0); - } - - pause() {} -} - -describe("mobile speech", () => { - beforeEach(() => { - vi.mocked(SecureStore.getItemAsync).mockResolvedValue(null); - vi.mocked(captureApiRequestContext).mockResolvedValue({ - apiBase: "https://support.example", - headers: { - authorization: "Bearer support-token", - "x-rakazo-space-id": "space-support", - }, - }); - vi.mocked(rpc).mockImplementation(async (proc) => { - if (proc === "aiConsent/status") return { version: "2026-09-14", recipients: [] } as never; - vi.mocked(currentApiBase).mockReturnValue("https://finance.example"); - return { ready: true, utterances: ["First", "Second"] } as never; - }); - vi.stubGlobal("Audio", FakeAudio); - vi.stubGlobal( - "fetch", - vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), { status: 200 })), - ); - }); - - afterEach(() => { - vi.useRealTimers(); - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }); - - it("keeps every request on the server and space captured before preparation", async () => { - await expect(speakText("Read this", { botId: "bot-1" })).resolves.toBe(true); - - const requestContext = { - apiBase: "https://support.example", - headers: { - authorization: "Bearer support-token", - "x-rakazo-space-id": "space-support", - }, - }; - expect(rpc).toHaveBeenCalledWith( - "voice/prepare", - { text: "Read this", voiceId: undefined, botId: "bot-1" }, - { requestContext }, - ); - expect(captureApiRequestContext).toHaveBeenCalledTimes(1); - const fetchMock = vi.mocked(fetch); - expect(fetchMock).toHaveBeenCalledTimes(2); - for (const [url, init] of fetchMock.mock.calls) { - expect(url).toBe("https://support.example/api/voice/speak"); - expect(init?.headers).toMatchObject(requestContext.headers); - } - }); - - it("listens for an HTML audio clip ending before playback starts", async () => { - class ImmediateAudio { - onended: (() => void) | null = null; - onerror: (() => void) | null = null; - - async play() { - expect(this.onended).toBeTypeOf("function"); - this.onended?.(); - } - } - vi.stubGlobal("Audio", ImmediateAudio); - - await expect(playMpeg(new Uint8Array([1, 2, 3]))).resolves.toBeUndefined(); - }); - - it("rejects oversized audio without waiting for response cancellation", async () => { - const cancel = vi.fn(() => new Promise(() => undefined)); - vi.stubGlobal( - "fetch", - vi.fn( - async () => - new Response(new ReadableStream({ cancel }), { - headers: { "content-length": String(MAX_VOICE_AUDIO_BYTES + 1) }, - }), - ), - ); - - await expect( - speakUtterance("Hello.", { requestContext: await captureApiRequestContext() }), - ).rejects.toThrow("Voice response is too large."); - expect(cancel).toHaveBeenCalledOnce(); - }); - - it("times out while a voice response body is stalled", async () => { - vi.useFakeTimers(); - vi.stubGlobal( - "fetch", - vi.fn( - async () => - new Response( - new ReadableStream({ - pull: () => new Promise(() => undefined), - }), - ), - ), - ); - - const pending = speakUtterance("Hello.", { - requestContext: await captureApiRequestContext(), - }); - const rejected = expect(pending).rejects.toThrow("Voice request timed out."); - await vi.advanceTimersByTimeAsync(VOICE_RESPONSE_TIMEOUT_MS); - - await rejected; - }); -}); - -async function flushDeviceSpeechImport() { - for (let i = 0; i < 5; i++) await Promise.resolve(); - await new Promise((resolve) => setTimeout(resolve, 0)); -} - -describe("on-device speech", () => { - beforeEach(() => { - vi.mocked(Speech.speak).mockReset(); - vi.mocked(Speech.stop).mockReset(); - vi.mocked(rpc).mockReset(); - vi.stubGlobal( - "fetch", - vi.fn(() => { - throw new Error("on-device speech must not touch the network"); - }), - ); - }); - - afterEach(() => { - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }); - - it("speaks locally and never touches the network when the device voice is on", async () => { - vi.mocked(SecureStore.getItemAsync).mockResolvedValue("1"); - vi.mocked(Speech.speak).mockImplementation((_text, options) => options?.onDone?.()); - - await expect(speakText("Read this")).resolves.toBe(true); - - expect(Speech.stop).toHaveBeenCalledOnce(); - expect(Speech.speak).toHaveBeenCalledWith("Read this", expect.any(Object)); - expect(rpc).not.toHaveBeenCalled(); - expect(fetch).not.toHaveBeenCalled(); - }); - - it("uses on-device speech when the preference cannot be read, and never hosts the reply", async () => { - vi.mocked(SecureStore.getItemAsync).mockRejectedValue(new Error("device locked")); - vi.mocked(Speech.speak).mockImplementation((_text, options) => options?.onDone?.()); - - await expect(speakText("Read this")).resolves.toBe(true); - - expect(Speech.speak).toHaveBeenCalledWith("Read this", expect.any(Object)); - expect(rpc).not.toHaveBeenCalled(); - expect(fetch).not.toHaveBeenCalled(); - }); - - it("resolves false on empty text without calling the OS engine", async () => { - await expect(speakWithDeviceVoice(" ")).resolves.toBe(false); - expect(Speech.speak).not.toHaveBeenCalled(); - }); - - it("rejects with the OS engine's own error instead of resolving false", async () => { - vi.mocked(Speech.speak).mockImplementation((_text, options) => - options?.onError?.(new Error("synth failed")), - ); - - await expect(speakWithDeviceVoice("Hello")).rejects.toThrow("synth failed"); - }); - - it("rejects when expo-speech is not usable instead of calling hosted voice", async () => { - const originalSpeak = Speech.speak; - Object.defineProperty(Speech, "speak", { configurable: true, value: undefined }); - try { - await expect(speakWithDeviceVoice("Hello")).rejects.toThrow("Could not play that clip."); - expect(rpc).not.toHaveBeenCalled(); - expect(fetch).not.toHaveBeenCalled(); - } finally { - Object.defineProperty(Speech, "speak", { configurable: true, value: originalSpeak }); - } - }); - - it("strips markdown and splits a long reply into bounded utterances, in order", async () => { - const spoken: string[] = []; - vi.mocked(Speech.speak).mockImplementation((text, options) => { - spoken.push(text); - options?.onDone?.(); - }); - const longSentence = `${"word ".repeat(70).trim()}.`; - const text = `**Bold** intro. ${longSentence} A short close.`; - - await expect(speakWithDeviceVoice(text)).resolves.toBe(true); - - expect(spoken.length).toBeGreaterThan(1); - for (const utterance of spoken) { - expect(utterance.length).toBeLessThan(500); - expect(utterance).not.toContain("**"); - } - expect(spoken.join(" ")).toContain("Bold intro"); - }); - - it("stops queuing more chunks once a newer call interrupts it", async () => { - const calls: Array<{ text: string; options: Parameters[1] }> = []; - vi.mocked(Speech.speak).mockImplementation((text, options) => { - calls.push({ text, options }); - }); - - const first = speakWithDeviceVoice("First sentence. Second sentence."); - await flushDeviceSpeechImport(); - expect(calls.map((c) => c.text)).toEqual(["First sentence."]); - - const second = speakWithDeviceVoice("Different message."); - calls[0]?.options?.onStopped?.(); - await flushDeviceSpeechImport(); - - expect(calls.map((c) => c.text)).not.toContain("Second sentence."); - await expect(first).resolves.toBe(true); - - calls[1]?.options?.onDone?.(); - await expect(second).resolves.toBe(true); - expect(calls.map((c) => c.text)).toEqual(["First sentence.", "Different message."]); - }); - - it("awaits Speech.stop before speaking and skips if a newer session started during stop", async () => { - let releaseStop: () => void = () => undefined; - const stopPending = new Promise((resolve) => { - releaseStop = resolve; - }); - vi.mocked(Speech.stop).mockReturnValue(stopPending); - vi.mocked(Speech.speak).mockImplementation((_text, options) => options?.onDone?.()); - - const first = speakWithDeviceVoice("Hello there."); - await flushDeviceSpeechImport(); - expect(Speech.speak).not.toHaveBeenCalled(); - - const second = speakWithDeviceVoice("Different message."); - await flushDeviceSpeechImport(); - releaseStop(); - await flushDeviceSpeechImport(); - - await expect(first).resolves.toBe(true); - await expect(second).resolves.toBe(true); - expect(Speech.speak).toHaveBeenCalledOnce(); - expect(Speech.speak).toHaveBeenCalledWith("Different message.", expect.any(Object)); - }); - - it("resolves true, not false, when interrupted on its final utterance", async () => { - const calls: Array<{ text: string; options: Parameters[1] }> = []; - vi.mocked(Speech.speak).mockImplementation((text, options) => { - calls.push({ text, options }); - }); - - const first = speakWithDeviceVoice("Only one sentence here."); - await flushDeviceSpeechImport(); - expect(calls).toHaveLength(1); - - const second = speakWithDeviceVoice("Different message."); - calls[0]?.options?.onStopped?.(); - await flushDeviceSpeechImport(); - - await expect(first).resolves.toBe(true); - - calls[1]?.options?.onDone?.(); - await expect(second).resolves.toBe(true); - }); -}); diff --git a/apps/mobile/lib/voice.ts b/apps/mobile/lib/voice.ts deleted file mode 100644 index ff2af4f7..00000000 --- a/apps/mobile/lib/voice.ts +++ /dev/null @@ -1,342 +0,0 @@ -import { ensureAiDataConsent, readBoundedResponseBytes, toUtterances } from "@milo/core"; -import { File, Paths } from "expo-file-system"; -import type * as ExpoSpeech from "expo-speech"; -import { promptAiConsent } from "./ai-consent"; -import type { ApiRequestContext } from "./api"; -import { aiConsentCoalesceKey, captureApiRequestContext, rpc } from "./api"; -import { loadDeviceVoiceEnabled } from "./device-voice"; -import { t } from "./i18n"; - -type SpeechOptions = { voiceId?: string; botId?: string }; -export const VOICE_RESPONSE_TIMEOUT_MS = 70_000; -export const MAX_VOICE_AUDIO_BYTES = 16 * 1024 * 1024; -const MAX_VOICE_ERROR_BYTES = 64 * 1024; - -/** Bumped by every new reply and by stopSpeaking, so an old one drops its queued clips. */ -let speechGeneration = 0; -/** Ends the clip playing right now, if any. */ -let stopPlayback: (() => void) | null = null; - -/** Cuts the reply off mid-sentence, for a caller who talked over it. */ -export function stopSpeaking(): void { - speechGeneration += 1; - stopPlayback?.(); -} - -export async function speakText(text: string, opts: SpeechOptions = {}): Promise { - let useDeviceVoice = false; - try { - useDeviceVoice = await loadDeviceVoiceEnabled(); - } catch { - // A read failure must not be treated as "off": that would send reply text - // through hosted voice after the user opted for on-device only. - useDeviceVoice = true; - } - if (useDeviceVoice) return speakWithDeviceVoice(text); - const requestContext = await captureApiRequestContext(); - const prepared = await rpc<{ ready: boolean; utterances: string[] }>( - "voice/prepare", - { text, voiceId: opts.voiceId, botId: opts.botId }, - { requestContext }, - ); - if (!prepared.ready) return false; - speechGeneration += 1; - const mine = speechGeneration; - for (const utterance of prepared.utterances) { - if (speechGeneration !== mine) break; - await playMpeg(await renderUtterance(utterance, opts, requestContext)); - } - return true; -} - -let deviceSpeechSession = 0; - -function startDeviceSpeechSession(): number { - return ++deviceSpeechSession; -} - -function isCurrentDeviceSpeechSession(session: number): boolean { - return session === deviceSpeechSession; -} - -export async function speakWithDeviceVoice(text: string): Promise { - const utterances = toUtterances(text); - if (utterances.length === 0) return false; - // Claim the session before importing so a newer call cannot start during - // that await and then overlap this call's remaining chunks. - const session = startDeviceSpeechSession(); - const Speech = await loadExpoSpeech(); - if (!isCurrentDeviceSpeechSession(session)) return true; - await Speech.stop(); - if (!isCurrentDeviceSpeechSession(session)) return true; - for (const utterance of utterances) { - if (!isCurrentDeviceSpeechSession(session)) return true; - await speakOneUtterance(Speech, utterance); - } - return true; -} - -async function loadExpoSpeech(): Promise { - let Speech: Partial; - try { - Speech = await import("expo-speech"); - } catch (error) { - throw error instanceof Error ? error : new Error(t("Could not play that clip.")); - } - if (typeof Speech.speak !== "function" || typeof Speech.stop !== "function") { - throw new Error(t("Could not play that clip.")); - } - return Speech as typeof ExpoSpeech; -} - -function speakOneUtterance(Speech: typeof ExpoSpeech, text: string): Promise { - return new Promise((resolve, reject) => { - Speech.speak(text, { - onDone: () => resolve(), - // Speech.stop() reports onStopped, not onDone. - onStopped: () => resolve(), - onError: (error) => reject(error instanceof Error ? error : new Error(String(error))), - }); - }); -} - -export async function speakUtterance( - text: string, - opts: SpeechOptions & { requestContext?: ApiRequestContext } = {}, -): Promise { - const requestContext = opts.requestContext ?? (await captureApiRequestContext()); - await ensureAiDataConsent({ - uses: ["voice"], - status: () => rpc("aiConsent/status", { uses: ["voice"] }, { requestContext }), - prompt: promptAiConsent, - allow: (input) => rpc("aiConsent/allow", input, { requestContext }), - coalesceKey: aiConsentCoalesceKey(requestContext), - }); - return renderUtterance(text, opts, requestContext); -} - -async function renderUtterance( - text: string, - opts: SpeechOptions, - requestContext: ApiRequestContext, -): Promise { - const deadline = requestDeadline(VOICE_RESPONSE_TIMEOUT_MS); - try { - const res = await withAbort( - fetch(`${requestContext.apiBase}/api/voice/speak`, { - method: "POST", - headers: { - "content-type": "application/json", - origin: "rakazo://", - ...requestContext.headers, - }, - body: JSON.stringify({ text, voiceId: opts.voiceId, botId: opts.botId }), - signal: deadline.signal, - }), - deadline.signal, - ); - if (!res.ok) { - const body = await readVoiceError(res, deadline.signal); - throw new Error(body.error ?? `Voice failed (${res.status})`); - } - return await readResponseBytes(res, MAX_VOICE_AUDIO_BYTES, deadline.signal); - } finally { - deadline.dispose(); - } -} - -export async function playMpeg(bytes: Uint8Array): Promise { - const AudioCtor = (globalThis as { Audio?: typeof Audio }).Audio; - if (typeof AudioCtor === "function") { - await playWithHtmlAudio(AudioCtor, bytes); - return; - } - await playWithNativeAudio(bytes); -} - -async function playWithHtmlAudio(AudioCtor: typeof Audio, bytes: Uint8Array): Promise { - const blob = new Blob([new Uint8Array(bytes)], { type: "audio/mpeg" }); - const url = URL.createObjectURL(blob); - try { - const audio = new AudioCtor(url); - await new Promise((resolve, reject) => { - let settled = false; - const finish = (error?: Error) => { - if (settled) return; - settled = true; - audio.onended = null; - audio.onerror = null; - if (error) reject(error); - else resolve(); - }; - audio.onended = () => finish(); - audio.onerror = () => finish(new Error(t("Could not play that clip."))); - stopPlayback = () => { - audio.pause(); - finish(); - }; - try { - void audio - .play() - .catch((error: unknown) => - finish(error instanceof Error ? error : new Error(t("Could not play that clip."))), - ); - } catch (error) { - finish(error instanceof Error ? error : new Error(t("Could not play that clip."))); - } - }); - } finally { - stopPlayback = null; - URL.revokeObjectURL(url); - } -} - -async function playWithNativeAudio(bytes: Uint8Array): Promise { - const { createAudioPlayer, setAudioModeAsync } = await import("expo-audio"); - await setAudioModeAsync({ - playsInSilentMode: true, - interruptionMode: "mixWithOthers", - shouldPlayInBackground: false, - }); - const file = new File(Paths.cache, `rakazo-voice-${Date.now()}.mp3`); - file.create({ overwrite: true }); - file.write(bytesToBase64(bytes), { encoding: "base64" }); - const player = createAudioPlayer({ uri: file.uri }); - try { - await new Promise((resolve, reject) => { - let settled = false; - let timer = setTimeout(() => finish(new Error(t("Could not play that clip."))), 15_000); - const finish = (error?: Error) => { - if (settled) return; - settled = true; - clearTimeout(timer); - stopPlayback = null; - sub.remove(); - if (error) reject(error); - else resolve(); - }; - const sub = player.addListener("playbackStatusUpdate", (status) => { - if (status.error) { - finish(new Error(status.error)); - return; - } - if (status.playbackState === "failed") { - finish(new Error(t("Could not play that clip."))); - return; - } - if (status.didJustFinish) { - finish(); - return; - } - if (status.playing && status.duration > 0) { - clearTimeout(timer); - timer = setTimeout( - () => finish(new Error(t("Could not play that clip."))), - Math.min(120_000, Math.ceil(status.duration * 1000) + 8_000), - ); - } - }); - stopPlayback = () => { - try { - player.pause(); - } catch { - // already stopped - } - finish(); - }; - try { - player.play(); - } catch (error) { - finish(error instanceof Error ? error : new Error(t("Could not play that clip."))); - } - }); - } finally { - stopPlayback = null; - player.release(); - try { - file.delete(); - } catch { - // already gone - } - } -} - -function bytesToBase64(bytes: Uint8Array): string { - if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64"); - let binary = ""; - const chunk = 0x8000; - for (let i = 0; i < bytes.length; i += chunk) { - binary += String.fromCharCode(...bytes.subarray(i, i + chunk)); - } - return btoa(binary); -} - -function requestDeadline(timeoutMs: number) { - const controller = new AbortController(); - const timer = setTimeout( - () => controller.abort(new Error("Voice request timed out.")), - timeoutMs, - ); - return { - signal: controller.signal, - dispose() { - clearTimeout(timer); - }, - }; -} - -async function readVoiceError( - response: Response, - signal: AbortSignal, -): Promise<{ error?: string }> { - const bytes = await readResponseBytes(response, MAX_VOICE_ERROR_BYTES, signal); - try { - const parsed = JSON.parse(new TextDecoder().decode(bytes)) as unknown; - return parsed && typeof parsed === "object" ? (parsed as { error?: string }) : {}; - } catch { - return {}; - } -} - -async function readResponseBytes( - response: Response, - maxBytes: number, - signal: AbortSignal, -): Promise { - const declared = Number(response.headers.get("content-length") ?? 0); - if (Number.isFinite(declared) && declared > maxBytes) { - cancelResponse(response); - throw new Error("Voice response is too large."); - } - return readBoundedResponseBytes(response, { - maxBytes, - tooLargeMessage: "Voice response is too large.", - read: (operation) => withAbort(operation(), signal), - }); -} - -function withAbort(promise: Promise, signal: AbortSignal): Promise { - if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Voice request aborted.")); - return new Promise((resolve, reject) => { - const onAbort = () => reject(signal.reason ?? new Error("Voice request aborted.")); - signal.addEventListener("abort", onAbort, { once: true }); - promise.then( - (value) => { - signal.removeEventListener("abort", onAbort); - resolve(value); - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - reject(error); - }, - ); - }); -} - -function cancelResponse(response: Response): void { - try { - void Promise.resolve(response.body?.cancel()).catch(() => undefined); - } catch { - // Response cleanup is best-effort. - } -} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index fdc3a747..83578482 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -26,7 +26,6 @@ "@react-native-vector-icons/material-design-icons": "13.1.4", "expo": "57.0.30", "expo-application": "57.0.3", - "expo-audio": "57.0.5", "expo-clipboard": "57.0.2", "expo-constants": "57.0.22", "expo-document-picker": "57.0.3", @@ -41,8 +40,6 @@ "expo-screen-orientation": "57.0.3", "expo-secure-store": "57.0.4", "expo-sharing": "57.0.23", - "expo-speech": "57.0.3", - "expo-speech-recognition": "57.1.0", "expo-splash-screen": "57.0.10", "expo-status-bar": "57.0.1", "expo-symbols": "57.0.3", diff --git a/apps/web/e2e/bot-organization.spec.ts b/apps/web/e2e/bot-organization.spec.ts index 8310ecd5..6e8417a4 100644 --- a/apps/web/e2e/bot-organization.spec.ts +++ b/apps/web/e2e/bot-organization.spec.ts @@ -183,7 +183,7 @@ test("chat composer puts the message above one row of controls", async ({ page } const boxes = await page.getByTestId("composer-bar").evaluate((composer) => Object.fromEntries( - ["Attach file", "Message Chief", "Voice", "Send"].map((label) => { + ["Attach file", "Message Chief", "Send"].map((label) => { const element = composer.querySelector(`[aria-label="${label}"]`); if (!element) throw new Error(`Missing composer control: ${label}`); const box = element.getBoundingClientRect(); @@ -192,7 +192,7 @@ test("chat composer puts the message above one row of controls", async ({ page } ), ); - const controls = ["Attach file", "Voice", "Send"].map((label) => boxes[label]!.center); + const controls = ["Attach file", "Send"].map((label) => boxes[label]!.center); expect(Math.max(...controls) - Math.min(...controls)).toBeLessThanOrEqual(1); expect(boxes["Message Chief"]!.bottom).toBeLessThanOrEqual(boxes["Attach file"]!.top); }); diff --git a/apps/web/e2e/golden.spec.ts b/apps/web/e2e/golden.spec.ts index 052d2cbc..0b58e071 100644 --- a/apps/web/e2e/golden.spec.ts +++ b/apps/web/e2e/golden.spec.ts @@ -210,12 +210,7 @@ test("sign-in, spawn, and stop work in the shell", async ({ page }, testInfo) => await expect(page.getByText(/^Steer /)).toHaveCount(0); await expect(composer).toHaveAttribute("placeholder", "Message Chief"); await expect(page.getByRole("button", { name: "Send", exact: true })).toBeVisible(); - const voiceButton = page - .getByTestId("composer-bar") - .getByRole("button", { name: "Voice", exact: true }); - await expect(voiceButton).toBeVisible(); await composer.fill("Use the newer report and keep the answer short."); - await expect(voiceButton).toHaveCount(0); // Tab order follows the layout: message, then the control row (attach, then send). await composer.press("Tab"); await expect(page.getByRole("button", { name: "Attach file", exact: true })).toBeFocused(); diff --git a/apps/web/e2e/group-chats.spec.ts b/apps/web/e2e/group-chats.spec.ts index ca0f2cf6..255a1139 100644 --- a/apps/web/e2e/group-chats.spec.ts +++ b/apps/web/e2e/group-chats.spec.ts @@ -26,10 +26,6 @@ test("a group shows two bots in one transcript", async ({ page }, testInfo) => { name: "Review team", botIds: [researcherId, writerId], }); - await rpc(page, "voice/connect", { - provider: "scripted", - apiKey: "fake-group-voice-key", - }); await page.reload(); await expect(page).toHaveURL(groupUrl); await expect(page.getByRole("combobox", { name: "Message Draft team" })).toBeVisible(); @@ -138,19 +134,6 @@ test("a group shows two bots in one transcript", async ({ page }, testInfo) => { const transcript = page.getByTestId("transcript"); await expect(transcript.getByText("Researcher", { exact: true }).first()).toBeVisible(); await expect(transcript.getByText("Research Writer", { exact: true }).first()).toBeVisible(); - const researcherSpeak = transcript - .locator("div") - .filter({ has: page.getByText("Researcher", { exact: true }) }) - .filter({ has: page.getByRole("button", { name: "Speak this reply" }) }) - .first() - .getByRole("button", { name: "Speak this reply" }); - const [speechRequest] = await Promise.all([ - page.waitForRequest( - (request) => request.url().includes("/api/voice/speak") && request.method() === "POST", - ), - researcherSpeak.click(), - ]); - expect(speechRequest.postDataJSON()).toMatchObject({ botId: researcherId }); await captureScreenshot(page, testInfo, "group-transcript"); await composer.fill("@Res"); diff --git a/apps/web/e2e/helpers.ts b/apps/web/e2e/helpers.ts index 1dd8201c..cdad64a6 100644 --- a/apps/web/e2e/helpers.ts +++ b/apps/web/e2e/helpers.ts @@ -151,15 +151,7 @@ export async function createBotFromPicker( /** Open the user Settings overlay, optionally switching to a sidebar section. */ export async function openUserSettings( page: Page, - section?: - | "general" - | "usage" - | "approvals" - | "notifications" - | "memory" - | "voice" - | "computer" - | "updates", + section?: "general" | "usage" | "approvals" | "notifications" | "memory" | "computer" | "updates", ) { await page.getByTestId("sidebar-settings").click(); const settings = page.getByTestId("user-settings"); diff --git a/apps/web/e2e/settings-shell.spec.ts b/apps/web/e2e/settings-shell.spec.ts index 9ccdd465..2ef57116 100644 --- a/apps/web/e2e/settings-shell.spec.ts +++ b/apps/web/e2e/settings-shell.spec.ts @@ -48,14 +48,9 @@ test("settings shell is Usage, General and Allow list in a browser", async ({ pa await expect(settings.getByRole("heading", { name: "Allow list", exact: true })).toBeVisible(); await expect(settings.getByTestId("action-confirmation-settings")).toBeVisible(); await captureScreenshot(page, testInfo, "settings-shell-allow-list"); + await expect(settings.getByTestId("settings-nav-voice")).toHaveCount(0); - await settings.getByTestId("settings-nav-voice").click(); - await expect(settings).toHaveAttribute("data-settings-section", "voice"); - await expect(settings.getByRole("heading", { name: "Voice", exact: true })).toBeVisible(); - await expect(settings.getByTestId("voice-settings")).toBeVisible(); - await captureScreenshot(page, testInfo, "settings-shell-voice"); - - await page.getByRole("button", { name: "Close voice settings" }).click(); + await page.getByRole("button", { name: "Close user settings" }).click(); await expect(page.getByTestId("user-settings")).toHaveCount(0); await openUserSettings(page, "usage"); diff --git a/apps/web/e2e/voice.spec.ts b/apps/web/e2e/voice.spec.ts deleted file mode 100644 index 8af3f100..00000000 --- a/apps/web/e2e/voice.spec.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { captureScreenshot, completeOnboarding, openUserSettings, rpc, signup } from "./helpers"; - -test("voice settings connect a key, speak a reply, and open a call", async ({ page }, testInfo) => { - const stamp = Date.now(); - const userName = `Voice ${stamp}`; - await signup(page, `voice-${stamp}@rakazo.test`, "password12", userName); - await completeOnboarding(page); - - await expect(page.getByRole("button", { name: "Call", exact: true })).toHaveCount(0); - await expect( - page.getByTestId("composer-bar").getByRole("button", { name: "Voice", exact: true }), - ).toHaveCount(1); - await captureScreenshot(page, testInfo, "voice-composer"); - await page - .getByTestId("composer-bar") - .getByRole("button", { name: "Voice", exact: true }) - .click(); - await expect(page.getByTestId("voice-settings")).toBeVisible(); - await expect(page.getByLabel("API key", { exact: true })).toBeVisible(); - await expect(page.getByRole("button", { name: "Dictate", exact: true })).toHaveCount(0); - await captureScreenshot(page, testInfo, "voice-settings"); - await page.getByRole("button", { name: "Close voice settings" }).click(); - await expect(page.getByTestId("voice-settings")).toHaveCount(0); - - const preparedOff = await rpc<{ ready: boolean }>(page, "voice/prepare", { - text: "Hello there.", - }); - expect(preparedOff.ready).toBe(false); - - await openUserSettings(page, "voice"); - await expect(page.getByTestId("voice-settings")).toBeVisible(); - await page.getByRole("button", { name: /Scripted/ }).click(); - const apiKeyInput = page.getByPlaceholder(/Paste your API key/); - await expect(apiKeyInput).toHaveAttribute("autocomplete", "new-password"); - await apiKeyInput.fill("fake-scripted-voice-key"); - await page.getByRole("button", { name: "Connect", exact: true }).click(); - await expect(page.getByText("Connected", { exact: true }).first()).toBeVisible(); - await expect(page.getByRole("button", { name: "Replace key" })).toBeVisible(); - await expect(page.getByRole("button", { name: "Disconnect", exact: true })).toBeVisible(); - await captureScreenshot(page, testInfo, "voice-settings-connected"); - - const spoken = page.waitForResponse( - (response) => response.url().includes("/api/voice/speak") && response.ok(), - ); - await page.getByRole("button", { name: "Hear a sample" }).click(); - const clip = await spoken; - expect(clip.headers()["content-type"]).toContain("audio/mpeg"); - - const credentials = await rpc>( - page, - "voice/credentials", - {}, - ); - expect(credentials).toEqual([expect.objectContaining({ hasKey: true, provider: "scripted" })]); - expect(JSON.stringify(credentials)).not.toContain("fake-scripted-voice-key"); - - await page.getByRole("button", { name: "Close voice settings" }).click(); - - const composer = page.getByPlaceholder(/Message/); - await composer.fill("say hello"); - await page.keyboard.press("Enter"); - // A reply can render more than one text bubble; speak the latest one. - const speakReply = page.getByRole("button", { name: "Speak this reply" }).last(); - await expect(speakReply).toBeVisible({ - timeout: 30_000, - }); - - const replySpoken = page.waitForResponse( - (response) => response.url().includes("/api/voice/speak") && response.ok(), - ); - await speakReply.click(); - await replySpoken; - - await openUserSettings(page, "voice"); - await expect(page.getByRole("button", { name: "Replace key" })).toBeVisible(); - await expect(page.getByRole("button", { name: "Disconnect", exact: true })).toBeVisible(); - await page.getByRole("button", { name: "Close voice settings" }).click(); - - await page - .getByTestId("composer-bar") - .getByRole("button", { name: "Voice", exact: true }) - .click(); - await expect(page.getByTestId("call-view")).toBeVisible(); - await expect(page.getByRole("button", { name: "Hang up" })).toBeVisible(); - await captureScreenshot(page, testInfo, "voice-call"); - await page.getByRole("button", { name: "Hang up" }).click(); - await expect(page.getByTestId("call-view")).toHaveCount(0); - - await openUserSettings(page, "voice"); - const settings = page.getByTestId("voice-settings"); - await settings.getByPlaceholder(/Paste a replacement key/).fill("leftover-voice-key"); - await settings.getByRole("button", { name: "Disconnect", exact: true }).click(); - await expect(settings.getByRole("button", { name: "Disconnect", exact: true })).toHaveCount(0); - await expect(settings.getByRole("button", { name: "Connect", exact: true })).toBeVisible(); - await expect(settings.getByLabel("API key", { exact: true })).toHaveValue(""); - await expect(rpc>(page, "voice/credentials", {})).resolves.toEqual( - [], - ); -}); diff --git a/apps/web/scripts/translations-de.json b/apps/web/scripts/translations-de.json index b54bfc8c..f9437d84 100644 --- a/apps/web/scripts/translations-de.json +++ b/apps/web/scripts/translations-de.json @@ -36,7 +36,6 @@ "Action confirmations": "Aktionsbestätigungen", "Actions for {0}": "Aktionen für {0}", "Active model": "Aktives Modell", - "Active voice": "Aktive Stimme", "Activity": "Aktivität", "Add": "Hinzufügen", "Add a server": "Server hinzufügen", @@ -102,8 +101,6 @@ "Bot screen": "Bot-Bildschirm", "Bot screen preview": "Bot-Bildschirmvorschau", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "Bots handeln standardmäßig ohne Nachfrage. Füge nur dann eine Ausnahme hinzu, wenn du eine Aktionsart zuerst prüfen möchtest.", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "Verwende deinen eigenen Schlüssel. Der Anbieter ist austauschbar; die Schaltflächen zum Sprechen und Anrufen deiner Bots bleiben gleich.", - "Call": "Anrufen", "Can't reach the server.": "Server nicht erreichbar.", "Cancel": "Abbrechen", "Cancel new bot": "Neuen Bot abbrechen", @@ -132,7 +129,6 @@ "Close panel": "Panel schließen", "Close preview": "Vorschau schließen", "Close user settings": "Benutzereinstellungen schließen", - "Close voice settings": "Stimmeinstellungen schließen", "Command": "Befehl", "Complete": "Abschließen", "Computer": "Computer", @@ -146,7 +142,6 @@ "Connect": "Verbinden", "Connect a model": "Modell verbinden", "Connect API key": "API-Schlüssel verbinden", - "Connect ElevenLabs, OpenAI, or Cartesia": "ElevenLabs, OpenAI oder Cartesia verbinden", "Connect MCP server “{name}”": "MCP-Server „{name}“ verbinden", "Connect OAuth": "OAuth verbinden", "Connect remote or local tool servers and choose which agents can use them.": "Verbinde Remote- oder lokale Toolserver und wähle aus, welche Agents sie verwenden dürfen.", @@ -170,7 +165,6 @@ "Could not complete OAuth": "OAuth konnte nicht abgeschlossen werden", "Could not connect": "Verbindung fehlgeschlagen", "Could not connect this provider": "Anbieter konnte nicht verbunden werden", - "Could not connect this voice provider": "Stimmanbieter konnte nicht verbunden werden", "Could not continue": "Fortfahren fehlgeschlagen", "Could not create bot": "Bot konnte nicht erstellt werden", "Could not create group": "Gruppe konnte nicht erstellt werden", @@ -188,7 +182,6 @@ "Could not load MCP servers": "MCP-Server konnten nicht geladen werden", "Could not load model settings": "Modelleinstellungen konnten nicht geladen werden", "Could not load this file.": "Datei konnte nicht geladen werden.", - "Could not load voice settings": "Stimmeinstellungen konnten nicht geladen werden", "Could not play a test clip": "Testclip konnte nicht abgespielt werden", "Could not reach this model server": "Modellserver konnte nicht erreicht werden", "Could not remove": "Entfernen fehlgeschlagen", @@ -203,7 +196,6 @@ "Could not save routine": "Routine konnte nicht gespeichert werden", "Could not save rule": "Regel konnte nicht gespeichert werden", "Could not save that choice": "Auswahl konnte nicht gespeichert werden", - "Could not save that voice": "Stimme konnte nicht gespeichert werden", "Could not save this choice": "Diese Auswahl konnte nicht gespeichert werden", "Could not send that": "Senden fehlgeschlagen", "Could not start OAuth": "OAuth konnte nicht gestartet werden", @@ -286,14 +278,11 @@ "Hear a sample": "Beispiel anhören", "Hi, this is how I'll sound when I read replies out loud.": "Hallo, so klinge ich, wenn ich Antworten vorlese.", "High": "Hoch", - "Hold to talk": "Zum Sprechen gedrückt halten", - "Hold to talk (on-device dictation)": "Zum Sprechen gedrückt halten (Diktat auf dem Gerät)", "hour": "Stunde", "hours": "Stunden", "How often": "Wie oft", "How to check": "So wird geprüft", "I’m done": "Ich bin fertig", - "If you heard that, voice is ready.": "Wenn du das gehört hast, ist die Stimme einsatzbereit.", "Import OpenAPI JSON": "OpenAPI-JSON importieren", "Inputs": "Eingaben", "Instruction": "Anweisung", @@ -315,7 +304,6 @@ "Loading peer messages…": "Bot-Nachrichten werden geladen…", "Loading preview…": "Vorschau wird geladen…", "Loading rules…": "Regeln werden geladen…", - "Loading voice providers…": "Stimmanbieter werden geladen…", "Loading…": "Wird geladen…", "Log out": "Abmelden", "Low": "Niedrig", @@ -403,7 +391,6 @@ "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed.": "Füge die OpenAI-kompatible Adresse deines Servers ein. Milo ergänzt /v1 bei Bedarf.", "Paste your API key": "Füge deinen API-Schlüssel ein", "Personal credential": "Persönliche Zugangsdaten", - "Pick a voice": "Stimme auswählen", "Pin": "Anheften", "Playing…": "Wiedergabe…", "Preview {0}": "Vorschau von {0}", @@ -459,7 +446,6 @@ "Sending…": "Wird gesendet…", "Server name": "Servername", "Server URL": "Server-URL", - "Set up voice to call": "Stimme für Anrufe einrichten", "Settings": "Einstellungen", "Settings: General": "Einstellungen: Allgemein", "Settings: Usage": "Einstellungen: Nutzung", @@ -476,18 +462,11 @@ "Skip or deploy key": "Überspringen oder Deploy-Key", "Skipped {0}": "{0} übersprungen", "Space interrupts · Esc hangs up": "Leertaste unterbricht · Esc legt auf", - "Speak": "Vorlesen", - "Speak + transcribe": "Sprechen + transkribieren", - "Speak only": "Nur sprechen", - "Speak this reply": "Diese Antwort vorlesen", - "Speaking…": "Spricht…", "Start recording": "Aufnahme starten", "Starting": "Startet", "Starting…": "Wird gestartet…", "Steps": "Schritte", "Stop": "Stoppen", - "Stop dictation": "Diktat stoppen", - "Stop speaking": "Vorlesen stoppen", "Stop teaching": "Anlernen beenden", "Stop the bot first": "Zuerst den Bot stoppen", "Stored encrypted": "Verschlüsselt gespeichert", @@ -529,7 +508,6 @@ "Use this model": "Dieses Modell verwenden", "Verify and add": "Prüfen und hinzufügen", "Verifying…": "Wird geprüft…", - "Voice": "Stimme", "Waiting for sign-in…": "Warten auf Anmeldung…", "Waiting…": "Warten…", "Weekdays": "Wochentage", diff --git a/apps/web/scripts/translations-es.json b/apps/web/scripts/translations-es.json index 9492fe2e..9f7befdb 100644 --- a/apps/web/scripts/translations-es.json +++ b/apps/web/scripts/translations-es.json @@ -30,7 +30,6 @@ "Actions for {0}": "Acciones para {0}", "Active": "Activo", "Active model": "Modelo activo", - "Active voice": "Voz activa", "Activity": "Actividad", "Add": "Agregar", "Add a model in Settings to use this.": "Agrega un modelo en Configuración para usarlo.", @@ -107,8 +106,6 @@ "Bot screen preview": "Vista previa de la pantalla del bot", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "Los bots actúan sin preguntar de forma predeterminada. Agrega una excepción solo cuando quieras revisar primero un tipo de acción.", "Bots are working": "Los bots están trabajando", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "Usa tu propia clave. El proveedor se puede cambiar; tus bots conservan los mismos botones de hablar y llamar.", - "Call": "Llamar", "Can't reach the server.": "No se puede alcanzar el servidor.", "Cancel": "Cancelar", "Cancel new bot": "Cancelar nuevo bot", @@ -143,7 +140,6 @@ "Close panel": "Cerrar panel", "Close preview": "Cerrar vista previa", "Close user settings": "Cerrar configuración de usuario", - "Close voice settings": "Cerrar configuración de voz", "Code": "Código", "Collapse {0}": "Contraer {0}", "Coming soon": "Próximamente", @@ -163,7 +159,6 @@ "Connect": "Conectar", "Connect a model": "Conectar un modelo", "Connect API key": "Conectar clave de API", - "Connect ElevenLabs, OpenAI, or Cartesia": "Conecta ElevenLabs, OpenAI o Cartesia", "Connect MCP server “{name}”": "Conectar servidor MCP “{name}”", "Connect OAuth": "Conectar OAuth", "Connect this provider to use it as your personal model.": "Conecta este proveedor para usarlo como tu modelo personal.", @@ -189,7 +184,6 @@ "Could not complete OAuth": "No se pudo completar OAuth", "Could not connect": "No se pudo conectar", "Could not connect this provider": "No se pudo conectar este proveedor", - "Could not connect this voice provider": "No se pudo conectar este proveedor de voz", "Could not connect to the computer screen": "No se pudo conectar a la pantalla de la computadora", "Could not continue": "No se pudo continuar", "Could not create bot": "No se pudo crear el bot", @@ -212,7 +206,6 @@ "Could not load this chat.": "No se pudo cargar este chat.", "Could not load this file.": "No se pudo cargar este archivo.", "Could not load update status": "No se pudo cargar el estado de actualización", - "Could not load voice settings": "No se pudo cargar la configuración de voz", "Could not play a test clip": "No se pudo reproducir un clip de prueba", "Could not reach the server": "No se pudo alcanzar el servidor", "Could not reach this model server": "No se pudo alcanzar este servidor de modelos", @@ -231,7 +224,6 @@ "Could not save routine": "No se pudo guardar la rutina", "Could not save rule": "No se pudo guardar la regla", "Could not save that choice": "No se pudo guardar esa opción", - "Could not save that voice": "No se pudo guardar esa voz", "Could not save this choice": "No se pudo guardar esta opción", "Could not send reset email": "No se pudo enviar el correo de restablecimiento", "Could not send that": "No se pudo enviar eso", @@ -335,14 +327,11 @@ "Hi, this is how I'll sound when I read replies out loud.": "Hola, así sonaré cuando lea las respuestas en voz alta.", "Hide password": "Ocultar contraseña", "High": "Alto", - "Hold to talk": "Mantén pulsado para hablar", - "Hold to talk (on-device dictation)": "Mantén pulsado para hablar (dictado en el dispositivo)", "hour": "hora", "hours": "horas", "How often": "Con qué frecuencia", "How to check": "Cómo comprobar", "I’m done": "Listo", - "If you heard that, voice is ready.": "Si escuchaste eso, la voz está lista.", "Import OpenAPI JSON": "Importar JSON de OpenAPI", "Inputs": "Entradas", "Instruction": "Instrucción", @@ -368,7 +357,6 @@ "Loading model catalog…": "Cargando catálogo de modelos…", "Loading preview…": "Cargando vista previa…", "Loading rules…": "Cargando reglas…", - "Loading voice providers…": "Cargando proveedores de voz…", "Loading…": "Cargando…", "Log out": "Cerrar sesión", "Low": "Bajo", @@ -474,7 +462,6 @@ "Paste your API key": "Pega tu clave de API", "Paused": "En pausa", "Personal credential": "Credencial personal", - "Pick a voice": "Elige una voz", "Pin": "Fijar", "Playing…": "Reproduciendo…", "POST to": "POST a", @@ -554,7 +541,6 @@ "Sentry alert": "Alerta de Sentry", "Server name": "Nombre del servidor", "Server URL": "URL del servidor", - "Set up voice to call": "Configura la voz para llamar", "Settings": "Configuración", "Settings: General": "Configuración: General", "Settings: Usage": "Configuración: Uso", @@ -576,18 +562,11 @@ "Software update": "Actualización de software", "Space default": "Predeterminado del Space", "Space interrupts · Esc hangs up": "Space interrumpe · Esc cuelga", - "Speak": "Hablar", - "Speak + transcribe": "Hablar + transcribir", - "Speak only": "Solo hablar", - "Speak this reply": "Leer esta respuesta", - "Speaking…": "Hablando…", "Start recording": "Iniciar grabación", "Starting": "Iniciando", "Starting…": "Iniciando…", "Steps": "Pasos", "Stop": "Detener", - "Stop dictation": "Detener dictado", - "Stop speaking": "Dejar de hablar", "Stop teaching": "Detener enseñanza", "Stopped.": "Detenido.", "Stored encrypted": "Almacenado cifrado", @@ -641,7 +620,6 @@ "Use this model": "Usar este modelo", "Verify and add": "Verificar y agregar", "Verifying…": "Verificando…", - "Voice": "Voz", "Waiting for sign-in…": "Esperando el inicio de sesión…", "Waiting for the API to come back…": "Esperando a que vuelva la API…", "Waiting…": "Esperando…", diff --git a/apps/web/scripts/translations-hi.json b/apps/web/scripts/translations-hi.json index a35ad223..f626fbd1 100644 --- a/apps/web/scripts/translations-hi.json +++ b/apps/web/scripts/translations-hi.json @@ -30,7 +30,6 @@ "Action confirmations": "कार्रवाई की पुष्टि", "Actions for {0}": "{0} के लिए कार्रवाइयां", "Active model": "सक्रिय मॉडल", - "Active voice": "सक्रिय आवाज़", "Activity": "गतिविधि", "Add": "जोड़ें", "Add a server": "एक सर्वर जोड़ें", @@ -95,8 +94,6 @@ "Bot screen": "बॉट स्क्रीन", "Bot screen preview": "बॉट स्क्रीन प्रीव्यू", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "बॉट डिफ़ॉल्ट रूप से बिना पूछे कार्रवाई करते हैं। अपवाद तभी जोड़ें जब आप किसी प्रकार की कार्रवाई की पहले समीक्षा करना चाहते हों।", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "अपनी कुंजी स्वयं लाएं। प्रोवाइडर बदला जा सकता है; आपके बॉट्स के बोलने और कॉल करने वाले बटन वही रहते हैं।", - "Call": "कॉल", "Can't reach the server.": "सर्वर तक नहीं पहुंचा जा सका।", "Cancel": "रद्द करें", "Cancel new bot": "नया बॉट रद्द करें", @@ -125,7 +122,6 @@ "Close panel": "पैनल बंद करें", "Close preview": "प्रीव्यू बंद करें", "Close user settings": "उपयोगकर्ता सेटिंग्स बंद करें", - "Close voice settings": "आवाज़ सेटिंग्स बंद करें", "Command": "कमांड", "Complete": "पूर्ण", "Computer": "कंप्यूटर", @@ -139,7 +135,6 @@ "Connect": "कनेक्ट करें", "Connect a model": "एक मॉडल कनेक्ट करें", "Connect API key": "API कुंजी कनेक्ट करें", - "Connect ElevenLabs, OpenAI, or Cartesia": "ElevenLabs, OpenAI या Cartesia कनेक्ट करें", "Connect MCP server “{name}”": "MCP सर्वर “{name}” कनेक्ट करें", "Connect OAuth": "OAuth कनेक्ट करें", "Connect remote or local tool servers and choose which agents can use them.": "रिमोट या लोकल टूल सर्वर कनेक्ट करें और चुनें कि कौन से एजेंट उनका उपयोग कर सकते हैं।", @@ -164,7 +159,6 @@ "Could not complete OAuth": "OAuth पूरा नहीं हो सका", "Could not connect": "कनेक्ट नहीं हो सका", "Could not connect this provider": "यह प्रोवाइडर कनेक्ट नहीं हो सका", - "Could not connect this voice provider": "यह आवाज़ प्रोवाइडर कनेक्ट नहीं हो सका", "Could not continue": "जारी नहीं रखा जा सका", "Could not create bot": "बॉट नहीं बनाया जा सका", "Could not create group": "समूह नहीं बनाया जा सका", @@ -182,7 +176,6 @@ "Could not load MCP servers": "MCP सर्वर लोड नहीं हो सके", "Could not load model settings": "मॉडल सेटिंग्स लोड नहीं हो सकीं", "Could not load this file.": "यह फ़ाइल लोड नहीं हो सकी।", - "Could not load voice settings": "आवाज़ सेटिंग्स लोड नहीं हो सकीं", "Could not play a test clip": "टेस्ट क्लिप नहीं चलाई जा सकी", "Could not reach this model server": "इस मॉडल सर्वर तक नहीं पहुंचा जा सका", "Could not remove": "हटाया नहीं जा सका", @@ -197,7 +190,6 @@ "Could not save routine": "रूटीन सहेजा नहीं जा सका", "Could not save rule": "नियम सहेजा नहीं जा सका", "Could not save that choice": "वह विकल्प सहेजा नहीं जा सका", - "Could not save that voice": "वह आवाज़ सहेजी नहीं जा सकी", "Could not save this choice": "यह विकल्प सहेजा नहीं जा सका", "Could not send that": "वह भेजा नहीं जा सका", "Could not start OAuth": "OAuth शुरू नहीं हो सका", @@ -279,14 +271,11 @@ "Hear a sample": "एक नमूना सुनें", "Hi, this is how I'll sound when I read replies out loud.": "नमस्ते, उत्तर पढ़कर सुनाते समय मेरी आवाज़ ऐसी होगी।", "High": "उच्च", - "Hold to talk": "बोलने के लिए दबाए रखें", - "Hold to talk (on-device dictation)": "बोलने के लिए दबाए रखें (डिवाइस पर ही श्रुतलेखन)", "hour": "घंटा", "hours": "घंटे", "How often": "कितनी बार", "How to check": "जांच कैसे करें", "I’m done": "मेरा काम हो गया", - "If you heard that, voice is ready.": "अगर आपने वह सुना, तो आवाज़ तैयार है।", "Import OpenAPI JSON": "OpenAPI JSON इम्पोर्ट करें", "Inputs": "इनपुट", "Instruction": "निर्देश", @@ -309,7 +298,6 @@ "Loading peer messages…": "सहयोगी बॉट के संदेश लोड हो रहे हैं…", "Loading preview…": "प्रीव्यू लोड हो रहा है…", "Loading rules…": "नियम लोड हो रहे हैं…", - "Loading voice providers…": "आवाज़ प्रोवाइडर्स लोड हो रहे हैं…", "Loading…": "लोड हो रहा है…", "Log out": "लॉग आउट", "Low": "निम्न", @@ -398,7 +386,6 @@ "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed.": "अपने सर्वर से OpenAI-संगत पता पेस्ट करें। ज़रूरत होने पर Milo /v1 जोड़ देता है।", "Paste your API key": "अपनी API कुंजी पेस्ट करें", "Personal credential": "व्यक्तिगत क्रेडेंशियल", - "Pick a voice": "एक आवाज़ चुनें", "Pin": "पिन करें", "Playing…": "प्ले हो रहा है…", "Preview {0}": "{0} का प्रीव्यू", @@ -461,7 +448,6 @@ "Sending…": "भेजा जा रहा है…", "Server name": "सर्वर का नाम", "Server URL": "सर्वर URL", - "Set up voice to call": "कॉल के लिए आवाज़ सेट करें", "Settings": "सेटिंग्स", "Settings: General": "सेटिंग्स: सामान्य", "Settings: Usage": "सेटिंग्स: उपयोग", @@ -478,18 +464,11 @@ "Skip or deploy key": "छोड़ें या डिप्लॉय कुंजी दें", "Skipped {0}": "{0} को छोड़ा गया", "Space interrupts · Esc hangs up": "स्पेस से बीच में रोकें · Esc से कॉल समाप्त करें", - "Speak": "बोलें", - "Speak + transcribe": "बोलें + लिप्यंतरण करें", - "Speak only": "केवल बोलें", - "Speak this reply": "यह उत्तर बोलकर सुनाएं", - "Speaking…": "बोल रहा है…", "Start recording": "रिकॉर्डिंग शुरू करें", "Starting": "शुरू हो रहा है", "Starting…": "शुरू हो रहा है…", "Steps": "चरण", "Stop": "रोकें", - "Stop dictation": "श्रुतलेखन रोकें", - "Stop speaking": "बोलना रोकें", "Stop teaching": "सिखाना रोकें", "Stop the bot first": "पहले बॉट रोकें", "Stored encrypted": "एन्क्रिप्टेड रूप में संग्रहीत", @@ -533,7 +512,6 @@ "Use this model": "यह मॉडल उपयोग करें", "Verify and add": "पुष्टि करके जोड़ें", "Verifying…": "पुष्टि की जा रही है…", - "Voice": "आवाज़", "Waiting for sign-in…": "साइन-इन की प्रतीक्षा…", "Waiting…": "प्रतीक्षा…", "Weekdays": "कार्यदिवस", diff --git a/apps/web/scripts/translations-ko.json b/apps/web/scripts/translations-ko.json index 89fd664a..4a44d374 100644 --- a/apps/web/scripts/translations-ko.json +++ b/apps/web/scripts/translations-ko.json @@ -36,7 +36,6 @@ "Action confirmations": "작업 실행 전 확인", "Actions for {0}": "{0} 작업 메뉴", "Active model": "현재 모델", - "Active voice": "현재 목소리", "Activity": "활동", "Add": "추가", "Add a server": "서버 추가", @@ -102,8 +101,6 @@ "Bot screen": "Bot 화면", "Bot screen preview": "Bot 화면 미리보기", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "Bot은 기본적으로 묻지 않고 작업합니다. 먼저 확인하고 싶은 작업만 예외로 추가하세요.", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "사용 중인 서비스의 API 키를 연결하세요. 서비스를 바꿔도 Bot의 읽기·통화 기능은 그대로 유지됩니다.", - "Call": "통화", "Can't reach the server.": "서버에 연결할 수 없습니다.", "Cancel": "취소", "Cancel new bot": "새 Bot 만들기 취소", @@ -132,7 +129,6 @@ "Close panel": "패널 닫기", "Close preview": "미리보기 닫기", "Close user settings": "계정 설정 닫기", - "Close voice settings": "음성 설정 닫기", "Command": "실행 명령", "Complete": "완료", "Computer": "컴퓨터", @@ -146,7 +142,6 @@ "Connect": "연결", "Connect a model": "AI 모델 연결", "Connect API key": "API 키 연결", - "Connect ElevenLabs, OpenAI, or Cartesia": "ElevenLabs, OpenAI 또는 Cartesia 연결", "Connect MCP server “{name}”": "MCP 서버 ‘{name}’ 연결", "Connect OAuth": "OAuth 연결", "Connect remote or local tool servers and choose which agents can use them.": "원격 또는 로컬 도구 서버를 연결하고 사용할 Bot을 선택하세요.", @@ -170,7 +165,6 @@ "Could not complete OAuth": "OAuth 인증을 완료하지 못했습니다.", "Could not connect": "연결하지 못했습니다.", "Could not connect this provider": "AI 서비스에 연결하지 못했습니다.", - "Could not connect this voice provider": "음성 서비스에 연결하지 못했습니다.", "Could not continue": "계속 진행하지 못했습니다.", "Could not create bot": "Bot을 만들지 못했습니다.", "Could not create group": "그룹을 만들지 못했습니다.", @@ -188,7 +182,6 @@ "Could not load MCP servers": "MCP 서버 목록을 불러오지 못했습니다.", "Could not load model settings": "AI 모델 설정을 불러오지 못했습니다.", "Could not load this file.": "파일을 불러오지 못했습니다.", - "Could not load voice settings": "음성 설정을 불러오지 못했습니다.", "Could not play a test clip": "샘플 음성을 재생하지 못했습니다.", "Could not reach this model server": "모델 서버에 연결하지 못했습니다.", "Could not remove": "삭제하지 못했습니다.", @@ -203,7 +196,6 @@ "Could not save routine": "자동 실행을 저장하지 못했습니다.", "Could not save rule": "확인 규칙을 저장하지 못했습니다.", "Could not save that choice": "선택 내용을 저장하지 못했습니다.", - "Could not save that voice": "목소리를 저장하지 못했습니다.", "Could not save this choice": "선택 내용을 저장하지 못했습니다.", "Could not send that": "메시지를 보내지 못했습니다.", "Could not start OAuth": "OAuth 인증을 시작하지 못했습니다.", @@ -286,14 +278,11 @@ "Hear a sample": "샘플 듣기", "Hi, this is how I'll sound when I read replies out loud.": "안녕하세요. 답변을 소리 내어 읽을 때 이런 목소리로 들립니다.", "High": "높음", - "Hold to talk": "누르고 말하기", - "Hold to talk (on-device dictation)": "누르고 말하기(기기 내 음성 인식)", "hour": "시간", "hours": "시간", "How often": "실행 주기", "How to check": "완료 확인 방법", "I’m done": "조작 끝내기", - "If you heard that, voice is ready.": "샘플이 들렸다면 음성 설정이 완료되었습니다.", "Import OpenAPI JSON": "OpenAPI JSON 가져오기", "Inputs": "입력값", "Instruction": "실행할 내용", @@ -315,7 +304,6 @@ "Loading peer messages…": "Bot 메시지를 불러오는 중…", "Loading preview…": "미리보기를 불러오는 중…", "Loading rules…": "확인 규칙을 불러오는 중…", - "Loading voice providers…": "음성 서비스를 불러오는 중…", "Loading…": "불러오는 중…", "Log out": "로그아웃", "Low": "낮음", @@ -403,7 +391,6 @@ "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed.": "서버의 OpenAI 호환 주소를 붙여넣으세요. 필요하면 Milo가 /v1을 추가합니다.", "Paste your API key": "API 키를 붙여넣으세요", "Personal credential": "내 인증 정보", - "Pick a voice": "목소리 선택", "Pin": "고정", "Playing…": "재생 중…", "Preview {0}": "{0} 미리보기", @@ -459,7 +446,6 @@ "Sending…": "보내는 중…", "Server name": "서버 이름", "Server URL": "서버 URL", - "Set up voice to call": "통화하려면 음성을 먼저 설정하세요", "Settings": "설정", "Settings: General": "설정: 일반", "Settings: Usage": "설정: 사용량", @@ -476,18 +462,11 @@ "Skip or deploy key": "건너뛰거나 배포 키", "Skipped {0}": "{0} 건너뜀", "Space interrupts · Esc hangs up": "Space: 끼어들기 · Esc: 통화 종료", - "Speak": "읽기", - "Speak + transcribe": "음성 출력·받아쓰기", - "Speak only": "음성 출력만", - "Speak this reply": "이 답변 읽기", - "Speaking…": "말하는 중…", "Start recording": "작업 녹화 시작", "Starting": "시작 중", "Starting…": "시작하는 중…", "Steps": "실행 단계", "Stop": "중지", - "Stop dictation": "음성 입력 중지", - "Stop speaking": "읽기 중지", "Stop teaching": "가르치기 종료", "Stop the bot first": "먼저 Bot을 중지하세요", "Stored encrypted": "암호화해 저장", @@ -529,7 +508,6 @@ "Use this model": "이 모델 사용", "Verify and add": "확인 후 추가", "Verifying…": "확인 중…", - "Voice": "음성", "Waiting for sign-in…": "로그인 완료를 기다리는 중…", "Waiting…": "기다리는 중…", "Weekdays": "주중", diff --git a/apps/web/scripts/translations-pt-BR.json b/apps/web/scripts/translations-pt-BR.json index 6742770d..89480300 100644 --- a/apps/web/scripts/translations-pt-BR.json +++ b/apps/web/scripts/translations-pt-BR.json @@ -30,7 +30,6 @@ "Action confirmations": "Confirmações de ação", "Actions for {0}": "Ações para {0}", "Active model": "Modelo ativo", - "Active voice": "Voz ativa", "Activity": "Atividade", "Add": "Adicionar", "Add a server": "Adicionar um servidor", @@ -95,8 +94,6 @@ "Bot screen": "Tela do bot", "Bot screen preview": "Pré-visualização da tela", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "Os bots agem sem perguntar por padrão. Adicione uma exceção apenas quando quiser analisar um tipo de ação primeiro.", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "Traga sua própria chave. O provedor pode ser trocado; seus bots mantêm os mesmos botões de fala e chamada.", - "Call": "Ligar", "Can't reach the server.": "Não é possível acessar o servidor.", "Cancel": "Cancelar", "Cancel new bot": "Cancelar novo bot", @@ -125,7 +122,6 @@ "Close panel": "Fechar painel", "Close preview": "Fechar pré-visualização", "Close user settings": "Fechar configurações do usuário", - "Close voice settings": "Fechar configurações de voz", "Command": "Comando", "Complete": "Concluir", "Computer": "Computador", @@ -139,7 +135,6 @@ "Connect": "Conectar", "Connect a model": "Conectar um modelo", "Connect API key": "Conecte-se com a chave API", - "Connect ElevenLabs, OpenAI, or Cartesia": "Conecte ElevenLabs, OpenAI ou Cartesia", "Connect MCP server “{name}”": "Conecte o servidor MCP “{name}”", "Connect OAuth": "Conectar OAuth", "Connect remote or local tool servers and choose which agents can use them.": "Conecte servidores de ferramentas remotos ou locais e escolha quais agentes podem usá-los.", @@ -164,7 +159,6 @@ "Could not complete OAuth": "Não foi possível concluir o OAuth", "Could not connect": "Não foi possível conectar", "Could not connect this provider": "Não foi possível conectar este provedor", - "Could not connect this voice provider": "Não foi possível conectar este provedor de voz", "Could not continue": "Não foi possível continuar", "Could not create bot": "Não foi possível criar o bot", "Could not create group": "Não foi possível criar o grupo", @@ -182,7 +176,6 @@ "Could not load MCP servers": "Não foi possível carregar os servidores MCP", "Could not load model settings": "Não foi possível carregar as configurações do modelo", "Could not load this file.": "Não foi possível carregar este arquivo.", - "Could not load voice settings": "Não foi possível carregar as configurações de voz", "Could not play a test clip": "Não foi possível reproduzir um clipe de teste", "Could not reach this model server": "Não foi possível acessar este servidor modelo", "Could not remove": "Não foi possível remover.", @@ -197,7 +190,6 @@ "Could not save routine": "Não foi possível salvar a rotina", "Could not save rule": "Não foi possível salvar", "Could not save that choice": "Não foi possível salvar essa opção", - "Could not save that voice": "Não foi possível salvar essa voz", "Could not save this choice": "Não foi possível salvar esta opção", "Could not send that": "Não foi possível enviar", "Could not start OAuth": "Não foi possível iniciar o OAuth", @@ -279,14 +271,11 @@ "Hear a sample": "Ouvir uma amostra", "Hi, this is how I'll sound when I read replies out loud.": "Olá, é assim que vou soar quando ler as respostas em voz alta.", "High": "Alto", - "Hold to talk": "Segure para falar", - "Hold to talk (on-device dictation)": "Segure para falar (ditado no dispositivo)", "hour": "hora", "hours": "horas", "How often": "Com que frequência", "How to check": "Como verificar", "I’m done": "Eu terminei.", - "If you heard that, voice is ready.": "Se você ouviu isso, a voz está pronta.", "Import OpenAPI JSON": "Importar OpenAPI JSON", "Inputs": "Entradas", "Instruction": "Instrução", @@ -309,7 +298,6 @@ "Loading peer messages…": "Carregando mensagens de pares...", "Loading preview…": "Carregando Visualização…", "Loading rules…": "Carregando regras…", - "Loading voice providers…": "Carregando provedores de voz...", "Loading…": "Carregando...", "Log out": "Sair", "Low": "Baixo", @@ -398,7 +386,6 @@ "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed.": "Cole o endereço compatível com OpenAI do seu servidor. Milo adiciona /v1 se necessário.", "Paste your API key": "Cole sua chave API", "Personal credential": "Senha Pessoal", - "Pick a voice": "Escolha uma voz", "Pin": "Fixar", "Playing…": "Reproduzindo", "Preview {0}": "Pré-visualizar {0}", @@ -461,7 +448,6 @@ "Sending…": "Enviando…", "Server name": "Nome do servidor", "Server URL": "URL do servidor", - "Set up voice to call": "Configurar voz para ligar", "Settings": "Configurações", "Settings: General": "Opções > Geral", "Settings: Usage": "Configurações: Uso", @@ -478,18 +464,11 @@ "Skip or deploy key": "Ignorar ou implantar chave", "Skipped {0}": "{0} ignorado", "Space interrupts · Esc hangs up": "Interrupções de espaço · Esc desliga", - "Speak": "Falar", - "Speak + transcribe": "Falar + transcrever", - "Speak only": "Falar apenas", - "Speak this reply": "Fale esta resposta", - "Speaking…": "Falando…", "Start recording": "Começar a gravar", "Starting": "Iniciando", "Starting…": "Iniciando…", "Steps": "Passos", "Stop": "Parar", - "Stop dictation": "Parar ditado", - "Stop speaking": "Pare de Falar", "Stop teaching": "Parar de ensinar", "Stop the bot first": "Pare o bot primeiro", "Stored encrypted": "Armazenado criptografado", @@ -533,7 +512,6 @@ "Use this model": "Use este modelo", "Verify and add": "Verificar e adicionar", "Verifying…": "Verificando…", - "Voice": "Voz", "Waiting for sign-in…": "Aguardando login...", "Waiting…": "Aguardando…", "Weekdays": "Dias da semana", diff --git a/apps/web/scripts/translations-tr.json b/apps/web/scripts/translations-tr.json index fa52ba4d..41d5a006 100644 --- a/apps/web/scripts/translations-tr.json +++ b/apps/web/scripts/translations-tr.json @@ -30,7 +30,6 @@ "Action confirmations": "İşlem onayları", "Actions for {0}": "{0} için işlemler", "Active model": "Etkin model", - "Active voice": "Etkin ses", "Activity": "Etkinlik", "Add": "Ekle", "Add a server": "Sunucu ekle", @@ -96,8 +95,6 @@ "Bot screen": "Bot ekranı", "Bot screen preview": "Bot ekranı önizlemesi", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "Botlar varsayılan olarak sormadan hareket eder. Yalnızca belirli bir işlem türünü önce incelemek istediğinde istisna ekle.", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "Kendi anahtarını getir. Sağlayıcı değiştirilebilir; botlarındaki seslendirme ve arama düğmeleri aynı kalır.", - "Call": "Ara", "Can't reach the server.": "Sunucuya ulaşılamıyor.", "Cancel": "İptal", "Cancel new bot": "Yeni botu iptal et", @@ -126,7 +123,6 @@ "Close panel": "Paneli kapat", "Close preview": "Önizlemeyi kapat", "Close user settings": "Kullanıcı ayarlarını kapat", - "Close voice settings": "Ses ayarlarını kapat", "Command": "Komut", "Complete": "Tamamlandı", "Computer": "Bilgisayar", @@ -141,7 +137,6 @@ "Connect a model": "Model bağla", "Connect API key": "API anahtarıyla bağlan", "Connect apps or add Treg, MCP, and OpenAPI tool sources.": "Uygulamaları bağla veya Treg, MCP ve OpenAPI araç kaynakları ekle.", - "Connect ElevenLabs, OpenAI, or Cartesia": "ElevenLabs, OpenAI veya Cartesia bağla", "Connect MCP server “{name}”": "“{name}” MCP sunucusunu bağla", "Connect OAuth": "OAuth ile bağlan", "Connect remote or local tool servers and choose which agents can use them.": "Uzak veya yerel araç sunucuları bağla ve hangi agent'ların kullanabileceğini seç.", @@ -166,7 +161,6 @@ "Could not complete OAuth": "OAuth tamamlanamadı", "Could not connect": "Bağlanılamadı", "Could not connect this provider": "Bu sağlayıcı bağlanamadı", - "Could not connect this voice provider": "Bu ses sağlayıcısı bağlanamadı", "Could not continue": "Devam edilemedi", "Could not create bot": "Bot oluşturulamadı", "Could not create group": "Grup oluşturulamadı", @@ -184,7 +178,6 @@ "Could not load MCP servers": "MCP sunucuları yüklenemedi", "Could not load model settings": "Model ayarları yüklenemedi", "Could not load this file.": "Bu dosya yüklenemedi.", - "Could not load voice settings": "Ses ayarları yüklenemedi", "Could not play a test clip": "Deneme sesi çalınamadı", "Could not reach this model server": "Bu model sunucusuna ulaşılamadı", "Could not remove": "Kaldırılamadı", @@ -199,7 +192,6 @@ "Could not save routine": "Rutin kaydedilemedi", "Could not save rule": "Kural kaydedilemedi", "Could not save that choice": "Bu seçim kaydedilemedi", - "Could not save that voice": "Bu ses kaydedilemedi", "Could not save this choice": "Bu seçim kaydedilemedi", "Could not send that": "Gönderilemedi", "Could not start OAuth": "OAuth başlatılamadı", @@ -280,14 +272,11 @@ "Hear a sample": "Örnek dinle", "Hi, this is how I'll sound when I read replies out loud.": "Merhaba, yanıtları sesli okuduğumda böyle duyulacağım.", "High": "Yüksek", - "Hold to talk": "Konuşmak için basılı tut", - "Hold to talk (on-device dictation)": "Konuşmak için basılı tut (cihaz üzerinde dikte)", "hour": "saat", "hours": "saat", "How often": "Ne sıklıkla", "How to check": "Nasıl kontrol edilir", "I’m done": "Bitirdim", - "If you heard that, voice is ready.": "Bunu duyduysan ses hazır.", "Import OpenAPI JSON": "OpenAPI JSON içe aktar", "Inputs": "Girdiler", "Instruction": "Talimat", @@ -311,7 +300,6 @@ "Loading peer messages…": "Eş bot mesajları yükleniyor…", "Loading preview…": "Önizleme yükleniyor…", "Loading rules…": "Kurallar yükleniyor…", - "Loading voice providers…": "Ses sağlayıcıları yükleniyor…", "Loading…": "Yükleniyor…", "Log out": "Çıkış yap", "Low": "Düşük", @@ -401,7 +389,6 @@ "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed.": "Sunucundaki OpenAI uyumlu adresi yapıştır. Gerekirse Milo /v1 ekler.", "Paste your API key": "API anahtarını yapıştır", "Personal credential": "Kişisel kimlik bilgisi", - "Pick a voice": "Bir ses seç", "Pin": "Sabitle", "Playing…": "Çalınıyor…", "Preview {0}": "{0} önizle", @@ -457,7 +444,6 @@ "Sending…": "Gönderiliyor…", "Server name": "Sunucu adı", "Server URL": "Sunucu URL'si", - "Set up voice to call": "Arama için sesi ayarla", "Settings": "Ayarlar", "Settings: General": "Ayarlar: Genel", "Settings: Usage": "Ayarlar: Kullanım", @@ -474,18 +460,11 @@ "Skip or deploy key": "Atla veya dağıtım anahtarı kullan", "Skipped {0}": "{0} atlandı", "Space interrupts · Esc hangs up": "Boşluk keser · Esc aramayı sonlandırır", - "Speak": "Seslendir", - "Speak + transcribe": "Seslendir + yazıya dök", - "Speak only": "Yalnızca seslendir", - "Speak this reply": "Bu yanıtı seslendir", - "Speaking…": "Konuşuyor…", "Start recording": "Kaydı başlat", "Starting": "Başlıyor", "Starting…": "Başlatılıyor…", "Steps": "Adımlar", "Stop": "Durdur", - "Stop dictation": "Dikteyi durdur", - "Stop speaking": "Seslendirmeyi durdur", "Stop teaching": "Öğretmeyi durdur", "Stop the bot first": "Önce botu durdur", "Stored encrypted": "Şifreli saklanıyor", @@ -527,7 +506,6 @@ "Use this model": "Bu modeli kullan", "Verify and add": "Doğrula ve ekle", "Verifying…": "Doğrulanıyor…", - "Voice": "Ses", "Waiting for sign-in…": "Oturum açma bekleniyor…", "Waiting…": "Bekleniyor…", "Weekdays": "Hafta içi", diff --git a/apps/web/scripts/translations-zh-CN.json b/apps/web/scripts/translations-zh-CN.json index 41679194..c14d0395 100644 --- a/apps/web/scripts/translations-zh-CN.json +++ b/apps/web/scripts/translations-zh-CN.json @@ -36,7 +36,6 @@ "Action confirmations": "操作确认", "Actions for {0}": "{0} 的操作", "Active model": "当前模型", - "Active voice": "当前语音", "Activity": "动态", "Add": "添加", "Add a server": "添加服务器", @@ -102,8 +101,6 @@ "Bot screen": "Bot 屏幕", "Bot screen preview": "Bot 屏幕预览", "Bots act without asking by default. Add an exception only when you want to review a type of action first.": "默认情况下 Bot 会直接执行。只有当你想先审核某类操作时,才添加例外。", - "Bring your own key. The provider is swappable; your bots keep the same speak and call buttons.": "使用你自己的密钥。提供方可更换,Bot 的朗读和通话按钮不变。", - "Call": "通话", "Can't reach the server.": "无法连接服务器。", "Cancel": "取消", "Cancel new bot": "取消新建 Bot", @@ -132,7 +129,6 @@ "Close panel": "关闭面板", "Close preview": "关闭预览", "Close user settings": "关闭用户设置", - "Close voice settings": "关闭语音设置", "Command": "命令", "Complete": "完成", "Computer": "电脑", @@ -146,7 +142,6 @@ "Connect": "连接", "Connect a model": "连接模型", "Connect API key": "连接 API 密钥", - "Connect ElevenLabs, OpenAI, or Cartesia": "连接 ElevenLabs、OpenAI 或 Cartesia", "Connect MCP server “{name}”": "连接 MCP 服务器“{name}”", "Connect OAuth": "连接 OAuth", "Connect remote or local tool servers and choose which agents can use them.": "连接远程或本地工具服务器,并选择哪些 Agent 可以使用。", @@ -170,7 +165,6 @@ "Could not complete OAuth": "无法完成 OAuth", "Could not connect": "无法连接", "Could not connect this provider": "无法连接此提供方", - "Could not connect this voice provider": "无法连接此语音提供方", "Could not continue": "无法继续", "Could not create bot": "无法创建 Bot", "Could not create group": "无法创建群组", @@ -188,7 +182,6 @@ "Could not load MCP servers": "无法加载 MCP 服务器", "Could not load model settings": "无法加载模型设置", "Could not load this file.": "无法加载此文件。", - "Could not load voice settings": "无法加载语音设置", "Could not play a test clip": "无法播放测试片段", "Could not reach this model server": "无法访问此模型服务器", "Could not remove": "无法移除", @@ -203,7 +196,6 @@ "Could not save routine": "无法保存例行任务", "Could not save rule": "无法保存规则", "Could not save that choice": "无法保存该选择", - "Could not save that voice": "无法保存该语音", "Could not save this choice": "无法保存此选择", "Could not send that": "无法发送", "Could not start OAuth": "无法开始 OAuth", @@ -286,14 +278,11 @@ "Hear a sample": "试听", "Hi, this is how I'll sound when I read replies out loud.": "你好,这是我朗读回复时的声音。", "High": "高", - "Hold to talk": "按住说话", - "Hold to talk (on-device dictation)": "按住说话(设备端口述)", "hour": "小时", "hours": "小时", "How often": "频率", "How to check": "如何检查", "I’m done": "我做完了", - "If you heard that, voice is ready.": "如果听到了,说明语音已就绪。", "Import OpenAPI JSON": "导入 OpenAPI JSON", "Inputs": "输入", "Instruction": "指令", @@ -315,7 +304,6 @@ "Loading peer messages…": "正在加载同事消息…", "Loading preview…": "正在加载预览…", "Loading rules…": "正在加载规则…", - "Loading voice providers…": "正在加载语音提供方…", "Loading…": "加载中…", "Log out": "退出登录", "Low": "低", @@ -402,7 +390,6 @@ "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed.": "粘贴服务器的 OpenAI 兼容地址。需要时 Milo 会补上 /v1。", "Paste your API key": "粘贴你的 API 密钥", "Personal credential": "个人凭据", - "Pick a voice": "选择语音", "Pin": "置顶", "Playing…": "播放中…", "Preview {0}": "预览 {0}", @@ -458,7 +445,6 @@ "Sending…": "正在发送…", "Server name": "服务器名称", "Server URL": "服务器 URL", - "Set up voice to call": "设置通话语音", "Settings": "设置", "Settings: General": "设置:通用", "Settings: Usage": "设置:用量", @@ -475,18 +461,11 @@ "Skip or deploy key": "跳过或使用部署密钥", "Skipped {0}": "已跳过 {0}", "Space interrupts · Esc hangs up": "空格键打断 · Esc 挂断", - "Speak": "朗读", - "Speak + transcribe": "朗读 + 转写", - "Speak only": "仅朗读", - "Speak this reply": "朗读这条回复", - "Speaking…": "正在朗读…", "Start recording": "开始录制", "Starting": "正在开始", "Starting…": "正在开始…", "Steps": "步骤", "Stop": "停止", - "Stop dictation": "停止口述", - "Stop speaking": "停止朗读", "Stop teaching": "停止示范", "Stop the bot first": "请先停止 Bot", "Stored encrypted": "已加密存储", @@ -528,7 +507,6 @@ "Use this model": "使用此模型", "Verify and add": "校验并添加", "Verifying…": "正在校验…", - "Voice": "语音", "Waiting for sign-in…": "等待登录…", "Waiting…": "等待中…", "Weekdays": "工作日", diff --git a/apps/web/src/components/call/CallCard.tsx b/apps/web/src/components/call/CallCard.tsx deleted file mode 100644 index 71d502a3..00000000 --- a/apps/web/src/components/call/CallCard.tsx +++ /dev/null @@ -1,137 +0,0 @@ -import { useLingui } from "@lingui/react/macro"; -import { BotAvatar, Button, cn } from "@milo/ui-web"; -import { Captions, Mic, MicOff, PhoneOff, Settings, User } from "lucide-react"; -import { useEffect } from "react"; -import { useNavigate, useParams } from "react-router-dom"; -import { endCall, toggleMute, toggleTranscript, useCallSession } from "../../lib/call-session"; - -const BARS = [9, 15, 21, 15, 9]; -const TRANSCRIPT_LINES = 4; -const EDITABLE = /^(?:input|textarea|select)$/i; - -export function CallCard({ onSettings }: { onSettings: () => void }) { - const { t } = useLingui(); - const call = useCallSession(); - const navigate = useNavigate(); - const { botId } = useParams(); - const onCall = Boolean(call); - useEffect(() => { - if (!onCall) return; - function onKey(event: KeyboardEvent) { - if (event.key !== "Escape" || event.defaultPrevented) return; - const target = event.target as HTMLElement | null; - if (target?.isContentEditable || EDITABLE.test(target?.tagName ?? "")) return; - endCall(); - } - window.addEventListener("keydown", onKey); - return () => window.removeEventListener("keydown", onKey); - }, [onCall]); - if (!call) return null; - const onBotScreen = botId === call.botId; - return ( -
-
- - - - -
-
- - - - -
- {call.transcriptOpen ? ( -
- {call.exchanges.slice(-TRANSCRIPT_LINES).map((exchange, index) => ( -

- {exchange.text} -

- ))} - {call.caption || call.heard ? ( -

- {call.caption || call.heard} -

- ) : null} -
- ) : null} -
- ); -} diff --git a/apps/web/src/components/call/VoiceChatCard.test.tsx b/apps/web/src/components/call/VoiceChatCard.test.tsx deleted file mode 100644 index 48b30ce8..00000000 --- a/apps/web/src/components/call/VoiceChatCard.test.tsx +++ /dev/null @@ -1,75 +0,0 @@ -// @vitest-environment jsdom - -import type { VoiceChatGroup } from "@milo/core"; -import type { ReactNode } from "react"; -import { act } from "react"; -import type { Root } from "react-dom/client"; -import { createRoot } from "react-dom/client"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { VoiceChatCard } from "./VoiceChatCard"; - -vi.mock("@lingui/react/macro", () => { - const t = (parts: TemplateStringsArray) => parts.join(""); - return { useLingui: () => ({ t }), Trans: ({ children }: { children: ReactNode }) => children }; -}); - -const marker = { - id: "marker-1", - role: "bot", - blocks: [{ kind: "voice_call" as const, title: "Booked a flight", farewell: "Talk soon" }], -}; - -const group: VoiceChatGroup = { - kind: "voiceChat", - key: "call:call-1", - callId: "call-1", - messages: [ - { id: "user-1", role: "user", blocks: [{ kind: "text", text: "book the flight" }] }, - { id: "bot-1", role: "bot", blocks: [{ kind: "text", text: "Booked." }] }, - marker, - ], - marker, -}; - -describe("VoiceChatCard", () => { - let root: Root | undefined; - let container: HTMLDivElement | undefined; - - afterEach(() => { - act(() => root?.unmount()); - container?.remove(); - root = undefined; - container = undefined; - }); - - function render(revealMessageId?: string) { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); - act(() => { - root?.render(); - }); - return container; - } - - it("stays collapsed until a jump targets a message inside it", () => { - const collapsed = render(); - expect(collapsed.querySelector("[data-message-id]")).toBeNull(); - expect(collapsed.querySelector("button")?.getAttribute("aria-expanded")).toBe("false"); - - act(() => root?.unmount()); - container?.remove(); - const opened = render("user-1"); - expect(opened.querySelector("button")?.getAttribute("aria-expanded")).toBe("true"); - expect(opened.querySelector('[data-message-id="user-1"]')?.textContent).toBe("book the flight"); - expect(opened.querySelector('[data-message-id="bot-1"]')?.textContent).toBe("Booked."); - expect(opened.querySelector('[data-message-id="marker-1"]')).not.toBeNull(); - - act(() => { - root?.render(); - }); - expect(opened.querySelector("button")?.getAttribute("aria-expanded")).toBe("true"); - expect(opened.querySelector('[data-message-id="user-1"]')).not.toBeNull(); - }); -}); diff --git a/apps/web/src/components/call/VoiceChatCard.tsx b/apps/web/src/components/call/VoiceChatCard.tsx deleted file mode 100644 index 2039a24e..00000000 --- a/apps/web/src/components/call/VoiceChatCard.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { useLingui } from "@lingui/react/macro"; -import type { VoiceChatGroup } from "@milo/core"; -import { speechFromBlocks, voiceChatDuration, voiceChatSummary } from "@milo/core"; -import { buttonVariants, cn } from "@milo/ui-web"; -import { AudioLines, ChevronDown } from "lucide-react"; -import { useState } from "react"; - -function clock(seconds: number): string { - return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; -} - -export function VoiceChatCard({ - group, - revealMessageId, -}: { - group: VoiceChatGroup; - revealMessageId?: string; -}) { - const { t } = useLingui(); - const [open, setOpen] = useState(false); - const revealed = - revealMessageId != null && group.messages.some((message) => message.id === revealMessageId); - // A jump looks the row up in the same commit. Expand during render so the row exists, - // and leave the card open after the request clears. - if (revealed && !open) setOpen(true); - const summary = voiceChatSummary(group); - return ( -
- - {!open && summary ? ( -

- {summary} -

- ) : null} - {open ? ( -
- {group.messages.map((message) => { - // The marker is the card's summary line, never a transcript turn. - const text = message === group.marker ? "" : speechFromBlocks(message.blocks).trim(); - if (!text) { - return ; - } - return ( -

- {text} -

- ); - })} -
- ) : null} -
- ); -} diff --git a/apps/web/src/lib/call-session.test.ts b/apps/web/src/lib/call-session.test.ts deleted file mode 100644 index 8f02faec..00000000 --- a/apps/web/src/lib/call-session.test.ts +++ /dev/null @@ -1,825 +0,0 @@ -import type { ProductEvent, ThreadMessage, ThreadSnapshot } from "@milo/contracts"; -import { - callIdFromClientNonce, - groupVoiceChats, - INTERIM_BARGE_IN_MS, - runThreadSubscription, -} from "@milo/core"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ECHO_GUARD_MS, endCall, getSnapshot, startCall, toggleMute } from "./call-session"; -import { dictation } from "./dictation.js"; -import { rpc } from "./rpc.js"; -import { reduceThreadSnapshot } from "./thread-events.js"; -import { speaker } from "./tts.js"; - -// The macro compiles away in the app build; tests run the source, so tag the template as-is. -vi.mock("@lingui/core/macro", () => ({ - t: (strings: TemplateStringsArray, ...values: unknown[]) => String.raw(strings, ...values), -})); - -vi.mock("@milo/core", async (importOriginal) => ({ - ...(await importOriginal()), - runThreadSubscription: vi.fn(async () => undefined), -})); - -vi.mock("./dictation.js", () => ({ - dictation: { - listen: vi.fn(async () => undefined), - stop: vi.fn(), - subscribe: vi.fn(() => () => undefined), - }, -})); - -vi.mock("./tts.js", () => ({ - speaker: { - speak: vi.fn(async () => undefined), - stop: vi.fn(), - isSpeaking: vi.fn(() => false), - subscribe: vi.fn(() => () => undefined), - }, -})); - -vi.mock("./rpc.js", () => ({ - rpc: { - threads: { - answer: vi.fn(), - endCall: vi.fn(async () => ({ ok: true })), - followUp: vi.fn(), - get: vi.fn(), - head: vi.fn(), - send: vi.fn(), - subscribe: vi.fn(), - }, - }, -})); - -const listen = vi.mocked(dictation.listen); -const speak = vi.mocked(speaker.speak); -const isSpeaking = vi.mocked(speaker.isSpeaking); -const send = vi.mocked(rpc.threads.send); -const followUp = vi.mocked(rpc.threads.followUp); -const getThread = vi.mocked(rpc.threads.get); -const endCallRpc = vi.mocked(rpc.threads.endCall); - -describe("call session", () => { - beforeEach(() => { - endCall(); - vi.clearAllMocks(); - vi.useFakeTimers(); - isSpeaking.mockReturnValue(false); - listen.mockResolvedValue(undefined); - getThread.mockResolvedValue(snapshot([]) as never); - send.mockResolvedValue({ runId: "run-1", taskId: "task-1" } as never); - endCallRpc.mockResolvedValue({ ok: true } as never); - }); - - afterEach(() => { - endCall(); - vi.useRealTimers(); - }); - - it("starts listening for the bot on the call", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: true }); - await Promise.resolve(); - - expect(getSnapshot()).toMatchObject({ - botId: "call-bot", - botName: "Ada", - phase: "listening", - muted: false, - }); - expect(listen).toHaveBeenCalledWith(expect.objectContaining({ transcribe: true })); - }); - - it("sends what it heard to the bot on the call, not the bot on screen", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await heard("book the flight"); - - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ botId: "call-bot", text: "book the flight" }), - ); - expect(getSnapshot()).toMatchObject({ - phase: "thinking", - exchanges: [{ role: "user", text: "book the flight" }], - }); - }); - - it("drops a send that finishes after the same bot is called again", async () => { - let finishSend: (value: { runId: string; taskId: string }) => void = () => undefined; - let failSend: (error: Error) => void = () => undefined; - send.mockImplementation( - () => - new Promise((resolve, reject) => { - finishSend = resolve; - failSend = reject; - }) as never, - ); - - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const first = heard("book the flight"); - expect(send).toHaveBeenCalledTimes(1); - - endCall(); - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const listens = listen.mock.calls.length; - getThread.mockClear(); - finishSend({ runId: "run-old", taskId: "task-old" }); - await first; - - expect(getThread).not.toHaveBeenCalled(); - expect(getSnapshot()).toMatchObject({ - botId: "call-bot", - phase: "listening", - caption: "", - }); - expect(listen.mock.calls.length).toBe(listens); - - const second = heard("window seat"); - expect(send).toHaveBeenCalledTimes(2); - endCall(); - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const listensAfter = listen.mock.calls.length; - failSend(new Error("offline")); - await second; - - expect(getSnapshot()).toMatchObject({ - botId: "call-bot", - phase: "listening", - caption: "", - }); - expect(listen.mock.calls.length).toBe(listensAfter); - }); - - it("tags every message in one call with the same call id", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await heard("book the flight"); - await heard("window seat please"); - - const nonces = send.mock.calls.map((call) => String(call[0]?.clientNonce)); - expect(nonces).toHaveLength(2); - expect(nonces[0]?.startsWith("call:")).toBe(true); - expect(callIdFromClientNonce(nonces[0])).toBe(callIdFromClientNonce(nonces[1])); - expect(nonces[0]).not.toBe(nonces[1]); - }); - - it("speaks a reply from the call's own feed, then listens again", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Booked for Friday")]) as never); - await heard("book the flight"); - - expect(speak).toHaveBeenCalledWith( - "Booked for Friday", - expect.objectContaining({ botId: "call-bot", messageId: "message-1" }), - ); - expect(getSnapshot()?.exchanges.at(-1)).toEqual({ role: "bot", text: "Booked for Friday" }); - - const speech = vi.mocked(speaker.subscribe).mock.calls[0]?.[0]; - listen.mockClear(); - speech?.({ status: "speaking", caption: "Booked for Friday" }); - await Promise.resolve(); - expect(getSnapshot()?.phase).toBe("speaking"); - // Dictation runs through playback so the caller can cut in. - expect(listen).toHaveBeenCalledTimes(1); - - listen.mockClear(); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - expect(getSnapshot()?.phase).toBe("listening"); - expect(listen).not.toHaveBeenCalled(); - }); - - it("waits out the echo guard when the mic was shut through playback", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await Promise.resolve(); - toggleMute(); - listen.mockClear(); - - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Booked for Friday" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS * 2); - expect(listen).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("speaking"); - - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS - 1); - expect(getSnapshot()?.phase).toBe("speaking"); - - await vi.advanceTimersByTimeAsync(1); - expect(getSnapshot()?.phase).toBe("listening"); - }); - - it("ignores the reply leaking into the mic while it plays", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await speakingReply("I'm here and hearing you"); - send.mockClear(); - vi.mocked(speaker.stop).mockClear(); - - await heard("hey I am here and here"); - - expect(send).not.toHaveBeenCalled(); - expect(speaker.stop).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("speaking"); - }); - - it("stops the reply when the caller talks over it", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const speech = await speakingReply("Booked for Friday"); - send.mockClear(); - speak.mockClear(); - vi.mocked(speaker.stop).mockClear(); - - await heard("wait, what about the deploy"); - - expect(speaker.stop).toHaveBeenCalled(); - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ text: "wait, what about the deploy" }), - ); - expect(getSnapshot()?.phase).toBe("thinking"); - - // The cut-off reply is spoken, so nothing resumes it and no guard runs. - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - expect(speak).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("thinking"); - }); - - it("lets a one-word interruption cut the reply short", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await speakingReply("Booked for Friday"); - send.mockClear(); - vi.mocked(speaker.stop).mockClear(); - - await heard("stop"); - - expect(speaker.stop).toHaveBeenCalled(); - expect(send).toHaveBeenCalledWith(expect.objectContaining({ text: "stop" })); - }); - - it("keeps playing through a one-word backchannel", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await speakingReply("Booked for Friday"); - send.mockClear(); - vi.mocked(speaker.stop).mockClear(); - - await heard("yeah"); - - expect(send).not.toHaveBeenCalled(); - expect(speaker.stop).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("speaking"); - }); - - it("drops a transcript that is the reply coming back through the mic", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue( - snapshot([botMessage("message-1", "I'm here and hearing you")]) as never, - ); - await heard("book the flight"); - send.mockClear(); - listen.mockClear(); - - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - await heard("hey I am here and here"); - - expect(send).not.toHaveBeenCalled(); - expect(getSnapshot()?.exchanges.at(-1)).toEqual({ - role: "bot", - text: "I'm here and hearing you", - }); - expect(listen).toHaveBeenCalledTimes(2); - }); - - it("ignores the reply coming back after a newer one was spoken", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue( - snapshot([botMessage("message-1", "I'm here and hearing you")]) as never, - ); - await heard("book the flight"); - getThread.mockResolvedValue( - snapshot([ - botMessage("message-1", "I'm here and hearing you"), - botMessage("message-2", "Booked for Friday"), - ]) as never, - ); - await feed?.refresh(); - expect(speak).toHaveBeenCalledTimes(2); - send.mockClear(); - - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - await heard("hey I am here and here"); - - expect(send).not.toHaveBeenCalled(); - }); - - it("keeps a turn taken mid-run in the call's card", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue(snapshot([], runningRun) as never); - await heard("book the flight"); - await heard("window seat please"); - - expect(send).toHaveBeenCalledTimes(1); - expect(followUp).toHaveBeenCalledWith( - expect.objectContaining({ botId: "call-bot", text: "window seat please" }), - ); - const sent = String(send.mock.calls[0]?.[0]?.clientNonce); - const followed = String(followUp.mock.calls[0]?.[0]?.clientNonce); - expect(followed.startsWith("call:")).toBe(true); - expect(callIdFromClientNonce(followed)).toBe(callIdFromClientNonce(sent)); - expect(followed).not.toBe(sent); - }); - - it("stops listening while muted", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await Promise.resolve(); - listen.mockClear(); - - toggleMute(); - expect(getSnapshot()).toMatchObject({ muted: true, heard: "" }); - expect(dictation.stop).toHaveBeenCalledWith("cancel"); - expect(listen).not.toHaveBeenCalled(); - - toggleMute(); - await Promise.resolve(); - expect(getSnapshot()?.muted).toBe(false); - expect(listen).toHaveBeenCalledTimes(1); - }); - - it("aborts the call feed and clears the store on hang up", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - expect(feed?.signal.aborted).toBe(false); - - endCall(); - - expect(feed?.signal.aborted).toBe(true); - expect(getSnapshot()).toBeNull(); - expect(speaker.stop).toHaveBeenCalled(); - }); - - it("closes the call server-side when the caller presses hang up", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await heard("book the flight"); - const callId = String(callIdFromClientNonce(String(send.mock.calls[0]?.[0]?.clientNonce))); - - endCall(); - - expect(endCallRpc).toHaveBeenCalledWith({ botId: "call-bot", callId }); - }); - - it("closes the call server-side once when the caller says goodbye", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Talk soon")]) as never); - await heard("that's all, bye"); - const callId = String(callIdFromClientNonce(String(send.mock.calls[0]?.[0]?.clientNonce))); - - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Talk soon" }); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - - expect(getSnapshot()).toBeNull(); - expect(endCallRpc).toHaveBeenCalledTimes(1); - expect(endCallRpc).toHaveBeenCalledWith({ botId: "call-bot", callId }); - }); - - it("does not close the call again when the bot ended it", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([], runningRun) as never); - await heard("end the call and make me a list"); - const callId = String(callIdFromClientNonce(String(send.mock.calls[0]?.[0]?.clientNonce))); - - feed?.onEvent?.(callEndedEvent(callId), { threadId: "thread-1", cursor: 3 }); - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Talk soon" }); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - - expect(getSnapshot()).toBeNull(); - expect(endCallRpc).not.toHaveBeenCalled(); - }); - - it("tears the previous call down before opening the next call's feed", async () => { - const unsubSpeech = vi.fn(); - const unsubDictation = vi.fn(); - vi.mocked(speaker.subscribe).mockReturnValueOnce(unsubSpeech); - vi.mocked(dictation.subscribe).mockReturnValueOnce(unsubDictation); - startCall({ botId: "bot-a", botName: "Ada", transcribe: false }); - const feedA = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - - let abortedWhenNextOpened: boolean | null = null; - vi.mocked(runThreadSubscription).mockImplementationOnce(async () => { - abortedWhenNextOpened = feedA?.signal.aborted ?? null; - }); - startCall({ botId: "bot-b", botName: "Grace", transcribe: false }); - await Promise.resolve(); - - expect(unsubSpeech).toHaveBeenCalledTimes(1); - expect(unsubDictation).toHaveBeenCalledTimes(1); - expect(abortedWhenNextOpened).toBe(true); - expect(getSnapshot()?.botId).toBe("bot-b"); - }); - - it("does not let an earlier farewell timer end the next call", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Talk soon")]) as never); - await heard("that's all"); - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Talk soon" }); - await Promise.resolve(); - - await heard("see you"); - endCall(); - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await Promise.resolve(); - await vi.advanceTimersByTimeAsync(20_000); - - expect(getSnapshot()?.botId).toBe("call-bot"); - }); - - it("hangs up once the bot has answered a goodbye", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Talk soon")]) as never); - await heard("that's all, bye"); - - expect(send).toHaveBeenCalledWith( - expect.objectContaining({ botId: "call-bot", text: "that's all, bye" }), - ); - expect(speak).toHaveBeenCalledWith( - "Talk soon", - expect.objectContaining({ messageId: "message-1" }), - ); - - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Talk soon" }); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - - expect(getSnapshot()).toBeNull(); - }); - - it("speaks the farewell and hangs up when the bot ends the call itself", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([], runningRun) as never); - await heard("end the call and make me a list"); - const callId = String(callIdFromClientNonce(String(send.mock.calls[0]?.[0]?.clientNonce))); - - feed?.onEvent?.(callEndedEvent(callId), { threadId: "thread-1", cursor: 3 }); - expect(speak).toHaveBeenCalledWith( - "Talk soon", - expect.objectContaining({ messageId: "message-marker" }), - ); - - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Talk soon" }); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - - expect(getSnapshot()).toBeNull(); - }); - - it("never speaks the work the bot files after it hung up", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([], runningRun) as never); - await heard("end the call and make me a list"); - const callId = String(callIdFromClientNonce(String(send.mock.calls[0]?.[0]?.clientNonce))); - feed?.onEvent?.(callEndedEvent(callId), { threadId: "thread-1", cursor: 3 }); - expect(speak).toHaveBeenCalledTimes(1); - - getThread.mockResolvedValue(snapshot([botMessage("message-2", "Here is the list")]) as never); - await feed?.refresh(); - - expect(speak).toHaveBeenCalledTimes(1); - }); - - it("ignores a call ended event from another call", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Talk soon")]) as never); - await heard("book the flight"); - - feed?.onEvent?.(callEndedEvent("someone-elses-call"), { threadId: "thread-1", cursor: 3 }); - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: "Talk soon" }); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - - expect(getSnapshot()?.phase).toBe("listening"); - }); - - it("speaks a streaming reply once, with the text its run finished on", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Booked")], runningRun) as never); - await heard("book the flight"); - expect(speak).not.toHaveBeenCalled(); - - getThread.mockResolvedValue( - snapshot([botMessage("message-1", "Booked for Friday")], runningRun) as never, - ); - await feed?.refresh(); - expect(speak).not.toHaveBeenCalled(); - - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Booked for Friday")]) as never); - await feed?.refresh(); - expect(speak).toHaveBeenCalledTimes(1); - expect(speak).toHaveBeenCalledWith( - "Booked for Friday", - expect.objectContaining({ messageId: "message-1" }), - ); - }); - - it("does not speak a message a refresh re-delivers", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Booked for Friday")]) as never); - await heard("book the flight"); - expect(speak).toHaveBeenCalledTimes(1); - - await feed?.refresh(); - await feed?.refresh(); - expect(speak).toHaveBeenCalledTimes(1); - }); - - it("does not start dictation while the speaker is still speaking", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Booked for Friday")]) as never); - await heard("book the flight"); - listen.mockClear(); - - // The previous utterance reports idle after the next one already started playing. - isSpeaking.mockReturnValue(true); - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - expect(listen).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).not.toBe("listening"); - - isSpeaking.mockReturnValue(false); - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - expect(listen).toHaveBeenCalledTimes(1); - }); - - it("tags the call's user message for the thread card before the server copy lands", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await heard("book the flight"); - - const callId = callIdFromClientNonce(String(send.mock.calls[0]?.[0]?.clientNonce)); - expect(callId).toBeDefined(); - // The event itself carries the call id, so the bubble groups with no run - // registered anywhere — note the event below has no runId at all. - const live = reduceThreadSnapshot(snapshot([]), userMessageEvent(String(callId))); - expect(live?.messages[0]?.callId).toBe(callId); - expect(groupVoiceChats(live?.messages ?? [])).toEqual([ - { kind: "voiceChat", key: `call:${callId}`, callId, messages: live?.messages }, - ]); - }); - - it("keeps quiet while the reply is still streaming, then speaks it whole", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([streamingMessage("Hey,")], runningRun) as never); - await heard("are you there"); - expect(speak).not.toHaveBeenCalled(); - - getThread.mockResolvedValue(snapshot([botMessage("message-1", "Hey, I'm here.")]) as never); - await feed?.refresh(); - expect(speak).toHaveBeenCalledTimes(1); - expect(speak).toHaveBeenCalledWith( - "Hey, I'm here.", - expect.objectContaining({ messageId: "message-1" }), - ); - }); - - it("never speaks tool activity on a call, and still speaks the reply", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([subagentMessage()], runningRun) as never); - await heard("what do you know about Anemoia"); - expect(speak).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("thinking"); - - getThread.mockResolvedValue( - snapshot([subagentMessage(), botMessage("message-1", "I know you run Anemoia")]) as never, - ); - await feed?.refresh(); - expect(speak).toHaveBeenCalledTimes(1); - expect(speak).toHaveBeenCalledWith( - "I know you run Anemoia", - expect.objectContaining({ messageId: "message-1" }), - ); - }); - - it("cuts the reply short on an interim heard over it, then sends the finished turn", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const speech = await speakingReply("Booked for Friday"); - send.mockClear(); - vi.mocked(speaker.stop).mockClear(); - - interim("what about the deploy"); - await vi.advanceTimersByTimeAsync(INTERIM_BARGE_IN_MS - 1); - expect(speaker.stop).not.toHaveBeenCalled(); - - await vi.advanceTimersByTimeAsync(1); - expect(speaker.stop).toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("listening"); - - // The cut-off reply never resumes, and the session that is still open finishes the turn. - const sessions = listen.mock.calls.length; - speech?.({ status: "idle" }); - await vi.advanceTimersByTimeAsync(ECHO_GUARD_MS); - expect(listen).toHaveBeenCalledTimes(sessions); - - await heard("what about the deploy"); - expect(send).toHaveBeenCalledWith(expect.objectContaining({ text: "what about the deploy" })); - }); - - it("keeps playing when the interim is the reply leaking into the mic", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await speakingReply("I'm here and hearing you"); - vi.mocked(speaker.stop).mockClear(); - - interim("I am here and hearing"); - await vi.advanceTimersByTimeAsync(INTERIM_BARGE_IN_MS * 2); - - expect(speaker.stop).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("speaking"); - }); - - it("keeps playing when an interim phrase is revised back into an echo", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await speakingReply("I'm here and hearing you"); - vi.mocked(speaker.stop).mockClear(); - - interim("I am"); - await vi.advanceTimersByTimeAsync(INTERIM_BARGE_IN_MS - 100); - interim("I am here and hearing"); - await vi.advanceTimersByTimeAsync(INTERIM_BARGE_IN_MS * 2); - - expect(speaker.stop).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("speaking"); - }); - - it("does not cut the reply for a single interim word", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - await speakingReply("Booked for Friday"); - vi.mocked(speaker.stop).mockClear(); - - interim("yeah"); - await vi.advanceTimersByTimeAsync(INTERIM_BARGE_IN_MS * 2); - - expect(speaker.stop).not.toHaveBeenCalled(); - expect(getSnapshot()?.phase).toBe("speaking"); - }); - - it("speaks only the final reply when a mid-turn progress message came first", async () => { - startCall({ botId: "call-bot", botName: "Ada", transcribe: false }); - const feed = vi.mocked(runThreadSubscription).mock.calls[0]?.[0]; - getThread.mockResolvedValue(snapshot([botMessage("progress-1", "Hey,")], runningRun) as never); - await heard("are you there"); - expect(speak).not.toHaveBeenCalled(); - - getThread.mockResolvedValue( - snapshot([ - botMessage("progress-1", "Hey,"), - botMessage("message-1", "Hey, I'm here."), - ]) as never, - ); - await feed?.refresh(); - expect(speak).toHaveBeenCalledTimes(1); - expect(speak).toHaveBeenCalledWith( - "Hey, I'm here.", - expect.objectContaining({ messageId: "message-1" }), - ); - }); -}); - -/** Drives a call to the point where the bot's reply is playing and the mic is open. */ -async function speakingReply(text: string) { - getThread.mockResolvedValue(snapshot([botMessage("message-1", text)]) as never); - await heard("book the flight"); - const speech = vi.mocked(speaker.subscribe).mock.calls.at(-1)?.[0]; - speech?.({ status: "speaking", caption: text }); - await Promise.resolve(); - return speech; -} - -/** One interim result from the open dictation session, the way the browser reports it. */ -function interim(transcript: string) { - const watcher = vi.mocked(dictation.subscribe).mock.calls.at(-1)?.[0]; - watcher?.({ status: "listening", transcript }); -} - -async function heard(text: string) { - const onFinal = listen.mock.calls.at(-1)?.[0]?.onFinal; - await onFinal?.(text); - await Promise.resolve(); -} - -function botMessage(id: string, text: string): ThreadMessage { - return { - id, - threadId: "thread-1", - seq: 4, - role: "bot", - runId: "run-1", - blocks: [{ kind: "text", text }], - createdAt: "2026-09-20T00:00:00.000Z", - }; -} - -/** The live message the thread streams the reply into while the run is still going. */ -function streamingMessage(text: string): ThreadMessage { - return { - id: "progress:run-1", - threadId: "thread-1", - seq: 4, - role: "bot", - runId: "run-1", - blocks: [{ kind: "progress", text }], - createdAt: "2026-09-20T00:00:00.000Z", - }; -} - -function subagentMessage(): ThreadMessage { - return { - id: "subagent:agent-1", - threadId: "thread-1", - seq: 4, - role: "bot", - runId: "run-1", - blocks: [ - { kind: "subagent", agentId: "agent-1", name: "helper", task: "dig", status: "running" }, - ], - createdAt: "2026-09-20T00:00:00.000Z", - }; -} - -const runningRun = { - id: "run-1", - botId: "call-bot", - threadId: "thread-1", - taskId: "task-1", - status: "running", - trigger: "user", - routineId: null, - modelProvider: null, - modelId: null, - error: null, - startedAt: "2026-09-20T00:00:00.000Z", - completedAt: null, - createdAt: "2026-09-20T00:00:00.000Z", -} as ThreadSnapshot["run"]; - -function callEndedEvent(callId: string, farewell = "Talk soon"): ProductEvent { - return { - id: "event-2", - seq: 6, - spaceId: "space-1", - threadId: "thread-1", - botId: "call-bot", - runId: "run-1", - type: "thread.call.ended", - payload: { - botId: "call-bot", - threadId: "thread-1", - runId: "run-1", - callId, - title: "Made a list", - farewell, - messageId: "message-marker", - }, - createdAt: "2026-09-20T00:00:00.000Z", - } as ProductEvent; -} - -function userMessageEvent(callId: string): ProductEvent { - return { - id: "event-1", - seq: 5, - spaceId: "space-1", - threadId: "thread-1", - botId: "call-bot", - type: "thread.message.created", - payload: { messageId: "message-user", role: "user", blocks: [], callId }, - createdAt: "2026-09-20T00:00:00.000Z", - } as ProductEvent; -} - -function snapshot(messages: ThreadMessage[], run: ThreadSnapshot["run"] = null): ThreadSnapshot { - return { - botId: "call-bot", - threadId: "thread-1", - cursor: 3, - messages, - olderCursor: null, - run, - }; -} diff --git a/apps/web/src/lib/call-session.ts b/apps/web/src/lib/call-session.ts deleted file mode 100644 index c567fb2b..00000000 --- a/apps/web/src/lib/call-session.ts +++ /dev/null @@ -1,496 +0,0 @@ -import { t } from "@lingui/core/macro"; -import type { ThreadMessage, ThreadSnapshot } from "@milo/contracts"; -import { - callClientNonce, - INTERIM_BARGE_IN_MS, - isCallBargeIn, - isFarewell, - isInterimCallBargeIn, - isSecretAskBlock, - runThreadSubscription, - speechFromBlocks, - spokenDecision, - spokenMemory, -} from "@milo/core"; -import { useSyncExternalStore } from "react"; -import { dictation } from "./dictation.js"; -import { rpc } from "./rpc.js"; -import { isThreadSnapshotEvent, reduceThreadSnapshot } from "./thread-events.js"; -import { speaker } from "./tts.js"; - -export type CallPhase = "listening" | "thinking" | "speaking"; -export type CallExchange = { role: "user" | "bot"; text: string }; - -export interface CallState { - botId: string; - botName: string; - botColor: string; - startedAt: number; - phase: CallPhase; - muted: boolean; - transcriptOpen: boolean; - caption: string; - heard: string; - exchanges: CallExchange[]; -} - -const RUN_ACTIVE = ["running", "queued", "leased"]; -/** How long a goodbye waits for a reply that may never come before hanging up anyway. */ -const FAREWELL_TIMEOUT = 20_000; -/** - * Quiet gap between the last audio frame and opening the microphone. - * ponytail: one fixed delay for every room and output device; make it adaptive only - * if a measured tail actually outruns it. - */ -export const ECHO_GUARD_MS = 600; -let state: CallState | null = null; -/** Shared by every message this call sends, so the thread can group one call's exchange. */ -let callId = ""; -let transcribe = false; -let thread: ThreadSnapshot | null = null; -let feed: AbortController | null = null; -/** Every bot message already spoken this call: a streaming message updates many times. */ -const spokenMessageIds = new Set(); -let unsubSpeech: (() => void) | null = null; -let unsubDictation: (() => void) | null = null; -let hangUpAfterReply = false; -/** The bot hung up itself: its farewell is the last thing this call speaks. */ -let botEndedCall = false; -let hangUpTimer: ReturnType | null = null; -/** Pending echo guard: the microphone stays shut until it fires. */ -let guardTimer: ReturnType | null = null; -/** Whether dictation is running, so playback can leave it open instead of restarting it. */ -let micOpen = false; -/** The caller cut the reply off: there is no tail left to wait out before listening. */ -let bargedIn = false; -/** A turn is in flight: its reply must be spoken even if the mic reopened meanwhile. */ -let awaitingReply = false; -/** Counting down an interim phrase heard over the reply, before it counts as cutting in. */ -let interimTimer: ReturnType | null = null; -const watchers = new Set<() => void>(); - -export function subscribe(watcher: () => void): () => void { - watchers.add(watcher); - return () => { - watchers.delete(watcher); - }; -} - -export function getSnapshot(): CallState | null { - return state; -} - -export function useCallSession(): CallState | null { - return useSyncExternalStore(subscribe, getSnapshot, getSnapshot); -} - -function emit() { - for (const watcher of [...watchers]) watcher(); -} - -function set(patch: Partial) { - if (!state) return; - state = { ...state, ...patch }; - emit(); -} - -export function startCall(call: { - botId: string; - botName: string; - botColor?: string; - transcribe: boolean; -}): void { - endCall(); - callId = randomId(); - transcribe = call.transcribe; - spokenMemory.clear(); - clearInterim(); - micOpen = false; - bargedIn = false; - awaitingReply = false; - state = { - botId: call.botId, - botName: call.botName, - botColor: call.botColor ?? "", - startedAt: Date.now(), - phase: "listening", - muted: false, - transcriptOpen: false, - caption: "", - heard: "", - exchanges: [], - }; - unsubSpeech = speaker.subscribe((speech) => { - if (!state) return; - if (speech.status === "speaking") { - bargedIn = false; - set({ phase: "speaking", caption: speech.caption ?? "" }); - // The mic stays open through playback so the caller can talk over the reply. - void openMic(); - } else if (speech.status === "idle" && state.phase !== "listening" && !bargedIn) { - set({ caption: "" }); - guardThenListen(); - } - if (speech.error) set({ caption: speech.error }); - }); - unsubDictation = dictation.subscribe((heard) => { - if (!state) return; - if (heard.status === "listening") { - set({ heard: pendingSecretAsk(thread) ? "" : heard.transcript }); - watchInterim(heard.transcript); - } else clearInterim(); - if (heard.error) set({ caption: heard.error }); - }); - watchThread(call.botId); - emit(); - void listen(); -} - -export function endCall(): void { - // A caller hang-up closes the call server-side, which files the marker and the wrap-up - // run. The bot's own end_call already did that, so only tell the server when it did not. - if (state && !botEndedCall) { - const { botId } = state; - // Fire and forget: the card is going away either way, and the server is idempotent. - void rpc.threads.endCall({ botId, callId }).catch(() => undefined); - } - feed?.abort(); - feed = null; - hangUpAfterReply = false; - botEndedCall = false; - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = null; - if (guardTimer) clearTimeout(guardTimer); - guardTimer = null; - clearInterim(); - micOpen = false; - bargedIn = false; - awaitingReply = false; - unsubSpeech?.(); - unsubDictation?.(); - unsubSpeech = null; - unsubDictation = null; - dictation.stop("cancel"); - speaker.stop(); - thread = null; - spokenMessageIds.clear(); - spokenMemory.clear(); - if (!state) return; - state = null; - emit(); -} - -export function toggleMute(): void { - if (!state) return; - const muted = !state.muted; - set({ muted }); - if (muted) { - dictation.stop("cancel"); - micOpen = false; - set({ heard: "" }); - return; - } - if (state.phase === "listening") void listen(); - else if (state.phase === "speaking") void openMic(); -} - -export function toggleTranscript(): void { - if (!state) return; - set({ transcriptOpen: !state.transcriptOpen }); -} - -/** Live feed for the bot on the call, independent of whichever thread is on screen. */ -function watchThread(botId: string) { - const controller = new AbortController(); - feed = controller; - const load = async () => commit(await rpc.threads.get({ botId }, { signal: controller.signal })); - void runThreadSubscription({ - signal: controller.signal, - loadInitial: load, - loadHead: () => rpc.threads.head({ botId }, { signal: controller.signal }), - refresh: load, - currentSnapshot: () => thread, - subscribe: (cursor) => rpc.threads.subscribe({ botId, cursor }, { signal: controller.signal }), - applyEvent: (event) => { - if (isThreadSnapshotEvent(event)) commit(reduceThreadSnapshot(thread, event)); - }, - onEvent: (event) => { - // The bot hung up: speak the farewell it wrote and stop there — the rest of its - // work lands in the thread as chat, which the caller is no longer listening to. - if (event.type !== "thread.call.ended" || event.payload.callId !== callId) return; - if (botEndedCall) return; - hangUpAfterReply = true; - botEndedCall = true; - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = setTimeout(endCall, FAREWELL_TIMEOUT); - speakFarewell(event.payload); - }, - }); -} - -/** The bot's own goodbye: the last thing this call says before the speaker goes idle. */ -function speakFarewell(payload: Record) { - if (!state) return; - const farewell = typeof payload.farewell === "string" ? payload.farewell.trim() : ""; - const messageId = typeof payload.messageId === "string" ? payload.messageId : undefined; - if (messageId) spokenMessageIds.add(messageId); - // Nothing to say: hang up instead of waiting out the fallback. - if (!farewell) { - endCall(); - return; - } - awaitingReply = false; - set({ exchanges: [...state.exchanges, { role: "bot", text: farewell }], heard: "" }); - spokenMemory.remember(farewell); - void speaker.speak(farewell, { botId: state.botId, messageId }); -} - -function commit(next: ThreadSnapshot | null) { - if (!next) return null; - thread = next; - reactToThread(); - return next; -} - -/** The tail of playback reaches the microphone after the audio element ends. */ -function guardThenListen() { - // Dictation ran right through playback: there is no shut mic to hold closed. - if (micOpen) { - void listen(); - return; - } - if (guardTimer) clearTimeout(guardTimer); - guardTimer = setTimeout(() => { - guardTimer = null; - void listen(); - }, ECHO_GUARD_MS); -} - -async function listen() { - if (!state) return; - // The caller said goodbye: every path back to listening hangs up instead. - if (hangUpAfterReply) { - endCall(); - return; - } - // A reply still playing owns the audio session; its idle event calls back here. - if (speaker.isSpeaking()) return; - // A guard is already counting down the quiet gap; it calls back here when it ends. - if (guardTimer) return; - set({ phase: "listening", heard: "" }); - speaker.stop(); - if (state.muted || pendingSecretAsk(thread)) { - dictation.stop("cancel"); - micOpen = false; - return; - } - await openMic(); -} - -/** Starts dictation unless it is already running, muted, or waiting on a typed secret. */ -async function openMic() { - if (!state || micOpen || state.muted || pendingSecretAsk(thread)) return; - micOpen = true; - try { - await dictation.listen({ - mode: "endpoint", - transcribe, - onFinal: (text) => void handleTranscript(text), - }); - } catch (error) { - micOpen = false; - set({ caption: errorText(error, t`Microphone failed`) }); - } -} - -async function handleTranscript(text: string) { - if (!state) return; - // Dictation stopped itself to deliver this final. - micOpen = false; - if (!text.trim()) { - void listen(); - return; - } - if (state.phase === "speaking") { - if (!isCallBargeIn(text)) { - set({ heard: "" }); - void openMic(); - return; - } - // The caller talked over the reply: cut the audio, and never resume that message. - bargedIn = true; - speaker.stop(); - set({ phase: "thinking", caption: "" }); - } - dictation.stop("submit"); - // The microphone caught the reply, not the caller: drop it and keep listening. - if (spokenMemory.isEcho(text)) { - set({ heard: "" }); - void listen(); - return; - } - if (pendingSecretAsk(thread)) { - set({ heard: "", caption: t`Hang up, then enter the code on screen.` }); - return; - } - const { botId, exchanges } = state; - const askId = latestAskId(thread); - const askMessage = thread?.messages.find((message) => message.id === askId); - // Captured now: a call started while this is in flight must not re-attach the new feed - // or commit this turn onto it. The same bot can be called again, so the bot id is not enough. - const callFeed = feed; - const turnCallId = callId; - const closing = isFarewell(text); - awaitingReply = true; - set({ heard: text, phase: "thinking", exchanges: [...exchanges, { role: "user", text }] }); - if (closing) { - hangUpAfterReply = true; - // A second goodbye replaces this timer. Clear the previous one or it can - // end the next call after this one has already hung up. - if (hangUpTimer) clearTimeout(hangUpTimer); - hangUpTimer = setTimeout(endCall, FAREWELL_TIMEOUT); - } - try { - if (askMessage) { - await rpc.threads.answer({ - botId, - runId: askMessage.runId ?? "", - messageId: askMessage.id, - answer: spokenDecision(text) ?? text, - }); - } else if (runActive(thread)) { - await rpc.threads.followUp({ botId, text, clientNonce: callClientNonce(turnCallId) }); - } else { - await rpc.threads.send({ botId, clientNonce: callClientNonce(turnCallId), text }); - } - if (!state || state.botId !== botId || callId !== turnCallId) return; - commit(await rpc.threads.get({ botId }, { signal: callFeed?.signal })); - } catch (error) { - if (!state || state.botId !== botId || callId !== turnCallId) return; - awaitingReply = false; - set({ caption: errorText(error, t`Could not send that`) }); - void listen(); - } -} - -/** - * Interim results are the only signal that arrives while the caller is still talking. - * A qualifying phrase that stands for INTERIM_BARGE_IN_MS stops the audio at once; the - * dictation session keeps running, so its silence window finishes the utterance and - * handleTranscript sends it as the next turn. - */ -function watchInterim(text: string) { - if (state?.phase !== "speaking") return; - if (!isInterimCallBargeIn(text)) { - clearInterim(); - return; - } - if (interimTimer) return; - interimTimer = setTimeout(() => { - interimTimer = null; - if (state?.phase !== "speaking") return; - // Never resume the cut-off message, and keep the idle it emits from reopening the mic. - bargedIn = true; - speaker.stop(); - set({ phase: "listening", caption: "" }); - }, INTERIM_BARGE_IN_MS); -} - -function clearInterim() { - if (interimTimer) clearTimeout(interimTimer); - interimTimer = null; -} - -/** - * Speak whatever the call's bot said last. A call never speaks tool activity: the - * card's phase indicator is the only feedback, so nothing talks over the caller. - */ -function reactToThread() { - if (!state) return; - // The bot already said goodbye: neither its marker nor the work it files after it is spoken. - if (botEndedCall) return; - if (pendingSecretAsk(thread)) { - dictation.stop("cancel"); - micOpen = false; - set({ heard: "" }); - } - // A turn sent back to listening mid-flight must not drop the reply it is waiting for. - if (state.phase === "listening" && !awaitingReply) return; - const { botId } = state; - const messages = thread?.messages ?? []; - const lastBot = [...messages].reverse().find((message) => message.role === "bot"); - if (lastBot && !spokenMessageIds.has(lastBot.id) && replyFinished(lastBot)) { - const text = speechFromBlocks(lastBot.blocks); - const ask = lastBot.blocks.find((block) => block.kind === "ask" && block.status !== "answered"); - const secretAsk = ask && isSecretAskBlock(ask); - if (text) { - // Never spoken again, interrupted or not. - spokenMessageIds.add(lastBot.id); - awaitingReply = false; - set({ exchanges: [...state.exchanges, { role: "bot", text }], heard: "" }); - spokenMemory.remember(text); - void speaker.speak( - secretAsk - ? `${text}. ${t`Hang up first, then enter the code on screen.`}` - : ask - ? `${text}. ${t`Say yes or no, or answer in a sentence.`}` - : text, - { botId, messageId: lastBot.id }, - ); - return; - } - if (!runActive(thread)) { - spokenMessageIds.add(lastBot.id); - awaitingReply = false; - void listen(); - } - } -} - -/** - * A reply is only whole once its own run stopped. Speaking a message the run is - * still streaming clips it, and later updates of the same id never get a turn. - */ -function replyFinished(message: ThreadMessage) { - const run = thread?.run; - if (!run) return true; - if (message.runId && message.runId !== run.id) return true; - return !RUN_ACTIVE.includes(run.status); -} - -function runActive(snapshot: ThreadSnapshot | null) { - return Boolean(snapshot?.run && RUN_ACTIVE.includes(snapshot.run.status)); -} - -function pendingSecretAsk(snapshot: ThreadSnapshot | null) { - const askId = latestAskId(snapshot); - const askMessage = snapshot?.messages.find((message) => message.id === askId); - return Boolean( - askMessage?.blocks.some( - (block) => block.kind === "ask" && isSecretAskBlock(block) && block.status !== "answered", - ), - ); -} - -function latestAskId(snapshot: ThreadSnapshot | null): string | null { - if (snapshot?.run?.status !== "waiting_input") return null; - for (let index = snapshot.messages.length - 1; index >= 0; index -= 1) { - const message = snapshot.messages[index]; - if (message?.runId !== snapshot.run.id) continue; - if (message.blocks.some((block) => block.kind === "ask" && block.status !== "answered")) { - return message.id; - } - } - return null; -} - -function errorText(error: unknown, fallback: string) { - return error instanceof Error ? error.message : fallback; -} - -function randomId(): string { - const webCrypto = globalThis.crypto; - return typeof webCrypto?.randomUUID === "function" - ? webCrypto.randomUUID() - : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; -} diff --git a/apps/web/src/lib/dictation.test.ts b/apps/web/src/lib/dictation.test.ts deleted file mode 100644 index 37b20fbd..00000000 --- a/apps/web/src/lib/dictation.test.ts +++ /dev/null @@ -1,1296 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { - combineTranscript, - Dictation, - MAX_TRANSCRIPTION_RESPONSE_BYTES, - TRANSCRIPTION_RESPONSE_TIMEOUT_MS, - webSpeechAvailable, - webSpeechNeedsServerFallback, -} from "./dictation.js"; - -afterEach(() => { - vi.unstubAllGlobals(); - vi.restoreAllMocks(); - vi.useRealTimers(); -}); - -function stubRecorderFallback(fetchMock: ReturnType) { - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - }, - ); -} - -describe("Dictation recorder fallback", () => { - it("stops tracks if hold-to-talk is cancelled while the mic prompt is open", async () => { - const track = { stop: vi.fn() }; - let grant!: (stream: { getTracks: () => Array<{ stop: () => void }> }) => void; - const pending = new Promise<{ getTracks: () => Array<{ stop: () => void }> }>((resolve) => { - grant = resolve; - }); - vi.stubGlobal("navigator", { - mediaDevices: { getUserMedia: vi.fn(() => pending) }, - language: "en-US", - }); - const started = vi.fn(); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - start() { - started(); - this.state = "recording"; - } - stop() { - this.state = "inactive"; - } - }, - ); - - const dictation = new Dictation(); - const listening = dictation.listen({ - mode: "hold", - transcribe: true, - onFinal: () => undefined, - }); - dictation.stop("cancel"); - grant({ getTracks: () => [track] }); - await listening; - - expect(track.stop).toHaveBeenCalledOnce(); - expect(started).not.toHaveBeenCalled(); - expect(dictation.state.status).toBe("idle"); - }); - - it("does not deliver a stale transcript to a newer session", async () => { - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - - let transcribe!: (body: { text: string }) => void; - const fetchMock = vi.fn( - (_url: string, init?: { signal?: AbortSignal }) => - new Promise((resolve, reject) => { - init?.signal?.addEventListener("abort", () => - reject(Object.assign(new Error("Aborted"), { name: "AbortError" })), - ); - transcribe = (body) => resolve(Response.json(body)); - }), - ); - vi.stubGlobal("fetch", fetchMock); - - class FakeRecorder { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - } - vi.stubGlobal("MediaRecorder", FakeRecorder); - - const first = vi.fn(); - const second = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal: first }); - dictation.submitHold(); - await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce()); - - await dictation.listen({ mode: "hold", transcribe: true, onFinal: second }); - transcribe({ text: "stale take" }); - await Promise.resolve(); - await Promise.resolve(); - - expect(first).not.toHaveBeenCalled(); - expect(second).not.toHaveBeenCalled(); - expect(dictation.state.status).toBe("listening"); - }); - - it("keeps line breaks in a server transcript with no speech prefix", async () => { - const fetchMock = vi.fn(async () => Response.json({ text: " line one\n\nline two " })); - stubRecorderFallback(fetchMock); - const onFinal = vi.fn(); - const dictation = new Dictation(); - - await dictation.listen({ mode: "hold", transcribe: true, onFinal }); - dictation.submitHold(); - - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("line one\n\nline two")); - }); - - it("keeps transcription in the space where recording started", async () => { - const store = new Map([["rakazo:space-id", "space-support"]]); - const localStorage = { - getItem: (key: string) => store.get(key) ?? null, - setItem: (key: string, value: string) => { - store.set(key, value); - }, - removeItem: (key: string) => { - store.delete(key); - }, - }; - vi.stubGlobal("window", { localStorage }); - vi.stubGlobal("localStorage", localStorage); - - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => - Response.json({ text: "hello" }), - ); - vi.stubGlobal("fetch", fetchMock); - - class FakeRecorder { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - } - vi.stubGlobal("MediaRecorder", FakeRecorder); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal }); - store.set("rakazo:space-id", "space-other"); - dictation.submitHold(); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("hello")); - - expect(fetchMock).toHaveBeenCalledWith( - "/api/voice/transcribe", - expect.objectContaining({ credentials: "include" }), - ); - const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers); - expect(headers.get("x-rakazo-space-id")).toBe("space-support"); - expect(headers.get("content-type")).toBe("application/json"); - }); - - it("rejects oversized transcription responses without waiting for cancellation", async () => { - const cancel = vi.fn(() => new Promise(() => undefined)); - const fetchMock = vi.fn( - async () => - new Response(new ReadableStream({ cancel }), { - headers: { "content-length": String(MAX_TRANSCRIPTION_RESPONSE_BYTES + 1) }, - }), - ); - stubRecorderFallback(fetchMock); - const dictation = new Dictation(); - - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - dictation.submitHold(); - - await vi.waitFor(() => - expect(dictation.state.error).toBe("Transcription response is too large."), - ); - expect(cancel).toHaveBeenCalledOnce(); - }); - - it("times out while a transcription response body is stalled", async () => { - vi.useFakeTimers(); - const fetchMock = vi.fn( - async () => - new Response( - new ReadableStream({ - pull: () => new Promise(() => undefined), - }), - ), - ); - stubRecorderFallback(fetchMock); - const dictation = new Dictation(); - - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - dictation.submitHold(); - await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce()); - await vi.advanceTimersByTimeAsync(TRANSCRIPTION_RESPONSE_TIMEOUT_MS); - - expect(dictation.state.error).toBe("Transcription request timed out."); - }); - - it("surfaces timeout when fetch rejects with AbortError", async () => { - // Browsers reject aborted fetch with DOMException AbortError. Matching token - // means the deadline fired (stop() bumps token first), so this must not stay - // stuck on "transcribing". - const fetchMock = vi.fn(async () => { - throw new DOMException("The operation was aborted.", "AbortError"); - }); - stubRecorderFallback(fetchMock); - const dictation = new Dictation(); - - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - dictation.submitHold(); - - await vi.waitFor(() => expect(dictation.state.error).toBe("Transcription request timed out.")); - expect(dictation.state.status).toBe("idle"); - }); - - it("stays silent when stop cancels an in-flight transcription", async () => { - const fetchMock = vi.fn( - (_url: string, init?: { signal?: AbortSignal }) => - new Promise((_resolve, reject) => { - init?.signal?.addEventListener( - "abort", - () => { - reject(new DOMException("The operation was aborted.", "AbortError")); - }, - { once: true }, - ); - }), - ); - stubRecorderFallback(fetchMock); - const dictation = new Dictation(); - - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - dictation.submitHold(); - await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce()); - expect(dictation.state.status).toBe("transcribing"); - - dictation.stop("cancel"); - await Promise.resolve(); - await Promise.resolve(); - - expect(dictation.state.status).toBe("idle"); - expect(dictation.state.error).toBeUndefined(); - }); - - it("ignores leftover audio from a replaced recorder", async () => { - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const fetchMock = vi.fn(async (_url: string, _init?: { body?: string }) => - Response.json({ text: "ok" }), - ); - vi.stubGlobal("fetch", fetchMock); - - const recorders: Array<{ - ondataavailable: ((event: { data: Blob }) => void) | null; - onstop: (() => void) | null; - stop: () => void; - }> = []; - class FakeRecorder { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - constructor() { - recorders.push(this); - } - start() { - this.state = "recording"; - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["new"], { type: "audio/webm" }) }); - this.onstop?.(); - } - } - vi.stubGlobal("MediaRecorder", FakeRecorder); - - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - recorders[0]?.ondataavailable?.({ - data: new Blob(["STALE-AUDIO-DATA"], { type: "audio/webm" }), - }); - dictation.submitHold(); - await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce()); - const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body ?? "")) as { - audioBase64: string; - }; - const decoded = atob(body.audioBase64); - expect(decoded).toContain("new"); - expect(decoded).not.toContain("STALE"); - }); - - it("returns to idle when the recorder cannot start", async () => { - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - vi.stubGlobal( - "MediaRecorder", - class { - start() { - throw new Error("recorder unavailable"); - } - }, - ); - - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - - expect(dictation.state.status).toBe("idle"); - expect(dictation.state.error).toBe("recorder unavailable"); - expect(track.stop).toHaveBeenCalledOnce(); - }); - - it("fails visibly when endpoint dictation has no silence detector", async () => { - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const started = vi.fn(); - vi.stubGlobal( - "MediaRecorder", - class { - start() { - started(); - } - }, - ); - - const dictation = new Dictation(); - await dictation.listen({ - mode: "endpoint", - transcribe: true, - onFinal: () => undefined, - }); - expect(started).not.toHaveBeenCalled(); - expect(track.stop).toHaveBeenCalledOnce(); - expect(dictation.state.error).toMatch(/stop talking/i); - }); - - it("stops an endpoint recording after silence", async () => { - vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); - const level = { current: 0.6 }; - class FakeAnalyser { - fftSize = 2048; - getByteTimeDomainData(data: Uint8Array) { - data.fill(Math.round(128 + level.current * 127)); - } - } - class FakeContext { - state = "running"; - createMediaStreamSource() { - return { connect() {} }; - } - createAnalyser() { - return new FakeAnalyser(); - } - close() { - return Promise.resolve(); - } - resume() { - return Promise.resolve(); - } - } - vi.stubGlobal("AudioContext", FakeContext); - - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const fetchMock = vi.fn(async () => Response.json({ text: "hello" })); - vi.stubGlobal("fetch", fetchMock); - - const onFinal = vi.fn(); - class FakeRecorder { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - } - vi.stubGlobal("MediaRecorder", FakeRecorder); - - const dictation = new Dictation(); - await dictation.listen({ - mode: "endpoint", - transcribe: true, - endpointMs: 240, - onFinal, - }); - expect(dictation.state.status).toBe("listening"); - await vi.advanceTimersByTimeAsync(80); - level.current = 0; - await vi.advanceTimersByTimeAsync(240); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("hello")); - vi.useRealTimers(); - }); - - it("does not let a replaced recorder tear down the new silence detector", async () => { - vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); - const level = { current: 0.6 }; - class FakeAnalyser { - fftSize = 2048; - getByteTimeDomainData(data: Uint8Array) { - data.fill(Math.round(128 + level.current * 127)); - } - } - class FakeContext { - state = "running"; - createMediaStreamSource() { - return { connect() {} }; - } - createAnalyser() { - return new FakeAnalyser(); - } - close() { - return Promise.resolve(); - } - resume() { - return Promise.resolve(); - } - } - vi.stubGlobal("AudioContext", FakeContext); - - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const fetchMock = vi.fn(async () => Response.json({ text: "later" })); - vi.stubGlobal("fetch", fetchMock); - - const recorders: Array<{ - onstop: (() => void) | null; - stop: () => void; - }> = []; - class FakeRecorder { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - constructor() { - recorders.push(this); - } - start() { - this.state = "recording"; - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - } - vi.stubGlobal("MediaRecorder", FakeRecorder); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ - mode: "endpoint", - transcribe: true, - endpointMs: 240, - onFinal, - }); - const staleStop = recorders[0]?.onstop; - await dictation.listen({ - mode: "endpoint", - transcribe: true, - endpointMs: 240, - onFinal, - }); - staleStop?.(); - await vi.advanceTimersByTimeAsync(80); - level.current = 0; - await vi.advanceTimersByTimeAsync(240); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("later")); - vi.useRealTimers(); - }); -}); - -describe("combineTranscript", () => { - it("joins a short prefix that is not a whole word in the server text", () => { - expect(combineTranscript("we", "welcome")).toBe("we welcome"); - }); - - it("does not repeat a word when the server transcript adds a comma", () => { - expect(combineTranscript("hello", "hello, world")).toBe("hello, world"); - expect(combineTranscript("hello", "Hello, world")).toBe("Hello, world"); - }); - - it.each([ - ["hello."], - ["hello!"], - ["hello?"], - ["hello; world"], - ["hello: world"], - ["hello's world"], - ["hello-world"], - ["hello)"], - ['hello"'], - ["hello,world"], - ])("treats punctuation after the retained word as a boundary (%s)", (serverText) => { - expect(combineTranscript("hello", serverText)).toBe(serverText); - }); - - it("keeps the server transcript when whitespace follows the retained words", () => { - expect(combineTranscript("call me later", "Call me later and goodbye")).toBe( - "Call me later and goodbye", - ); - }); - - it("still joins when the server text continues the retained token", () => { - expect(combineTranscript("hello", "helloworld")).toBe("hello helloworld"); - expect(combineTranscript("hello", "hello2")).toBe("hello hello2"); - expect(combineTranscript("hello", "hello_world")).toBe("hello hello_world"); - expect(combineTranscript("na", "naïve")).toBe("na naïve"); - expect(combineTranscript("a", "a𐐀")).toBe("a a𐐀"); - expect(combineTranscript("a𐐀", "a𐐀 more")).toBe("a𐐀 more"); - }); -}); - -describe("dictation engine choice", () => { - it("uses Web Speech when the browser implements it", () => { - vi.stubGlobal("window", { SpeechRecognition: class {} }); - expect(webSpeechAvailable()).toBe(true); - }); - - it("treats Electron as having no usable Web Speech", () => { - vi.stubGlobal("window", { - webkitSpeechRecognition: class {}, - rakazoDesktop: { platform: "darwin" }, - }); - expect(webSpeechAvailable()).toBe(false); - }); - - it("treats an Electron user agent as having no usable Web Speech", () => { - vi.stubGlobal("window", { webkitSpeechRecognition: class {} }); - vi.stubGlobal("navigator", { userAgent: "Mozilla/5.0 Electron/44.2.0" }); - expect(webSpeechAvailable()).toBe(false); - }); - - it("falls back only for service failures when transcription is connected", () => { - expect(webSpeechNeedsServerFallback("network", true)).toBe(true); - expect(webSpeechNeedsServerFallback("service-not-allowed", true)).toBe(true); - expect(webSpeechNeedsServerFallback("network", false)).toBe(false); - expect(webSpeechNeedsServerFallback("not-allowed", true)).toBe(false); - expect(webSpeechNeedsServerFallback("aborted", true)).toBe(false); - expect(webSpeechNeedsServerFallback(undefined, true)).toBe(false); - }); -}); - -describe("Dictation web speech", () => { - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: unknown) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - let instances: FakeRecognition[] = []; - - beforeEach(() => { - instances = []; - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - vi.stubGlobal("navigator", { language: "en-US" }); - }); - - type Part = string | { transcript: string; isFinal: true }; - - /** One onresult carrying the whole session so far, the way Chrome reports it. */ - function said(rec: FakeRecognition | undefined, ...parts: Part[]) { - rec?.onresult?.({ - resultIndex: 0, - results: parts.map((part) => { - const { transcript, isFinal } = - typeof part === "string" ? { transcript: part, isFinal: false } : part; - return Object.assign([{ transcript }], { isFinal }); - }), - }); - } - - /** Chrome flips a result to final at its own phrase boundary, mid-sentence. */ - function done(transcript: string): Part { - return { transcript, isFinal: true }; - } - - it("rides out a pause in the middle of a sentence", async () => { - vi.useFakeTimers(); - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "endpoint", onFinal }); - const rec = instances[0]; - expect(rec?.continuous).toBe(true); - expect(rec?.interimResults).toBe(true); - - said(rec, "okay it is based on"); - await vi.advanceTimersByTimeAsync(1_100); - expect(onFinal).not.toHaveBeenCalled(); - - said(rec, "okay it is based on", " the new project"); - await vi.advanceTimersByTimeAsync(1_100); - expect(onFinal).not.toHaveBeenCalled(); - - await vi.advanceTimersByTimeAsync(200); - expect(onFinal).toHaveBeenCalledTimes(1); - expect(onFinal).toHaveBeenCalledWith("okay it is based on the new project"); - }); - - it("keeps the window open when Chrome finalises words it already reported", async () => { - vi.useFakeTimers(); - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "endpoint", onFinal }); - const rec = instances[0]; - - said(rec, "okay tell me"); - await vi.advanceTimersByTimeAsync(400); - // Chrome's phrase boundary: the same words again, this time final. The caller only - // took a breath, so the quiet gap starts here, not at the first guess at the phrase. - said(rec, done("okay tell me")); - await vi.advanceTimersByTimeAsync(900); - expect(onFinal).not.toHaveBeenCalled(); - - said(rec, done("okay tell me"), " about the projects"); - await vi.advanceTimersByTimeAsync(1_100); - expect(onFinal).not.toHaveBeenCalled(); - - await vi.advanceTimersByTimeAsync(200); - expect(onFinal).toHaveBeenCalledTimes(1); - expect(onFinal).toHaveBeenCalledWith("okay tell me about the projects"); - }); - - it("never ends the turn because the browser ended the session", async () => { - vi.useFakeTimers(); - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "endpoint", onFinal }); - const rec = instances[0]; - - said(rec, "one of the new projects"); - rec?.onend?.(); - expect(onFinal).not.toHaveBeenCalled(); - expect(rec?.start).toHaveBeenCalledTimes(2); - - // The restarted session numbers its results from zero; the earlier words survive. - said(rec, "and the deadlines"); - await vi.advanceTimersByTimeAsync(1_200); - expect(onFinal).toHaveBeenCalledTimes(1); - expect(onFinal).toHaveBeenCalledWith("one of the new projects and the deadlines"); - }); - - it("publishes interim words to watchers long before the turn ends", async () => { - vi.useFakeTimers(); - const onFinal = vi.fn(); - const dictation = new Dictation(); - const seen: string[] = []; - dictation.subscribe((snapshot) => seen.push(snapshot.transcript)); - await dictation.listen({ mode: "endpoint", onFinal }); - - said(instances[0], "what about the deploy"); - await vi.advanceTimersByTimeAsync(300); - - // The only signal available while the caller is still talking. - expect(seen.at(-1)).toBe("what about the deploy"); - expect(onFinal).not.toHaveBeenCalled(); - }); - - it("restarts endpoint recognition after a quiet end", async () => { - const dictation = new Dictation(); - await dictation.listen({ mode: "endpoint", onFinal: () => undefined }); - const rec = instances[0]; - expect(rec?.start).toHaveBeenCalledOnce(); - rec?.onend?.(); - expect(rec?.start).toHaveBeenCalledTimes(2); - expect(dictation.state.status).toBe("listening"); - }); - - it("records through the connected voice provider in Electron", async () => { - const constructed = vi.fn(); - class FakeRecognition { - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - constructed(); - } - } - vi.stubGlobal("window", { - webkitSpeechRecognition: FakeRecognition, - rakazoDesktop: { platform: "darwin" }, - }); - const fetchMock = vi.fn(async () => Response.json({ text: "from fish" })); - stubRecorderFallback(fetchMock); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal }); - expect(constructed).not.toHaveBeenCalled(); - expect(dictation.state.error).toBeUndefined(); - expect(dictation.state.status).toBe("listening"); - dictation.submitHold(); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("from fish")); - expect(fetchMock).toHaveBeenCalledWith( - "/api/voice/transcribe", - expect.objectContaining({ method: "POST" }), - ); - }); - - it.each(["network", "service-not-allowed"])( - "falls back to server transcription when Web Speech fails with %s", - async (error) => { - const instances: Array<{ - onerror: ((event: { error?: string }) => void) | null; - onend: (() => void) | null; - start: ReturnType; - abort: ReturnType; - }> = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: unknown) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(() => { - this.onerror?.({ error: "aborted" }); - this.onend?.(); - }); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - const fetchMock = vi.fn(async () => Response.json({ text: "from server" })); - let markRecording: () => void = () => undefined; - const recording = new Promise((resolve) => { - markRecording = resolve; - }); - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - markRecording(); - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - }, - ); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal }); - const rec = instances[0]; - expect(rec?.start).toHaveBeenCalledOnce(); - const onend = rec?.onend; - rec?.onerror?.({ error }); - onend?.(); - await recording; - expect(dictation.state.error).toBeUndefined(); - expect(dictation.state.status).toBe("listening"); - expect(rec?.abort).toHaveBeenCalledOnce(); - dictation.submitHold(); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("from server")); - expect(onFinal).toHaveBeenCalledOnce(); - }, - ); - - it("continues an endpoint turn and joins speech heard before Web Speech failed", async () => { - vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); - const level = { current: 0.6 }; - class FakeAnalyser { - fftSize = 2048; - getByteTimeDomainData(data: Uint8Array) { - data.fill(Math.round(128 + level.current * 127)); - } - } - class FakeContext { - state = "running"; - createMediaStreamSource() { - return { connect() {} }; - } - createAnalyser() { - return new FakeAnalyser(); - } - close() { - return Promise.resolve(); - } - resume() { - return Promise.resolve(); - } - } - vi.stubGlobal("AudioContext", FakeContext); - - type ResultEvent = { - resultIndex: number; - results: ArrayLike>; - }; - const instances: FakeRecognition[] = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: ResultEvent) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - let markRecording: () => void = () => undefined; - const recording = new Promise((resolve) => { - markRecording = resolve; - }); - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const fetchMock = vi.fn(async () => Response.json({ text: " from server " })); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - markRecording(); - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - }, - ); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ - mode: "endpoint", - transcribe: true, - endpointMs: 240, - onFinal, - }); - const rec = instances[0]; - const onend = rec?.onend; - rec?.onresult?.({ - resultIndex: 0, - results: [[{ transcript: "call me later" }]], - }); - rec?.onerror?.({ error: "network" }); - onend?.(); - await recording; - - expect(onFinal).not.toHaveBeenCalled(); - expect(dictation.state.status).toBe("listening"); - expect(dictation.state.transcript).toBe("call me later"); - expect(dictation.state.error).toBeUndefined(); - expect(rec?.abort).toHaveBeenCalledOnce(); - await vi.advanceTimersByTimeAsync(80); - level.current = 0; - await vi.advanceTimersByTimeAsync(240); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("call me later from server")); - expect(onFinal).toHaveBeenCalledOnce(); - expect(fetchMock).toHaveBeenCalledOnce(); - }); - - it("submits retained speech when the microphone fails after fallback", async () => { - type ResultEvent = { - resultIndex: number; - results: ArrayLike>; - }; - const instances: FakeRecognition[] = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: ResultEvent) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => { - throw new Error("Microphone denied"); - }), - }, - language: "en-US", - }); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "endpoint", transcribe: true, onFinal }); - const rec = instances[0]; - rec?.onresult?.({ - resultIndex: 0, - results: [[{ transcript: "call me later" }]], - }); - rec?.onerror?.({ error: "service-not-allowed" }); - - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("call me later")); - expect(onFinal).toHaveBeenCalledOnce(); - expect(dictation.state.status).toBe("idle"); - expect(dictation.state.error).toBeUndefined(); - }); - - it("submits retained speech when transcription fails after fallback", async () => { - type ResultEvent = { - resultIndex: number; - results: ArrayLike>; - }; - const instances: FakeRecognition[] = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: ResultEvent) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - let markRecording: () => void = () => undefined; - const recording = new Promise((resolve) => { - markRecording = resolve; - }); - const fetchMock = vi.fn(async () => Response.json({ error: "unavailable" }, { status: 503 })); - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - markRecording(); - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - }, - ); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal }); - const rec = instances[0]; - rec?.onresult?.({ - resultIndex: 0, - results: [[{ transcript: "call me later" }]], - }); - rec?.onerror?.({ error: "network" }); - await recording; - expect(onFinal).not.toHaveBeenCalled(); - dictation.submitHold(); - - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("call me later")); - expect(onFinal).toHaveBeenCalledOnce(); - expect(dictation.state.status).toBe("idle"); - expect(dictation.state.error).toBeUndefined(); - expect(fetchMock).toHaveBeenCalledOnce(); - }); - - it("does not repeat server text that already starts with the retained speech", async () => { - type ResultEvent = { - resultIndex: number; - results: ArrayLike>; - }; - const instances: FakeRecognition[] = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: ResultEvent) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - let markRecording: () => void = () => undefined; - const recording = new Promise((resolve) => { - markRecording = resolve; - }); - const fetchMock = vi.fn(async () => Response.json({ text: " Call me later and goodbye " })); - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - markRecording(); - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - }, - ); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal }); - instances[0]?.onresult?.({ - resultIndex: 0, - results: [[{ transcript: "call me later" }]], - }); - instances[0]?.onerror?.({ error: "network" }); - await recording; - dictation.submitHold(); - - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("Call me later and goodbye")); - expect(onFinal).toHaveBeenCalledOnce(); - }); - - it("stops an endpoint fallback on silence without new microphone energy", async () => { - vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); - class FakeAnalyser { - fftSize = 2048; - getByteTimeDomainData(data: Uint8Array) { - data.fill(128); - } - } - class FakeContext { - state = "running"; - createMediaStreamSource() { - return { connect() {} }; - } - createAnalyser() { - return new FakeAnalyser(); - } - close() { - return Promise.resolve(); - } - resume() { - return Promise.resolve(); - } - } - vi.stubGlobal("AudioContext", FakeContext); - - type ResultEvent = { - resultIndex: number; - results: ArrayLike>; - }; - const instances: FakeRecognition[] = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: ResultEvent) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - let markRecording: () => void = () => undefined; - const recording = new Promise((resolve) => { - markRecording = resolve; - }); - const track = { stop: vi.fn() }; - vi.stubGlobal("navigator", { - mediaDevices: { - getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })), - }, - language: "en-US", - }); - const fetchMock = vi.fn(async () => Response.json({ text: "still there" })); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "MediaRecorder", - class { - state = "inactive"; - ondataavailable: ((event: { data: Blob }) => void) | null = null; - onstop: (() => void) | null = null; - start() { - this.state = "recording"; - markRecording(); - } - stop() { - this.state = "inactive"; - this.ondataavailable?.({ data: new Blob(["audio"], { type: "audio/webm" }) }); - this.onstop?.(); - } - }, - ); - - const onFinal = vi.fn(); - const dictation = new Dictation(); - await dictation.listen({ - mode: "endpoint", - transcribe: true, - endpointMs: 240, - onFinal, - }); - instances[0]?.onresult?.({ - resultIndex: 0, - results: [[{ transcript: "call me later" }]], - }); - instances[0]?.onerror?.({ error: "network" }); - await recording; - - expect(onFinal).not.toHaveBeenCalled(); - expect(dictation.state.transcript).toBe("call me later"); - await vi.advanceTimersByTimeAsync(80); - expect(onFinal).not.toHaveBeenCalled(); - await vi.advanceTimersByTimeAsync(160); - await vi.waitFor(() => expect(onFinal).toHaveBeenCalledWith("call me later still there")); - expect(onFinal).toHaveBeenCalledOnce(); - expect(fetchMock).toHaveBeenCalledOnce(); - }); - - it("keeps a Web Speech permission error when no server fallback applies", async () => { - const instances: Array<{ - onerror: ((event: { error?: string }) => void) | null; - }> = []; - class FakeRecognition { - continuous = false; - interimResults = false; - lang = ""; - onresult: ((event: unknown) => void) | null = null; - onerror: ((event: { error?: string }) => void) | null = null; - onend: (() => void) | null = null; - start = vi.fn(); - stop = vi.fn(); - abort = vi.fn(); - constructor() { - instances.push(this); - } - } - vi.stubGlobal("window", { SpeechRecognition: FakeRecognition }); - vi.stubGlobal("navigator", { language: "en-US" }); - const started = vi.fn(); - vi.stubGlobal( - "MediaRecorder", - class { - start() { - started(); - } - }, - ); - - const dictation = new Dictation(); - await dictation.listen({ mode: "hold", transcribe: true, onFinal: () => undefined }); - instances[0]?.onerror?.({ error: "not-allowed" }); - expect(dictation.state.error).toBe("Dictation failed: not-allowed"); - expect(started).not.toHaveBeenCalled(); - - const offline = new Dictation(); - await offline.listen({ mode: "hold", onFinal: () => undefined }); - instances[1]?.onerror?.({ error: "network" }); - expect(offline.state.error).toBe("Dictation failed: network"); - expect(started).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/web/src/lib/dictation.ts b/apps/web/src/lib/dictation.ts deleted file mode 100644 index d994802f..00000000 --- a/apps/web/src/lib/dictation.ts +++ /dev/null @@ -1,583 +0,0 @@ -import { readBoundedResponseBytes } from "@milo/core"; -import { selectedSpaceId, withSpaceHeaders } from "./rpc.js"; - -export type DictationMode = "hold" | "endpoint"; - -export type DictationSnapshot = { - status: "idle" | "listening" | "transcribing"; - transcript: string; - error?: string; -}; - -type SpeechRecognitionCtor = new () => SpeechRecognitionLike; - -interface SpeechRecognitionLike { - continuous: boolean; - interimResults: boolean; - lang: string; - onresult: ((event: { resultIndex: number; results: SpeechRecognitionResultList }) => void) | null; - onerror: ((event: { error?: string }) => void) | null; - onend: (() => void) | null; - start(): void; - stop(): void; - abort(): void; -} - -const IDLE: DictationSnapshot = { status: "idle", transcript: "" }; -/** - * Quiet gap that ends an utterance, measured on the page. Chrome's own end-of-speech - * fires on any pause, which cuts a caller off mid-sentence; a natural breath is well - * under this, a finished turn is well over it. - */ -const ENDPOINT_SILENCE_MS = 1200; -const ENDPOINT_TICK_MS = 80; -const SILENCE_RMS = 0.035; -export const TRANSCRIPTION_RESPONSE_TIMEOUT_MS = 70_000; -export const MAX_TRANSCRIPTION_RESPONSE_BYTES = 64 * 1024; -const ENDPOINT_UNSUPPORTED = - "This browser can't detect when you stop talking. Use Chrome, the desktop app, or hold-to-talk in the composer."; -/** Web Speech codes that mean the cloud recognizer cannot be used. */ -const WEB_SPEECH_SERVICE_ERRORS = new Set(["network", "service-not-allowed"]); - -export function webSpeechAvailable(): boolean { - return Boolean(speechRecognitionCtor()) && !electronSpeechHost(); -} - -/** - * Electron exposes webkitSpeechRecognition without a speech-service key, so - * recognition fails with `network`. Don't treat that API as available there. - */ -function electronSpeechHost(): boolean { - if (typeof window !== "undefined") { - const host = window as Window & { rakazoDesktop?: unknown }; - if (host.rakazoDesktop) return true; - } - if (typeof navigator === "undefined") return false; - const agent = navigator.userAgent; - return typeof agent === "string" && agent.includes("Electron"); -} - -/** Connected server transcription should take over after Web Speech cannot run. */ -export function webSpeechNeedsServerFallback( - error: string | undefined, - transcribe: boolean, -): boolean { - return transcribe && typeof error === "string" && WEB_SPEECH_SERVICE_ERRORS.has(error); -} - -function normalizedTranscript(text: string): string { - return text.trim().replace(/\s+/g, " "); -} - -function startsWithWholePrefix(serverText: string, prefix: string): boolean { - const head = prefix.toLowerCase(); - const tail = serverText.toLowerCase(); - if (!tail.startsWith(head)) return false; - // Index by code point. A supplementary-plane letter is two UTF-16 units, and - // the first half alone is not a letter. - const point = tail.codePointAt(head.length); - if (point === undefined) return true; - // Punctuation ends the retained word. Letters, numbers, and "_" continue it. - return !/[\p{L}\p{N}_]/u.test(String.fromCodePoint(point)); -} - -export function combineTranscript(prefix: string, serverText: string): string { - const head = normalizedTranscript(prefix); - const tail = serverText.trim(); - if (!head) return tail; - if (!tail) return head; - if (startsWithWholePrefix(tail, head)) return tail; - return `${head} ${normalizedTranscript(tail)}`; -} - -function speechRecognitionCtor(): SpeechRecognitionCtor | undefined { - if (typeof window === "undefined") return undefined; - const host = window as Window & { - SpeechRecognition?: SpeechRecognitionCtor; - webkitSpeechRecognition?: SpeechRecognitionCtor; - }; - return host.SpeechRecognition ?? host.webkitSpeechRecognition; -} - -function audioContextCtor(): (new () => AudioContext) | undefined { - if (typeof AudioContext === "function") return AudioContext; - if (typeof window === "undefined") return undefined; - const host = window as Window & { webkitAudioContext?: typeof AudioContext }; - return host.webkitAudioContext; -} - -export class Dictation { - private snapshot: DictationSnapshot = IDLE; - private watchers = new Set<(s: DictationSnapshot) => void>(); - private recognition: SpeechRecognitionLike | null = null; - private media: MediaRecorder | null = null; - private chunks: Blob[] = []; - private token = 0; - private silenceTimer: ReturnType | undefined; - private transcribeAbort: AbortController | null = null; - private audioContext: AudioContext | null = null; - private vadTimer: ReturnType | undefined; - private onFinal: ((text: string) => void) | null = null; - - subscribe(fn: (s: DictationSnapshot) => void): () => void { - this.watchers.add(fn); - fn(this.snapshot); - return () => { - this.watchers.delete(fn); - }; - } - - get state(): DictationSnapshot { - return this.snapshot; - } - - private set(next: DictationSnapshot) { - this.snapshot = next; - for (const watcher of [...this.watchers]) watcher(next); - } - - stop(reason: "submit" | "cancel" | "replace" = "cancel") { - this.token += 1; - this.transcribeAbort?.abort(); - this.transcribeAbort = null; - this.stopVad(); - clearTimeout(this.silenceTimer); - this.silenceTimer = undefined; - const rec = this.recognition; - this.recognition = null; - if (rec) { - rec.onresult = null; - rec.onerror = null; - rec.onend = null; - try { - if (reason === "submit") rec.stop(); - else rec.abort(); - } catch { - // already stopped - } - } - const media = this.media; - this.media = null; - if (media && media.state !== "inactive") { - try { - media.stop(); - } catch { - // already stopped - } - } - this.chunks = []; - this.onFinal = null; - if (this.snapshot.status !== "idle" || this.snapshot.error) this.set(IDLE); - } - - async listen(opts: { - mode: DictationMode; - transcribe?: boolean; - endpointMs?: number; - onFinal: (text: string) => void; - }): Promise { - this.stop("replace"); - const mine = this.token; - const spaceId = selectedSpaceId(); - this.onFinal = opts.onFinal; - this.set({ status: "listening", transcript: "" }); - const transcribe = Boolean(opts.transcribe); - if (webSpeechAvailable()) { - this.listenWebSpeech( - opts.mode, - opts.endpointMs ?? ENDPOINT_SILENCE_MS, - mine, - transcribe, - spaceId, - ); - return; - } - if (transcribe) { - await this.listenRecorder(mine, opts.mode, opts.endpointMs ?? ENDPOINT_SILENCE_MS, spaceId); - return; - } - this.set({ - ...IDLE, - error: - "This browser has no on-device dictation. Connect a voice provider with transcription, or use Chrome / the desktop app.", - }); - } - - private listenWebSpeech( - mode: DictationMode, - endpointMs: number, - mine: number, - transcribe: boolean, - spaceId: string | null, - ) { - const Ctor = speechRecognitionCtor(); - if (!Ctor) return; - const rec = new Ctor(); - let live = true; - rec.continuous = true; - rec.interimResults = true; - rec.lang = navigator.language || "en-US"; - // Chrome numbers results per session, so a restart starts over: keep the earlier text. - let carried = ""; - rec.onresult = (event) => { - if (!live || this.token !== mine) return; - let session = ""; - for (let i = 0; i < event.results.length; i += 1) { - session += event.results[i]?.[0]?.transcript ?? ""; - } - const transcript = `${carried} ${session}`.trim(); - this.set({ status: "listening", transcript }); - if (mode !== "endpoint") return; - // Every result means the caller was just heard, so the quiet gap is measured from - // here. That includes Chrome finalising a phrase it already reported: its phrase - // boundary is a breath, and the words repeat, so a window tied to new text alone - // expires before Chrome opens its first interim for the rest of the sentence. - if (!transcript) return; - clearTimeout(this.silenceTimer); - this.silenceTimer = setTimeout(() => { - if (!live || this.token !== mine) return; - this.finish(this.snapshot.transcript, mine); - }, endpointMs); - }; - rec.onerror = (event) => { - if (!live || this.token !== mine) return; - if (event.error === "aborted" || event.error === "no-speech") return; - if (webSpeechNeedsServerFallback(event.error, transcribe)) { - live = false; - this.fallbackToServer(rec, mine, mode, endpointMs, spaceId); - return; - } - live = false; - this.set({ - ...IDLE, - error: event.error ? `Dictation failed: ${event.error}` : "Dictation failed.", - }); - }; - rec.onend = () => { - if (!live || this.token !== mine) return; - if (this.snapshot.status !== "listening") return; - if (mode === "hold") { - this.finish(this.snapshot.transcript, mine); - return; - } - // Chrome ends the session on its own — after a pause, or its ~60s cap — and that - // says nothing about whether the caller finished. Only the silence window above - // ends an utterance; here we just pick the microphone back up. - carried = this.snapshot.transcript; - try { - rec.start(); - } catch { - this.set({ ...IDLE, error: "Dictation ended unexpectedly." }); - } - }; - this.recognition = rec; - try { - rec.start(); - } catch { - if (!live || this.token !== mine) return; - if (transcribe) { - live = false; - this.fallbackToServer(rec, mine, mode, endpointMs, spaceId); - return; - } - live = false; - this.releaseRecognition(rec); - this.set({ ...IDLE, error: "Dictation failed." }); - } - } - - private fallbackToServer( - rec: SpeechRecognitionLike, - mine: number, - mode: DictationMode, - endpointMs: number, - spaceId: string | null, - ) { - const recognized = normalizedTranscript(this.snapshot.transcript); - this.releaseRecognition(rec); - clearTimeout(this.silenceTimer); - this.silenceTimer = undefined; - if (this.token !== mine) return; - this.set({ status: "listening", transcript: recognized }); - void this.listenRecorder(mine, mode, endpointMs, spaceId); - } - - private releaseRecognition(rec: SpeechRecognitionLike) { - rec.onresult = null; - rec.onerror = null; - rec.onend = null; - if (this.recognition === rec) this.recognition = null; - try { - rec.abort(); - } catch { - // already stopped - } - } - - private async listenRecorder( - mine: number, - mode: DictationMode, - endpointMs: number, - spaceId: string | null, - ) { - let stream: MediaStream; - try { - stream = await navigator.mediaDevices.getUserMedia({ - audio: { echoCancellation: true, noiseSuppression: true }, - }); - } catch (error) { - this.failListening(mine, error instanceof Error ? error.message : "Microphone failed"); - return; - } - if (this.token !== mine) { - for (const track of stream.getTracks()) track.stop(); - return; - } - const keptSpeech = this.snapshot.transcript.trim().length > 0; - if (mode === "endpoint" && !this.armSilence(stream, mine, endpointMs, keptSpeech)) { - for (const track of stream.getTracks()) track.stop(); - this.failListening(mine, ENDPOINT_UNSUPPORTED); - return; - } - let media: MediaRecorder | undefined; - try { - media = new MediaRecorder(stream); - this.media = media; - this.chunks = []; - media.ondataavailable = (event) => { - if (this.token !== mine) return; - if (event.data.size) this.chunks.push(event.data); - }; - media.onstop = () => { - for (const track of stream.getTracks()) track.stop(); - if (this.token !== mine) return; - this.stopVad(); - void this.transcribeChunks(mine, spaceId); - }; - media.start(mode === "endpoint" ? 250 : undefined); - } catch (error) { - if (media) { - media.ondataavailable = null; - media.onstop = null; - } - for (const track of stream.getTracks()) track.stop(); - if (this.media === media) this.media = null; - if (this.token !== mine) return; - this.stopVad(); - this.failListening(mine, error instanceof Error ? error.message : "Dictation failed."); - } - } - - private armSilence( - stream: MediaStream, - mine: number, - endpointMs: number, - alreadyHeard = false, - ): boolean { - const Ctor = audioContextCtor(); - if (!Ctor) return false; - try { - const ctx = new Ctor(); - const source = ctx.createMediaStreamSource(stream); - const analyser = ctx.createAnalyser(); - analyser.fftSize = 2048; - source.connect(analyser); - this.audioContext = ctx; - if (ctx.state === "suspended") void ctx.resume(); - const data = new Uint8Array(analyser.fftSize); - let heardSpeech = alreadyHeard; - let silentFor = 0; - this.vadTimer = setInterval(() => { - const media = this.media; - if (this.token !== mine || !media || media.state === "inactive") return; - analyser.getByteTimeDomainData(data); - let sum = 0; - for (const sample of data) { - const n = (sample - 128) / 128; - sum += n * n; - } - const rms = Math.sqrt(sum / data.length); - if (rms > SILENCE_RMS) { - heardSpeech = true; - silentFor = 0; - return; - } - if (!heardSpeech) return; - silentFor += ENDPOINT_TICK_MS; - if (silentFor < endpointMs) return; - this.stopVad(); - try { - media.stop(); - } catch { - // already stopped - } - }, ENDPOINT_TICK_MS); - return true; - } catch { - this.stopVad(); - return false; - } - } - - private stopVad() { - clearInterval(this.vadTimer); - this.vadTimer = undefined; - const ctx = this.audioContext; - this.audioContext = null; - if (ctx) void ctx.close().catch(() => undefined); - } - - private async transcribeChunks(mine: number, spaceId: string | null) { - if (this.token !== mine) return; - const blob = new Blob(this.chunks, { type: this.chunks[0]?.type || "audio/webm" }); - this.chunks = []; - if (!blob.size) { - const prefix = normalizedTranscript(this.snapshot.transcript); - if (!prefix) { - this.set(IDLE); - return; - } - this.finish(prefix, mine); - return; - } - this.set({ status: "transcribing", transcript: this.snapshot.transcript }); - const abort = new AbortController(); - this.transcribeAbort = abort; - const timer = setTimeout( - () => abort.abort(new Error("Transcription request timed out.")), - TRANSCRIPTION_RESPONSE_TIMEOUT_MS, - ); - try { - const audioBase64 = await blobToBase64(blob); - if (this.token !== mine) return; - const res = await withAbort( - fetch("/api/voice/transcribe", { - method: "POST", - headers: withSpaceHeaders({ "content-type": "application/json" }, spaceId), - credentials: "include", - body: JSON.stringify({ audioBase64, mimeType: blob.type }), - signal: abort.signal, - }), - abort.signal, - ); - if (this.token !== mine) { - cancelResponse(res); - return; - } - const body = await readTranscriptionBody(res, abort.signal); - if (this.token !== mine) return; - if (!res.ok) { - this.failListening(mine, body.error ?? "Could not transcribe that recording."); - return; - } - this.finish(combineTranscript(this.snapshot.transcript, body.text ?? ""), mine); - } catch (error) { - // User cancel bumps token in stop() before aborting, so a matching token - // means the deadline timer fired. Browsers may reject fetch as AbortError - // instead of signal.reason; surface the timeout either way. - if (this.token !== mine) return; - const timedOut = - (abort.signal.reason instanceof Error && - abort.signal.reason.message === "Transcription request timed out.") || - (error instanceof Error && error.message === "Transcription request timed out."); - if (timedOut || (error instanceof Error && error.name === "AbortError")) { - this.failListening(mine, "Transcription request timed out."); - return; - } - this.failListening( - mine, - error instanceof Error ? error.message : "Could not transcribe that recording.", - ); - } finally { - clearTimeout(timer); - if (this.transcribeAbort === abort) this.transcribeAbort = null; - } - } - - submitHold() { - if (this.media && this.media.state !== "inactive") { - this.media.stop(); - return; - } - this.finish(this.snapshot.transcript, this.token); - } - - private failListening(mine: number, message: string) { - if (this.token !== mine) return; - const prefix = normalizedTranscript(this.snapshot.transcript); - if (prefix) { - this.finish(prefix, mine); - return; - } - this.set({ ...IDLE, error: message }); - } - - private finish(text: string, mine: number) { - if (this.token !== mine) return; - const trimmed = text.trim(); - const onFinal = this.onFinal; - this.stop("submit"); - if (trimmed) onFinal?.(trimmed); - } -} - -async function blobToBase64(blob: Blob): Promise { - const buffer = await blob.arrayBuffer(); - const bytes = new Uint8Array(buffer); - let binary = ""; - for (const byte of bytes) binary += String.fromCharCode(byte); - return btoa(binary); -} - -async function readTranscriptionBody( - response: Response, - signal: AbortSignal, -): Promise<{ text?: string; error?: string }> { - const declared = Number(response.headers.get("content-length") ?? 0); - if (Number.isFinite(declared) && declared > MAX_TRANSCRIPTION_RESPONSE_BYTES) { - cancelResponse(response); - throw new Error("Transcription response is too large."); - } - const bytes = await readBoundedResponseBytes(response, { - maxBytes: MAX_TRANSCRIPTION_RESPONSE_BYTES, - tooLargeMessage: "Transcription response is too large.", - read: (operation) => withAbort(operation(), signal), - }); - try { - const parsed = JSON.parse(new TextDecoder().decode(bytes)) as unknown; - return parsed && typeof parsed === "object" - ? (parsed as { text?: string; error?: string }) - : {}; - } catch { - return {}; - } -} - -function withAbort(promise: Promise, signal: AbortSignal): Promise { - if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Request aborted.")); - return new Promise((resolve, reject) => { - const onAbort = () => reject(signal.reason ?? new Error("Request aborted.")); - signal.addEventListener("abort", onAbort, { once: true }); - promise.then( - (value) => { - signal.removeEventListener("abort", onAbort); - resolve(value); - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - // Prefer abort reason over a bare AbortError from fetch/read. - reject(signal.aborted ? (signal.reason ?? error) : error); - }, - ); - }); -} - -function cancelResponse(response: Response): void { - try { - void Promise.resolve(response.body?.cancel()).catch(() => undefined); - } catch { - // Response cleanup is best-effort. - } -} - -export const dictation = new Dictation(); diff --git a/apps/web/src/lib/thread-events.test.ts b/apps/web/src/lib/thread-events.test.ts index 0a61e739..85d05c7d 100644 --- a/apps/web/src/lib/thread-events.test.ts +++ b/apps/web/src/lib/thread-events.test.ts @@ -1394,9 +1394,9 @@ describe("thread event reduction", () => { expect(next?.messages[0]?.blocks[0]).toMatchObject({ status: "answered", answer: "Paris" }); }); - it("titles the call marker in place when the wrap-up run names it", () => { + it("titles a historical voice_call marker in place when the wrap-up run names it", () => { const initial = snapshot([ - { ...message("marker-1", [{ kind: "voice_call", title: "", farewell: "" }]), callId: "c-1" }, + message("marker-1", [{ kind: "voice_call", title: "", farewell: "" }]), ]); const next = reduceThreadSnapshot( initial, @@ -1413,7 +1413,6 @@ describe("thread event reduction", () => { expect(next?.messages).toHaveLength(1); expect(next?.messages[0]?.blocks[0]).toMatchObject({ title: "Flight booked" }); - expect(next?.messages[0]?.callId).toBe("c-1"); }); it("preserves botId on durable bot messages", () => { diff --git a/apps/web/src/lib/thread-events.ts b/apps/web/src/lib/thread-events.ts index 21e0b7b8..932444c3 100644 --- a/apps/web/src/lib/thread-events.ts +++ b/apps/web/src/lib/thread-events.ts @@ -461,7 +461,6 @@ export function reduceThreadSnapshot( const role = (event.payload.role as ThreadMessage["role"]) ?? "bot"; const blocks = (event.payload.blocks as ThreadMessage["blocks"]) ?? []; const id = String(event.payload.messageId ?? event.id); - const known = prev.messages.find((message) => message.id === id); const next: ThreadMessage = { id, threadId: event.threadId, @@ -470,7 +469,6 @@ export function reduceThreadSnapshot( blocks, botId: event.botId, runId: event.runId, - callId: typeof event.payload.callId === "string" ? event.payload.callId : known?.callId, replyToMessageId: typeof event.payload.replyToMessageId === "string" ? event.payload.replyToMessageId diff --git a/apps/web/src/lib/tts.test.ts b/apps/web/src/lib/tts.test.ts deleted file mode 100644 index a9ca7fa3..00000000 --- a/apps/web/src/lib/tts.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { MAX_VOICE_AUDIO_BYTES, Speaker, VOICE_RESPONSE_TIMEOUT_MS } from "./tts.js"; - -afterEach(() => { - vi.useRealTimers(); - vi.unstubAllGlobals(); - vi.restoreAllMocks(); -}); - -function stubSelectedSpace(id: string) { - const store = new Map([["rakazo:space-id", id]]); - const localStorage = { - getItem: (key: string) => store.get(key) ?? null, - setItem: (key: string, value: string) => { - store.set(key, value); - }, - removeItem: (key: string) => { - store.delete(key); - }, - }; - vi.stubGlobal("window", { localStorage }); - vi.stubGlobal("localStorage", localStorage); - return (next: string) => store.set("rakazo:space-id", next); -} - -describe("Speaker", () => { - it("interrupting before audio arrives leaves the speaker idle", async () => { - const speaker = new Speaker(); - vi.spyOn( - speaker as unknown as { prepare: () => Promise }, - "prepare", - ).mockImplementation(() => new Promise(() => undefined)); - const pending = speaker.speak("Hello there.", { messageId: "m1" }); - speaker.stop(); - await pending; - expect(speaker.state.status).toBe("idle"); - }); - - it("resolves with an error snapshot instead of rejecting", async () => { - const speaker = new Speaker(); - vi.spyOn( - speaker as unknown as { prepare: () => Promise }, - "prepare", - ).mockRejectedValue(new Error("ElevenLabs rejected that key.")); - await expect(speaker.speak("Hi there.")).resolves.toBeUndefined(); - expect(speaker.state.error).toBe("ElevenLabs rejected that key."); - }); - - it("keeps speak requests in the space where playback started", async () => { - const changeSelectedSpace = stubSelectedSpace("space-support"); - const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => ({ - ok: true, - blob: async () => new Blob(["audio"]), - json: async () => ({}), - })); - vi.stubGlobal("fetch", fetchMock); - vi.stubGlobal( - "Audio", - class { - src = ""; - onended: (() => void) | null = null; - onerror: (() => void) | null = null; - play() { - queueMicrotask(() => this.onended?.()); - return Promise.resolve(); - } - pause() {} - }, - ); - vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:voice"); - vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined); - - const speaker = new Speaker(); - const prepare = vi - .spyOn( - speaker as unknown as { - prepare: ( - text: string, - opts: unknown, - signal: AbortSignal, - spaceId: string | null, - ) => Promise; - }, - "prepare", - ) - .mockImplementation(async () => { - changeSelectedSpace("space-other"); - return ["Hello."]; - }); - await speaker.speak("Hello.", { messageId: "m1" }); - - expect(fetchMock).toHaveBeenCalledWith( - "/api/voice/speak", - expect.objectContaining({ credentials: "include" }), - ); - const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers); - expect(headers.get("x-rakazo-space-id")).toBe("space-support"); - expect(headers.get("content-type")).toBe("application/json"); - expect(prepare.mock.calls[0]?.[3]).toBe("space-support"); - }); - - it("rejects oversized audio without waiting for response cancellation", async () => { - const cancel = vi.fn(() => new Promise(() => undefined)); - vi.stubGlobal( - "fetch", - vi.fn( - async () => - new Response(new ReadableStream({ cancel }), { - headers: { "content-length": String(MAX_VOICE_AUDIO_BYTES + 1) }, - }), - ), - ); - const speaker = new Speaker(); - vi.spyOn( - speaker as unknown as { prepare: () => Promise }, - "prepare", - ).mockResolvedValue(["Hello."]); - - await expect(speaker.speak("Hello.")).resolves.toBeUndefined(); - - expect(speaker.state.error).toBe("Voice response is too large."); - expect(cancel).toHaveBeenCalledOnce(); - }); - - it("times out while a voice response body is stalled", async () => { - vi.useFakeTimers(); - vi.stubGlobal( - "fetch", - vi.fn( - async () => - new Response( - new ReadableStream({ - pull: () => new Promise(() => undefined), - }), - ), - ), - ); - const speaker = new Speaker(); - vi.spyOn( - speaker as unknown as { prepare: () => Promise }, - "prepare", - ).mockResolvedValue(["Hello."]); - - const pending = speaker.speak("Hello."); - await vi.advanceTimersByTimeAsync(VOICE_RESPONSE_TIMEOUT_MS); - await pending; - - expect(speaker.state.error).toBe("Voice request timed out."); - }); -}); diff --git a/apps/web/src/lib/tts.ts b/apps/web/src/lib/tts.ts deleted file mode 100644 index 3db3476e..00000000 --- a/apps/web/src/lib/tts.ts +++ /dev/null @@ -1,293 +0,0 @@ -import { readBoundedResponseBytes } from "@milo/core"; -import { rpc, selectedSpaceId, withSpaceHeaders } from "./rpc.js"; - -export type SpeechStatus = "idle" | "preparing" | "speaking"; - -export interface SpeechSnapshot { - status: SpeechStatus; - botId?: string; - messageId?: string; - caption?: string; - error?: string; -} - -interface SpeakOptions { - voiceId?: string; - botId?: string; - messageId?: string; -} - -type TtsErrorBody = { error?: string }; - -const IDLE: SpeechSnapshot = { status: "idle" }; -export const VOICE_RESPONSE_TIMEOUT_MS = 70_000; -export const MAX_VOICE_AUDIO_BYTES = 16 * 1024 * 1024; -const MAX_VOICE_ERROR_BYTES = 64 * 1024; - -export class Speaker { - private snapshot: SpeechSnapshot = IDLE; - private watchers = new Set<(s: SpeechSnapshot) => void>(); - private token = 0; - private audio: HTMLAudioElement | null = null; - private objectUrl: string | null = null; - private settlePlayback: ((finished: boolean) => void) | null = null; - private request: AbortController | null = null; - - subscribe(fn: (s: SpeechSnapshot) => void): () => void { - this.watchers.add(fn); - fn(this.snapshot); - return () => { - this.watchers.delete(fn); - }; - } - - get state(): SpeechSnapshot { - return this.snapshot; - } - - private set(next: SpeechSnapshot) { - this.snapshot = next; - for (const watcher of [...this.watchers]) watcher(next); - } - - isSpeaking(messageId?: string): boolean { - if (this.snapshot.status === "idle") return false; - return messageId ? this.snapshot.messageId === messageId : true; - } - - stop() { - this.token += 1; - this.request?.abort(); - this.request = null; - if (this.settlePlayback) this.settlePlayback(false); - else this.teardownAudio(); - if (this.snapshot.status !== "idle" || this.snapshot.error) this.set(IDLE); - } - - private teardownAudio() { - if (this.audio) { - this.audio.pause(); - this.audio.src = ""; - this.audio = null; - } - if (this.objectUrl) { - URL.revokeObjectURL(this.objectUrl); - this.objectUrl = null; - } - } - - async speak(text: string, opts: SpeakOptions = {}): Promise { - this.stop(); - const mine = this.token; - const controller = new AbortController(); - this.request = controller; - const live = () => this.token === mine && !controller.signal.aborted; - const spaceId = selectedSpaceId(); - - this.set({ status: "preparing", botId: opts.botId, messageId: opts.messageId }); - let utterances: string[]; - try { - utterances = await withAbort(controller.signal, () => - this.prepare(text, opts, controller.signal, spaceId), - ); - } catch (error) { - if (live()) { - this.set({ ...IDLE, error: error instanceof Error ? error.message : String(error) }); - } - if (this.request === controller) this.request = null; - return; - } - if (!live()) return; - if (!utterances.length) { - this.set(IDLE); - if (this.request === controller) this.request = null; - return; - } - - type Rendered = { blob: Blob; error?: never } | { blob?: never; error: unknown }; - const render = (utterance: string): Promise => - this.render(utterance, opts, controller.signal, spaceId).then( - (blob) => ({ blob }), - (error: unknown) => ({ error }), - ); - let next: Promise | null = render(utterances[0] ?? ""); - for (let i = 0; i < utterances.length; i += 1) { - const current = next; - next = i + 1 < utterances.length ? render(utterances[i + 1] ?? "") : null; - if (!current) break; - const rendered = await current; - if ("error" in rendered) { - if (live()) { - this.set({ - ...IDLE, - error: - rendered.error instanceof Error ? rendered.error.message : String(rendered.error), - }); - } - if (this.request === controller) this.request = null; - return; - } - if (!live()) return; - this.set({ - status: "speaking", - botId: opts.botId, - messageId: opts.messageId, - caption: utterances[i], - }); - const finished = await this.play(rendered.blob, live); - if (!finished || !live()) { - if (live()) this.set(IDLE); - if (this.request === controller) this.request = null; - return; - } - } - if (live()) this.set(IDLE); - if (this.request === controller) this.request = null; - } - - private async prepare( - text: string, - opts: SpeakOptions, - signal: AbortSignal, - spaceId: string | null, - ): Promise { - const body = await rpc.voice.prepare( - { text, voiceId: opts.voiceId, botId: opts.botId }, - { signal, context: { spaceId } }, - ); - if (!body.ready) { - throw new Error("Add a voice provider key and pick a voice in Voice settings."); - } - return body.utterances ?? []; - } - - private async render( - text: string, - opts: SpeakOptions, - signal: AbortSignal, - spaceId: string | null, - ): Promise { - const deadline = requestDeadline(signal, VOICE_RESPONSE_TIMEOUT_MS); - try { - const res = await withAbort(deadline.signal, () => - fetch("/api/voice/speak", { - method: "POST", - headers: withSpaceHeaders({ "content-type": "application/json" }, spaceId), - credentials: "include", - body: JSON.stringify({ text, voiceId: opts.voiceId, botId: opts.botId }), - signal: deadline.signal, - }), - ); - if (!res.ok) { - const body = await readVoiceError(res, deadline.signal); - throw new Error(body.error ?? `the voice service returned ${res.status}`); - } - const bytes = await readResponseBytes(res, MAX_VOICE_AUDIO_BYTES, deadline.signal); - return new Blob([new Uint8Array(bytes)], { - type: res.headers.get("content-type") ?? "audio/mpeg", - }); - } finally { - deadline.dispose(); - } - } - - private play(blob: Blob, live: () => boolean): Promise { - return new Promise((resolve) => { - if (!live()) return resolve(false); - this.teardownAudio(); - const url = URL.createObjectURL(blob); - const audio = new Audio(url); - this.audio = audio; - this.objectUrl = url; - let settled = false; - const done = (ok: boolean) => { - if (settled) return; - settled = true; - audio.onended = null; - audio.onerror = null; - if (this.settlePlayback === done) this.settlePlayback = null; - if (this.audio === audio) this.teardownAudio(); - resolve(ok); - }; - this.settlePlayback = done; - audio.onended = () => done(true); - audio.onerror = () => done(false); - audio.play().catch(() => done(false)); - }); - } -} - -export const speaker = new Speaker(); - -function withAbort(signal: AbortSignal, run: () => Promise): Promise { - if (signal.aborted) { - return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError")); - } - return new Promise((resolve, reject) => { - const onAbort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError")); - signal.addEventListener("abort", onAbort, { once: true }); - run().then( - (value) => { - signal.removeEventListener("abort", onAbort); - resolve(value); - }, - (error: unknown) => { - signal.removeEventListener("abort", onAbort); - reject(error); - }, - ); - }); -} - -function requestDeadline(parent: AbortSignal, timeoutMs: number) { - const controller = new AbortController(); - const abortFromParent = () => controller.abort(parent.reason); - if (parent.aborted) abortFromParent(); - else parent.addEventListener("abort", abortFromParent, { once: true }); - const timer = setTimeout( - () => controller.abort(new Error("Voice request timed out.")), - timeoutMs, - ); - return { - signal: controller.signal, - dispose() { - clearTimeout(timer); - parent.removeEventListener("abort", abortFromParent); - }, - }; -} - -async function readVoiceError(response: Response, signal: AbortSignal): Promise { - const bytes = await readResponseBytes(response, MAX_VOICE_ERROR_BYTES, signal); - try { - const parsed = JSON.parse(new TextDecoder().decode(bytes)) as unknown; - return parsed && typeof parsed === "object" ? (parsed as TtsErrorBody) : {}; - } catch { - return {}; - } -} - -async function readResponseBytes( - response: Response, - maxBytes: number, - signal: AbortSignal, -): Promise { - const declared = Number(response.headers.get("content-length") ?? 0); - if (Number.isFinite(declared) && declared > maxBytes) { - cancelResponse(response); - throw new Error("Voice response is too large."); - } - return readBoundedResponseBytes(response, { - maxBytes, - tooLargeMessage: "Voice response is too large.", - read: (operation) => withAbort(signal, operation), - }); -} - -function cancelResponse(response: Response): void { - try { - void Promise.resolve(response.body?.cancel()).catch(() => undefined); - } catch { - // Response cleanup is best-effort. - } -} diff --git a/apps/web/src/locales/de/messages.po b/apps/web/src/locales/de/messages.po index 0f15e4d1..7ae217a0 100644 --- a/apps/web/src/locales/de/messages.po +++ b/apps/web/src/locales/de/messages.po @@ -193,10 +193,6 @@ msgstr "Zugriffstoken (optional)" msgid "Account" msgstr "Konto" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Kontostandard" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "" #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API-Schlüssel" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "Benutzereinstellungen schließen" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Stimmeinstellungen schließen" - #: src/components/AskCard.tsx msgid "Code" msgstr "Code" @@ -934,7 +924,6 @@ msgstr "Passwort bestätigen" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Verbinden" @@ -979,7 +968,6 @@ msgstr "Apps verbinden" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Verbunden" @@ -988,11 +976,6 @@ msgstr "Verbunden" msgid "Connected · {0}" msgstr "Verbunden · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "{0} verbunden." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Verbunden. Die Tools sind ab deiner nächsten Nachricht verfügbar." #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Verbindung wird hergestellt…" @@ -1108,10 +1090,6 @@ msgstr "Verbindung fehlgeschlagen" msgid "Could not connect this provider" msgstr "Anbieter konnte nicht verbunden werden" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "Stimmanbieter konnte nicht verbunden werden" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "" @@ -1177,10 +1155,6 @@ msgstr "OAuth-Verbindung konnte nicht getrennt werden" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "Stimmanbieter konnte nicht getrennt werden" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "Datei konnte nicht geladen werden." msgid "Could not load update status" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "Stimmeinstellungen konnten nicht geladen werden" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "Datei konnte nicht geöffnet werden" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "Terminal konnte nicht geöffnet werden" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "Testclip konnte nicht abgespielt werden" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "Skill konnte nicht gespeichert werden" msgid "Could not save that choice" msgstr "Auswahl konnte nicht gespeichert werden" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "Sprachmodell konnte nicht gespeichert werden" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "Stimme konnte nicht gespeichert werden" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "E-Mail zum Zurücksetzen konnte nicht gesendet werden" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "Senden fehlgeschlagen" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "OAuth konnte nicht gestartet werden" @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Trennen" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Verbindung wird getrennt…" @@ -1989,18 +1941,6 @@ msgstr "{0} an mich übergeben" msgid "Hand to me" msgstr "An mich übergeben" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Auflegen" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "" - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "" - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "" @@ -2019,14 +1959,6 @@ msgstr "Header-Name" msgid "Header value" msgstr "Header-Wert" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Beispiel anhören" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Hallo, so klinge ich, wenn ich Antworten vorlese." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Transkript ausblenden" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "Hoch" @@ -2068,10 +1996,6 @@ msgstr "So wird geprüft" msgid "I’m done" msgstr "Ich bin fertig" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "Wenn du das gehört hast, ist die Stimme einsatzbereit." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Bild-Upload-Bereich" @@ -2241,10 +2165,6 @@ msgstr "Vorschau wird geladen…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Stimmanbieter werden geladen…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Nachricht…" msgid "Messaged {peer}" msgstr "Nachricht an {peer} gesendet" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Mikrofonfehler" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Minimal" @@ -2480,10 +2396,6 @@ msgstr "Verschiebe sie in deine geteilten Erinnerungen." msgid "Move to" msgstr "Verschieben nach" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Stummschalten" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "OAuth-Verbindung fehlgeschlagen" msgid "OAuth expired" msgstr "" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "Im Gespräch mit {0}" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Dein Arbeitsbereich wird geöffnet…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "Optional" @@ -2831,18 +2737,10 @@ msgstr "Passwort aktualisiert" msgid "Passwords do not match" msgstr "Die Passwörter stimmen nicht überein" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Ersatzschlüssel einfügen" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Füge die OpenAI-kompatible Adresse deines Servers ein. Milo ergänzt /v1 bei Bedarf." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "Füge deinen API-Schlüssel ein" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "" msgid "Pin" msgstr "Anheften" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Wiedergabe…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Anbieter" @@ -2911,10 +2804,6 @@ msgstr "Reagieren" msgid "Reactions" msgstr "Reaktionen" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Antworten vorlesen" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "schreibgeschützt" @@ -3076,10 +2965,6 @@ msgstr "Erneut öffnen" msgid "Replace API key" msgstr "API-Schlüssel ersetzen" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Schlüssel ersetzen" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "Wird gespeichert…" msgid "Say hi" msgstr "Hallo sagen" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Antworte mit Ja oder Nein oder in einem Satz." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Servername" msgid "Server URL" msgstr "Server-URL" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Transkript anzeigen" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Space-Standard" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Vorlesen" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Sprechen + transkribieren" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Nur sprechen" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Diese Antwort vorlesen" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Sprachmodell" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Aufnahme starten" @@ -3571,10 +3427,6 @@ msgstr "Schritte" msgid "Stop" msgstr "Stoppen" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Vorlesen stoppen" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Anlernen beenden" @@ -3769,10 +3621,6 @@ msgstr "Toolquellen" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Transkript" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Treg-Token" @@ -3806,10 +3654,6 @@ msgstr "" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Stummschaltung aufheben" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Lösen" @@ -3940,17 +3784,6 @@ msgstr "Ansicht" msgid "View chat" msgstr "Chat anzeigen" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Stimme" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Sprachchat" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/en/messages.po b/apps/web/src/locales/en/messages.po index 6fce6727..56e499a3 100644 --- a/apps/web/src/locales/en/messages.po +++ b/apps/web/src/locales/en/messages.po @@ -193,10 +193,6 @@ msgstr "Access token (optional)" msgid "Account" msgstr "Account" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Account default" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "Account label" @@ -437,7 +433,6 @@ msgstr "API is back, but the update did not finish. Check the host logs." #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API key" @@ -841,11 +836,6 @@ msgstr "Close usage settings" msgid "Close user settings" msgstr "Close user settings" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Close voice settings" - #: src/components/AskCard.tsx msgid "Code" msgstr "Code" @@ -934,7 +924,6 @@ msgstr "Confirm password" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Connect" @@ -979,7 +968,6 @@ msgstr "Connect your apps" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Connected" @@ -988,11 +976,6 @@ msgstr "Connected" msgid "Connected · {0}" msgstr "Connected · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "Connected {0}." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Connected. Its tools are available from your next message." #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Connecting…" @@ -1108,10 +1090,6 @@ msgstr "Could not connect" msgid "Could not connect this provider" msgstr "Could not connect this provider" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "Could not connect this voice provider" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "Could not connect to the computer screen" @@ -1177,10 +1155,6 @@ msgstr "Could not disconnect OAuth" msgid "Could not disconnect this provider" msgstr "Could not disconnect this provider" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "Could not disconnect this voice provider" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "Could not dismiss" @@ -1275,10 +1249,6 @@ msgstr "Could not load this file." msgid "Could not load update status" msgstr "Could not load update status" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "Could not load voice settings" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "Could not open file" @@ -1291,10 +1261,6 @@ msgstr "Could not open local settings. Start the local server and create its own msgid "Could not open terminal" msgstr "Could not open terminal" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "Could not play a test clip" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "Could not save skill" msgid "Could not save that choice" msgstr "Could not save that choice" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "Could not save that speech model" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "Could not save that voice" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "Could not save the credential" @@ -1407,10 +1365,6 @@ msgstr "Could not search catalog" msgid "Could not send reset email" msgstr "Could not send reset email" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "Could not send that" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "Could not start OAuth" @@ -1672,7 +1626,6 @@ msgstr "Direct MCP" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Disconnect" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "Disconnected {0}." #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Disconnecting…" @@ -1989,18 +1941,6 @@ msgstr "Hand {0} to me" msgid "Hand to me" msgstr "Hand to me" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Hang up" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "Hang up first, then enter the code on screen." - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "Hang up, then enter the code on screen." - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "header" @@ -2019,14 +1959,6 @@ msgstr "Header name" msgid "Header value" msgstr "Header value" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Hear a sample" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Hi, this is how I'll sound when I read replies out loud." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "Hide bots" @@ -2035,10 +1967,6 @@ msgstr "Hide bots" msgid "Hide password" msgstr "Hide password" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Hide transcript" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "High" @@ -2068,10 +1996,6 @@ msgstr "How to check" msgid "I’m done" msgstr "I’m done" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "If you heard that, voice is ready." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Image upload area" @@ -2241,10 +2165,6 @@ msgstr "Loading preview…" msgid "Loading tools…" msgstr "Loading tools…" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Loading voice providers…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Message…" msgid "Messaged {peer}" msgstr "Messaged {peer}" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Microphone failed" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Minimal" @@ -2480,10 +2396,6 @@ msgstr "Move them to your shared memory." msgid "Move to" msgstr "Move to" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Mute" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "OAuth connection failed" msgid "OAuth expired" msgstr "OAuth expired" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "On a call with {0}" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "On a schedule" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Opening your Space…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "Optional" @@ -2831,18 +2737,10 @@ msgstr "Password updated" msgid "Passwords do not match" msgstr "Passwords do not match" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Paste a replacement key" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "Paste your API key" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "Paused" msgid "Pin" msgstr "Pin" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Playing…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "POST to" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "Protected input" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Providers" @@ -2911,10 +2804,6 @@ msgstr "React" msgid "Reactions" msgstr "Reactions" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Read replies aloud" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "read-only" @@ -3076,10 +2965,6 @@ msgstr "Reopen" msgid "Replace API key" msgstr "Replace API key" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Replace key" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "Replace value" @@ -3294,10 +3179,6 @@ msgstr "Saving…" msgid "Say hi" msgstr "Say hi" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Say yes or no, or answer in a sentence." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Server name" msgid "Server URL" msgstr "Server URL" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "Show password" msgid "Show tool activity" msgstr "Show tool activity" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Show transcript" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Space default" msgid "Spaces" msgstr "Spaces" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Speak" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Speak + transcribe" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Speak only" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Speak this reply" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Speech model" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Start recording" @@ -3571,10 +3427,6 @@ msgstr "Steps" msgid "Stop" msgstr "Stop" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Stop speaking" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Stop teaching" @@ -3769,10 +3621,6 @@ msgstr "Tool sources" msgid "Tools" msgstr "Tools" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Transcript" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Treg token" @@ -3806,10 +3654,6 @@ msgstr "Unavailable" msgid "Uninstall" msgstr "Uninstall" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Unmute" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Unpin" @@ -3940,17 +3784,6 @@ msgstr "View" msgid "View chat" msgstr "View chat" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Voice" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Voice chat" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/es/messages.po b/apps/web/src/locales/es/messages.po index c1b07e06..5dedac85 100644 --- a/apps/web/src/locales/es/messages.po +++ b/apps/web/src/locales/es/messages.po @@ -193,10 +193,6 @@ msgstr "Token de acceso (opcional)" msgid "Account" msgstr "Cuenta" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Predeterminado de la cuenta" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "La API volvió, pero la actualización no terminó. Revisa los logs del #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "Clave de API" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "Cerrar configuración de usuario" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Cerrar configuración de voz" - #: src/components/AskCard.tsx msgid "Code" msgstr "Código" @@ -934,7 +924,6 @@ msgstr "Confirmar contraseña" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Conectar" @@ -979,7 +968,6 @@ msgstr "Conecta tus apps" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Conectado" @@ -988,11 +976,6 @@ msgstr "Conectado" msgid "Connected · {0}" msgstr "Conectado · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "Se conectó {0}." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Conectado: sus herramientas estarán disponibles desde tu próximo mensa #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Conectando…" @@ -1108,10 +1090,6 @@ msgstr "No se pudo conectar" msgid "Could not connect this provider" msgstr "No se pudo conectar este proveedor" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "No se pudo conectar este proveedor de voz" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "No se pudo conectar a la pantalla de la computadora" @@ -1177,10 +1155,6 @@ msgstr "No se pudo desconectar OAuth" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "No se pudo desconectar este proveedor de voz" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "No se pudo cargar este archivo." msgid "Could not load update status" msgstr "No se pudo cargar el estado de actualización" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "No se pudo cargar la configuración de voz" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "No se pudo abrir la terminal" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "No se pudo reproducir un clip de prueba" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "No se pudo guardar la habilidad" msgid "Could not save that choice" msgstr "No se pudo guardar esa opción" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "No se pudo guardar ese modelo de habla" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "No se pudo guardar esa voz" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "No se pudo enviar el correo de restablecimiento" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "No se pudo enviar eso" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "No se pudo iniciar OAuth" @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Desconectar" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Desconectando…" @@ -1989,18 +1941,6 @@ msgstr "Pásame {0}" msgid "Hand to me" msgstr "Pásamelo a mí" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Colgar" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "Cuelga primero y luego ingresa el código en pantalla." - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "Cuelga y luego ingresa el código en pantalla." - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "Encabezado" @@ -2019,14 +1959,6 @@ msgstr "Nombre del encabezado" msgid "Header value" msgstr "Valor del encabezado" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Escuchar una muestra" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Hola, así sonaré cuando lea las respuestas en voz alta." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "Ocultar contraseña" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Ocultar la transcripción" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "Alto" @@ -2068,10 +1996,6 @@ msgstr "Cómo comprobar" msgid "I’m done" msgstr "Listo" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "Si escuchaste eso, la voz está lista." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Área de carga de imagen" @@ -2241,10 +2165,6 @@ msgstr "Cargando vista previa…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Cargando proveedores de voz…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Mensaje…" msgid "Messaged {peer}" msgstr "Mensaje enviado a {peer}" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Falló el micrófono" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Mínimo" @@ -2480,10 +2396,6 @@ msgstr "Muévelas a tu memoria compartida." msgid "Move to" msgstr "Mover a" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Silenciar" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "Falló la conexión OAuth" msgid "OAuth expired" msgstr "OAuth expirado" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "En llamada con {0}" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "Con un horario" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Abriendo tu Space…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "Opcional" @@ -2831,18 +2737,10 @@ msgstr "Contraseña actualizada" msgid "Passwords do not match" msgstr "Las contraseñas no coinciden" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Pega una clave de reemplazo" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Pega la dirección compatible con OpenAI de tu servidor. Milo agrega /v1 si es necesario." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "Pega tu clave de API" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "En pausa" msgid "Pin" msgstr "Fijar" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Reproduciendo…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "POST a" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Proveedores" @@ -2911,10 +2804,6 @@ msgstr "Reaccionar" msgid "Reactions" msgstr "Reacciones" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Leer respuestas en voz alta" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "Solo lectura" @@ -3076,10 +2965,6 @@ msgstr "Reabrir" msgid "Replace API key" msgstr "Reemplazar clave de API" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Reemplazar clave" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "Guardando…" msgid "Say hi" msgstr "Saludar" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Di sí o no, o responde en una frase." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Nombre del servidor" msgid "Server URL" msgstr "URL del servidor" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "Mostrar contraseña" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Mostrar la transcripción" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Predeterminado del Space" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Hablar" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Hablar + transcribir" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Solo hablar" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Leer esta respuesta" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Modelo de habla" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Iniciar grabación" @@ -3571,10 +3427,6 @@ msgstr "Pasos" msgid "Stop" msgstr "Detener" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Dejar de hablar" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Detener enseñanza" @@ -3769,10 +3621,6 @@ msgstr "Fuentes de herramientas" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Transcripción" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Token de Treg" @@ -3806,10 +3654,6 @@ msgstr "No disponible" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Activar el sonido" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Desfijar" @@ -3940,17 +3784,6 @@ msgstr "Vista" msgid "View chat" msgstr "Ver chat" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Voz" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Chat de voz" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/fr/messages.po b/apps/web/src/locales/fr/messages.po index 236f4262..27974c28 100644 --- a/apps/web/src/locales/fr/messages.po +++ b/apps/web/src/locales/fr/messages.po @@ -193,10 +193,6 @@ msgstr "Jeton d'accès (optionnel)" msgid "Account" msgstr "Compte" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Défaut du compte" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "Libellé du compte" @@ -437,7 +433,6 @@ msgstr "L'API est de retour, mais la mise à jour n'est pas terminée. Vérifiez #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "Clé API" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "Fermer les paramètres utilisateur" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Fermer les paramètres vocaux" - #: src/components/AskCard.tsx msgid "Code" msgstr "Code" @@ -934,7 +924,6 @@ msgstr "Confirmer le mot de passe" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Connecter" @@ -979,7 +968,6 @@ msgstr "Connectez vos apps" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Connecté" @@ -988,11 +976,6 @@ msgstr "Connecté" msgid "Connected · {0}" msgstr "Connecté · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "Connecté à {0}." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Connecté. Ses outils sont disponibles dès votre prochain message." #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Connexion en cours…" @@ -1108,10 +1090,6 @@ msgstr "Impossible de se connecter" msgid "Could not connect this provider" msgstr "Impossible de se connecter à ce fournisseur" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "Impossible de se connecter à ce fournisseur vocal" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "Impossible de se connecter à l'écran de l'ordinateur" @@ -1177,10 +1155,6 @@ msgstr "Impossible de déconnecter OAuth" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "Impossible de déconnecter ce fournisseur vocal" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "Impossible de fermer" @@ -1275,10 +1249,6 @@ msgstr "Impossible de charger ce fichier." msgid "Could not load update status" msgstr "Impossible de charger l'état de la mise à jour" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "Impossible de charger les paramètres vocaux" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "Impossible d'ouvrir les paramètres locaux. Démarrez le serveur local e msgid "Could not open terminal" msgstr "Impossible d'ouvrir le terminal" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "Impossible de lire un extrait de test" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "Impossible d'enregistrer la compétence" msgid "Could not save that choice" msgstr "Impossible d'enregistrer ce choix" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "Impossible d'enregistrer ce modèle de parole" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "Impossible d'enregistrer cette voix" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "Impossible de rechercher dans le catalogue" msgid "Could not send reset email" msgstr "Impossible d'envoyer l'e-mail de réinitialisation" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "Impossible d'envoyer cela" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "Impossible de démarrer OAuth" @@ -1672,7 +1626,6 @@ msgstr "MCP direct" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Déconnecter" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Déconnexion en cours…" @@ -1989,18 +1941,6 @@ msgstr "Me confier {0}" msgid "Hand to me" msgstr "Me le confier" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Raccrocher" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "Raccrochez d'abord, puis saisissez le code à l'écran." - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "Raccrochez, puis saisissez le code à l'écran." - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "en-tête" @@ -2019,14 +1959,6 @@ msgstr "Nom de l'en-tête" msgid "Header value" msgstr "Valeur de l'en-tête" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Écouter un extrait" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Bonjour, c'est ainsi que je sonnerai quand je lirai les réponses à voix haute." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "Masquer les bots" @@ -2035,10 +1967,6 @@ msgstr "Masquer les bots" msgid "Hide password" msgstr "Masquer le mot de passe" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Masquer la transcription" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "Élevé" @@ -2068,10 +1996,6 @@ msgstr "Comment vérifier" msgid "I’m done" msgstr "J'ai terminé" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "Si vous avez entendu cela, la voix est prête." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Zone de téléchargement d'image" @@ -2241,10 +2165,6 @@ msgstr "Chargement de l'aperçu…" msgid "Loading tools…" msgstr "Chargement des outils…" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Chargement des fournisseurs vocaux…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Message…" msgid "Messaged {peer}" msgstr "A contacté {peer}" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Le microphone a échoué" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Minimal" @@ -2480,10 +2396,6 @@ msgstr "Déplacez-les dans votre mémoire partagée." msgid "Move to" msgstr "Déplacer vers" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Couper le micro" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "Échec de la connexion OAuth" msgid "OAuth expired" msgstr "OAuth expiré" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "En appel avec {0}" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "Sur planification" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Ouverture de votre espace…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "Optionnel" @@ -2831,18 +2737,10 @@ msgstr "Mot de passe mis à jour" msgid "Passwords do not match" msgstr "Les mots de passe ne correspondent pas" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Collez une clé de remplacement" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Collez l'adresse compatible OpenAI de votre serveur. Milo ajoute /v1 si nécessaire." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "Collez votre clé API" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "En pause" msgid "Pin" msgstr "Épingler" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Lecture en cours…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "POST vers" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Fournisseurs" @@ -2911,10 +2804,6 @@ msgstr "Réagir" msgid "Reactions" msgstr "Réactions" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Lire les réponses à voix haute" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "lecture seule" @@ -3076,10 +2965,6 @@ msgstr "Rouvrir" msgid "Replace API key" msgstr "Remplacer la clé API" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Remplacer la clé" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "Enregistrement en cours…" msgid "Say hi" msgstr "Dire bonjour" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Dites oui ou non, ou répondez en une phrase." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Nom du serveur" msgid "Server URL" msgstr "URL du serveur" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "Afficher le mot de passe" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Afficher la transcription" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Défaut de l'espace" msgid "Spaces" msgstr "Espaces" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Parler" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Parler + transcrire" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Parler uniquement" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Lire cette réponse à voix haute" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Modèle de parole" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Démarrer l'enregistrement" @@ -3571,10 +3427,6 @@ msgstr "Étapes" msgid "Stop" msgstr "Arrêter" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Arrêter la lecture" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Arrêter l'enseignement" @@ -3769,10 +3621,6 @@ msgstr "Sources d'outils" msgid "Tools" msgstr "Outils" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Transcription" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Jeton Treg" @@ -3806,10 +3654,6 @@ msgstr "Indisponible" msgid "Uninstall" msgstr "Désinstaller" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Réactiver le micro" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Désépingler" @@ -3940,17 +3784,6 @@ msgstr "Affichage" msgid "View chat" msgstr "Voir la conversation" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Voix" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Chat vocal" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/hi/messages.po b/apps/web/src/locales/hi/messages.po index 16bd2a42..02142a92 100644 --- a/apps/web/src/locales/hi/messages.po +++ b/apps/web/src/locales/hi/messages.po @@ -193,10 +193,6 @@ msgstr "एक्सेस टोकन (वैकल्पिक)" msgid "Account" msgstr "खाता" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "खाता डिफ़ॉल्ट" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "" #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API कुंजी" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "उपयोगकर्ता सेटिंग्स बंद करें" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "आवाज़ सेटिंग्स बंद करें" - #: src/components/AskCard.tsx msgid "Code" msgstr "कोड" @@ -934,7 +924,6 @@ msgstr "पासवर्ड की पुष्टि करें" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "कनेक्ट करें" @@ -979,7 +968,6 @@ msgstr "अपने ऐप जोड़ें" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "कनेक्टेड" @@ -988,11 +976,6 @@ msgstr "कनेक्टेड" msgid "Connected · {0}" msgstr "कनेक्टेड · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "{0} कनेक्ट किया गया।" - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "कनेक्टेड। इसके टूल आपके अग #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "कनेक्ट हो रहा है…" @@ -1108,10 +1090,6 @@ msgstr "कनेक्ट नहीं हो सका" msgid "Could not connect this provider" msgstr "यह प्रोवाइडर कनेक्ट नहीं हो सका" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "यह आवाज़ प्रोवाइडर कनेक्ट नहीं हो सका" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "" @@ -1177,10 +1155,6 @@ msgstr "OAuth डिस्कनेक्ट नहीं हो सका" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "यह आवाज़ प्रोवाइडर डिस्कनेक्ट नहीं हो सका" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "यह फ़ाइल लोड नहीं हो सकी।" msgid "Could not load update status" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "आवाज़ सेटिंग्स लोड नहीं हो सकीं" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "टर्मिनल नहीं खोला जा सका" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "टेस्ट क्लिप नहीं चलाई जा सकी" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "स्किल सहेजी नहीं जा सकी" msgid "Could not save that choice" msgstr "वह विकल्प सहेजा नहीं जा सका" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "वह वाक् मॉडल सहेजा नहीं जा सका" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "वह आवाज़ सहेजी नहीं जा सकी" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "रीसेट ईमेल नहीं भेजा जा सका" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "वह भेजा नहीं जा सका" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "OAuth शुरू नहीं हो सका" @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "डिस्कनेक्ट करें" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "डिस्कनेक्ट हो रहा है…" @@ -1989,18 +1941,6 @@ msgstr "{0} मुझे सौंपें" msgid "Hand to me" msgstr "मुझे सौंपें" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "कॉल समाप्त करें" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "" - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "" - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "" @@ -2019,14 +1959,6 @@ msgstr "हेडर नाम" msgid "Header value" msgstr "हेडर मान" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "एक नमूना सुनें" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "नमस्ते, उत्तर पढ़कर सुनाते समय मेरी आवाज़ ऐसी होगी।" - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "ट्रांसक्रिप्ट छिपाएँ" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "उच्च" @@ -2068,10 +1996,6 @@ msgstr "जांच कैसे करें" msgid "I’m done" msgstr "मेरा काम हो गया" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "अगर आपने वह सुना, तो आवाज़ तैयार है।" - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "छवि अपलोड क्षेत्र" @@ -2241,10 +2165,6 @@ msgstr "प्रीव्यू लोड हो रहा है…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "आवाज़ प्रोवाइडर्स लोड हो रहे हैं…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "संदेश…" msgid "Messaged {peer}" msgstr "{peer} को संदेश भेजा" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "माइक्रोफ़ोन विफल" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "न्यूनतम" @@ -2480,10 +2396,6 @@ msgstr "उन्हें अपनी साझा मेमोरी मे msgid "Move to" msgstr "यहां ले जाएं" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "म्यूट करें" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "OAuth कनेक्शन विफल" msgid "OAuth expired" msgstr "" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "{0} के साथ कॉल पर" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "आपका वर्कस्पेस खुल रहा है…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "वैकल्पिक" @@ -2831,18 +2737,10 @@ msgstr "पासवर्ड अपडेट हो गया" msgid "Passwords do not match" msgstr "पासवर्ड मेल नहीं खाते" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "बदलने के लिए नई कुंजी पेस्ट करें" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "अपने सर्वर से OpenAI-संगत पता पेस्ट करें। ज़रूरत होने पर Milo /v1 जोड़ देता है।" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "अपनी API कुंजी पेस्ट करें" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "" msgid "Pin" msgstr "पिन करें" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "प्ले हो रहा है…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "प्रोवाइडर्स" @@ -2911,10 +2804,6 @@ msgstr "प्रतिक्रिया दें" msgid "Reactions" msgstr "प्रतिक्रियाएँ" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "उत्तर पढ़कर सुनाएं" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "केवल पढ़ने योग्य" @@ -3076,10 +2965,6 @@ msgstr "पुनः खोलें" msgid "Replace API key" msgstr "API कुंजी बदलें" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "कुंजी बदलें" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "सहेजा जा रहा है…" msgid "Say hi" msgstr "नमस्ते कहें" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "हां या ना कहें, या एक वाक्य में उत्तर दें।" - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "सर्वर का नाम" msgid "Server URL" msgstr "सर्वर URL" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "ट्रांसक्रिप्ट दिखाएँ" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "स्पेस डिफ़ॉल्ट" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "बोलें" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "बोलें + लिप्यंतरण करें" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "केवल बोलें" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "यह उत्तर बोलकर सुनाएं" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "वाक् मॉडल" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "रिकॉर्डिंग शुरू करें" @@ -3571,10 +3427,6 @@ msgstr "चरण" msgid "Stop" msgstr "रोकें" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "बोलना रोकें" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "सिखाना रोकें" @@ -3769,10 +3621,6 @@ msgstr "टूल स्रोत" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "ट्रांसक्रिप्ट" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Treg टोकन" @@ -3806,10 +3654,6 @@ msgstr "" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "अनम्यूट करें" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "पिन हटाएं" @@ -3940,17 +3784,6 @@ msgstr "दृश्य" msgid "View chat" msgstr "चैट देखें" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "आवाज़" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "वॉइस चैट" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/ko/messages.po b/apps/web/src/locales/ko/messages.po index e8a1a181..cdd7a378 100644 --- a/apps/web/src/locales/ko/messages.po +++ b/apps/web/src/locales/ko/messages.po @@ -193,10 +193,6 @@ msgstr "액세스 토큰(선택 사항)" msgid "Account" msgstr "계정" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "계정 기본값" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "API가 다시 작동하지만 업데이트가 완료되지 않았습니 #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API 키" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "계정 설정 닫기" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "음성 설정 닫기" - #: src/components/AskCard.tsx msgid "Code" msgstr "코드" @@ -934,7 +924,6 @@ msgstr "비밀번호 확인" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "연결" @@ -979,7 +968,6 @@ msgstr "앱 연결" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "연결됨" @@ -988,11 +976,6 @@ msgstr "연결됨" msgid "Connected · {0}" msgstr "연결됨 · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "{0}에 연결했습니다." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "연결되었습니다. 다음 메시지부터 이 도구를 사용할 #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "연결 중…" @@ -1108,10 +1090,6 @@ msgstr "연결하지 못했습니다." msgid "Could not connect this provider" msgstr "AI 서비스에 연결하지 못했습니다." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "음성 서비스에 연결하지 못했습니다." - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "" @@ -1177,10 +1155,6 @@ msgstr "OAuth 연결을 해제하지 못했습니다." msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "음성 서비스 연결을 해제하지 못했습니다." - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "파일을 불러오지 못했습니다." msgid "Could not load update status" msgstr "업데이트 상태를 불러올 수 없습니다" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "음성 설정을 불러오지 못했습니다." - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "터미널을 열 수 없습니다" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "샘플 음성을 재생하지 못했습니다." - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "스킬을 저장하지 못했습니다" msgid "Could not save that choice" msgstr "선택 내용을 저장하지 못했습니다." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "음성 모델을 저장하지 못했습니다." - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "목소리를 저장하지 못했습니다." - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "재설정 이메일을 보낼 수 없습니다" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "메시지를 보내지 못했습니다." - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "OAuth 인증을 시작하지 못했습니다." @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "연결 해제" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "연결 해제 중…" @@ -1989,18 +1941,6 @@ msgstr "{0}은(는) 나에게 넘기기" msgid "Hand to me" msgstr "나에게 넘기기" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "통화 종료" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "먼저 전화를 끊은 다음 화면에 표시된 코드를 입력하세요." - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "전화를 끊은 다음 화면에 표시된 코드를 입력하세요." - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "header" @@ -2019,14 +1959,6 @@ msgstr "헤더 이름" msgid "Header value" msgstr "헤더 값" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "샘플 듣기" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "안녕하세요. 답변을 소리 내어 읽을 때 이런 목소리로 들립니다." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "비밀번호 숨기기" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "대화 기록 숨기기" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "높음" @@ -2068,10 +1996,6 @@ msgstr "완료 확인 방법" msgid "I’m done" msgstr "조작 끝내기" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "샘플이 들렸다면 음성 설정이 완료되었습니다." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "이미지 업로드 영역" @@ -2241,10 +2165,6 @@ msgstr "미리보기를 불러오는 중…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "음성 서비스를 불러오는 중…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "메시지를 입력하세요" msgid "Messaged {peer}" msgstr "{peer}에게 메시지 보냄" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "마이크를 사용할 수 없습니다." - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "최소" @@ -2480,10 +2396,6 @@ msgstr "공용 기억으로 옮깁니다." msgid "Move to" msgstr "섹션으로 이동" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "음소거" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "OAuth 연결 실패" msgid "OAuth expired" msgstr "" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "{0}님과 통화 중" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "일정에 따라" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "작업공간을 여는 중…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "선택 사항" @@ -2831,18 +2737,10 @@ msgstr "비밀번호가 업데이트되었습니다" msgid "Passwords do not match" msgstr "비밀번호가 일치하지 않습니다" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "새 API 키를 붙여넣으세요" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "서버의 OpenAI 호환 주소를 붙여넣으세요. 필요하면 Milo가 /v1을 추가합니다." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "API 키를 붙여넣으세요" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "일시 중지됨" msgid "Pin" msgstr "고정" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "재생 중…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "POST 대상" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "서비스" @@ -2911,10 +2804,6 @@ msgstr "반응하기" msgid "Reactions" msgstr "반응" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "답변을 자동으로 읽기" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "읽기 전용" @@ -3076,10 +2965,6 @@ msgstr "다시 열기" msgid "Replace API key" msgstr "API 키 교체" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "키 교체" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "저장 중…" msgid "Say hi" msgstr "인사하기" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "예 또는 아니요로 답하거나 문장으로 답해 주세요." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "서버 이름" msgid "Server URL" msgstr "서버 URL" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "비밀번호 표시" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "대화 기록 표시" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "스페이스 기본값" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "읽기" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "음성 출력·받아쓰기" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "음성 출력만" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "이 답변 읽기" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "음성 모델" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "작업 녹화 시작" @@ -3571,10 +3427,6 @@ msgstr "실행 단계" msgid "Stop" msgstr "중지" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "읽기 중지" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "가르치기 종료" @@ -3769,10 +3621,6 @@ msgstr "도구 소스" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "대화 기록" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Treg 토큰" @@ -3806,10 +3654,6 @@ msgstr "사용할 수 없음" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "음소거 해제" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "고정 해제" @@ -3940,17 +3784,6 @@ msgstr "보기" msgid "View chat" msgstr "채팅 보기" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "음성" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "음성 대화" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/pt-BR/messages.po b/apps/web/src/locales/pt-BR/messages.po index cf08ce11..ff1b6e13 100644 --- a/apps/web/src/locales/pt-BR/messages.po +++ b/apps/web/src/locales/pt-BR/messages.po @@ -193,10 +193,6 @@ msgstr "Token de acesso (opcional)" msgid "Account" msgstr "Conta" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Padrão da conta" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "" #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "Chave de API" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "Fechar configurações do usuário" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Fechar configurações de voz" - #: src/components/AskCard.tsx msgid "Code" msgstr "Código" @@ -934,7 +924,6 @@ msgstr "Confirmar senha" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Conectar" @@ -979,7 +968,6 @@ msgstr "Conecte seus apps" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Conectado" @@ -988,11 +976,6 @@ msgstr "Conectado" msgid "Connected · {0}" msgstr "Conectado · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "Conectado {0}." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Conectado. Suas ferramentas estão disponíveis na sua próxima mensagem #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Conectando…" @@ -1108,10 +1090,6 @@ msgstr "Não foi possível conectar" msgid "Could not connect this provider" msgstr "Não foi possível conectar este provedor" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "Não foi possível conectar este provedor de voz" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "" @@ -1177,10 +1155,6 @@ msgstr "Não foi possível desconectar o OAuth" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "Não foi possível desconectar este provedor de voz" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "Não foi possível carregar este arquivo." msgid "Could not load update status" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "Não foi possível carregar as configurações de voz" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "Não foi possível abrir o terminal" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "Não foi possível reproduzir um clipe de teste" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "Não foi possível salvar a habilidade" msgid "Could not save that choice" msgstr "Não foi possível salvar essa opção" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "Não foi possível salvar esse modelo de fala" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "Não foi possível salvar essa voz" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "Não foi possível enviar o e-mail de redefinição" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "Não foi possível enviar" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "Não foi possível iniciar o OAuth" @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Desconectar" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Desconectando…" @@ -1989,18 +1941,6 @@ msgstr "Deixar {0} comigo" msgid "Hand to me" msgstr "Deixar comigo" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Desligar" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "" - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "" - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "" @@ -2019,14 +1959,6 @@ msgstr "Nome do Cabeçalho" msgid "Header value" msgstr "Valor do cabeçalho" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Ouvir uma amostra" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Olá, é assim que vou soar quando ler as respostas em voz alta." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Ocultar transcrição" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "Alto" @@ -2068,10 +1996,6 @@ msgstr "Como verificar" msgid "I’m done" msgstr "Eu terminei." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "Se você ouviu isso, a voz está pronta." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Área de envio de imagem" @@ -2241,10 +2165,6 @@ msgstr "Carregando Visualização…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Carregando provedores de voz..." - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Mensagem…" msgid "Messaged {peer}" msgstr "Enviou mensagem para {peer}" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Falha no microfone" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Mínimo" @@ -2480,10 +2396,6 @@ msgstr "Mova-os para a sua memória compartilhada." msgid "Move to" msgstr "Mover para" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Silenciar" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "Falha na conexão OAuth" msgid "OAuth expired" msgstr "" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "Em chamada com {0}" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Abrindo seu espaço de trabalho..." #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "Opcional" @@ -2831,18 +2737,10 @@ msgstr "Senha atualizada" msgid "Passwords do not match" msgstr "As senhas não coincidem" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Cole uma chave de substituição" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Cole o endereço compatível com OpenAI do seu servidor. Milo adiciona /v1 se necessário." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "Cole sua chave API" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "" msgid "Pin" msgstr "Fixar" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Reproduzindo" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Provedores" @@ -2911,10 +2804,6 @@ msgstr "Reagir" msgid "Reactions" msgstr "Reações" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Leia as respostas em voz alta" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "somente leitura" @@ -3076,10 +2965,6 @@ msgstr "Reabrir" msgid "Replace API key" msgstr "Substituir chave de API" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Substituir chave" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "Salvando..." msgid "Say hi" msgstr "Dizer oi" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Diga sim ou não, ou responda em uma frase." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Nome do servidor" msgid "Server URL" msgstr "URL do servidor" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Mostrar transcrição" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Padrão do espaço" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Falar" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Falar + transcrever" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Falar apenas" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Fale esta resposta" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Modelo de fala" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Começar a gravar" @@ -3571,10 +3427,6 @@ msgstr "Passos" msgid "Stop" msgstr "Parar" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Pare de Falar" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Parar de ensinar" @@ -3769,10 +3621,6 @@ msgstr "Fontes de ferramentas" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Transcrição" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Token Treg" @@ -3806,10 +3654,6 @@ msgstr "" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Reativar som" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Desafixar" @@ -3940,17 +3784,6 @@ msgstr "Visualização" msgid "View chat" msgstr "Ver conversa" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Voz" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Conversa por voz" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/ru/messages.po b/apps/web/src/locales/ru/messages.po index db7af83d..0c9e0ae9 100644 --- a/apps/web/src/locales/ru/messages.po +++ b/apps/web/src/locales/ru/messages.po @@ -193,10 +193,6 @@ msgstr "Токен доступа (необязательно)" msgid "Account" msgstr "Аккаунт" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Учетная запись по умолчанию" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "Ярлык аккаунта" @@ -437,7 +433,6 @@ msgstr "API вернулся, но обновление не завершило #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API-ключ" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "Закрыть настройки пользователя" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Закрыть настройки голоса" - #: src/components/AskCard.tsx msgid "Code" msgstr "Код" @@ -934,7 +924,6 @@ msgstr "Подтвердите пароль" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Подключить" @@ -979,7 +968,6 @@ msgstr "Подключите приложения" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Подключено" @@ -988,11 +976,6 @@ msgstr "Подключено" msgid "Connected · {0}" msgstr "Подключено · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "Подключено: {0}." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Подключено. Его инструменты доступны и #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Подключение…" @@ -1108,10 +1090,6 @@ msgstr "Не удалось подключиться" msgid "Could not connect this provider" msgstr "Не удалось подключить этого провайдера" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "Не удалось подключить этого голосового провайдера." - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "Не удалось подключиться к экрану компьютера" @@ -1177,10 +1155,6 @@ msgstr "Не удалось отключить OAuth" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "Не удалось отключить этого голосового провайдера." - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "Не удалось отклонить" @@ -1275,10 +1249,6 @@ msgstr "Не удалось загрузить этот файл." msgid "Could not load update status" msgstr "Не удалось загрузить статус обновления" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "Не удалось загрузить голосовые настройки." - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "Не удалось открыть локальные настройки msgid "Could not open terminal" msgstr "Не удалось открыть терминал" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "Не удалось воспроизвести тестовый клип." - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "Не удалось сохранить навык" msgid "Could not save that choice" msgstr "Не удалось сохранить этот выбор" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "Не удалось сохранить речевую модель" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "Не удалось сохранить этот голос" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "Не удалось выполнить поиск по каталогу" msgid "Could not send reset email" msgstr "Не удалось отправить электронное письмо для сброса" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "Не удалось отправить это" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "Не удалось запустить OAuth" @@ -1672,7 +1626,6 @@ msgstr "Прямой MCP" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Отключить" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Отключение…" @@ -1989,18 +1941,6 @@ msgstr "Передавать мне {0}" msgid "Hand to me" msgstr "Передать мне" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Завершить звонок" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "Сначала повесьте трубку, затем введите код на экране." - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "Повесьте трубку, затем введите код на экране." - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "заголовок" @@ -2019,14 +1959,6 @@ msgstr "Название заголовка" msgid "Header value" msgstr "Значение заголовка" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Прослушать образец" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Привет, вот как я буду звучать, когда буду читать ответы вслух." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "Скрыть ботов" @@ -2035,10 +1967,6 @@ msgstr "Скрыть ботов" msgid "Hide password" msgstr "Скрыть пароль" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Скрыть расшифровку" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "Высокий" @@ -2068,10 +1996,6 @@ msgstr "Как проверить" msgid "I’m done" msgstr "Готово" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "Если вы это услышали, голос готов." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Область загрузки изображения" @@ -2241,10 +2165,6 @@ msgstr "Загрузка предварительного просмотра…" msgid "Loading tools…" msgstr "Загрузка инструментов…" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Загрузка поставщиков голосовой связи…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Сообщение…" msgid "Messaged {peer}" msgstr "Отправлено сообщение {peer}" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Ошибка микрофона" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Минимальный" @@ -2480,10 +2396,6 @@ msgstr "Переместите их в свою общую память." msgid "Move to" msgstr "Переместить в" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Выключить микрофон" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "Соединение OAuth не удалось" msgid "OAuth expired" msgstr "Срок действия OAuth истек" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "Звонок с {0}" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "По расписанию" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Открытие вашего пространства…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "Необязательно" @@ -2831,18 +2737,10 @@ msgstr "Пароль обновлён" msgid "Passwords do not match" msgstr "Пароли не совпадают" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Вставьте запасной ключ" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Вставьте OpenAI-совместимый адрес со своего сервера. При необходимости Milo добавляет /v1." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "Вставьте свой ключ API" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "Приостановлено" msgid "Pin" msgstr "Закрепить" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Воспроизведение…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "ОТПРАВИТЬ в" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Провайдеры" @@ -2911,10 +2804,6 @@ msgstr "" msgid "Reactions" msgstr "" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Читать ответы вслух" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "только для чтения" @@ -3076,10 +2965,6 @@ msgstr "Открыть заново" msgid "Replace API key" msgstr "Заменить ключ API" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Заменить ключ" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "Сохранение…" msgid "Say hi" msgstr "Поздороваться" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Скажите «да» или «нет» или ответьте предложением." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Имя сервера" msgid "Server URL" msgstr "URL-адрес сервера" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "Показать пароль" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Показать расшифровку" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Пространство по умолчанию" msgid "Spaces" msgstr "Пространства" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Озвучить" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Озвучить + расшифровать" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Только озвучить" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Озвучить этот ответ" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Речевая модель" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Начать запись" @@ -3571,10 +3427,6 @@ msgstr "Шаги" msgid "Stop" msgstr "Остановить" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Остановить озвучивание" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Остановить обучение" @@ -3769,10 +3621,6 @@ msgstr "Источники инструментов" msgid "Tools" msgstr "Инструменты" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Расшифровка" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Токен Treg" @@ -3806,10 +3654,6 @@ msgstr "Недоступно" msgid "Uninstall" msgstr "Удалить" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Включить микрофон" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Открепить" @@ -3940,17 +3784,6 @@ msgstr "Вид" msgid "View chat" msgstr "Открыть чат" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Голос" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Голосовой чат" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/tr/messages.po b/apps/web/src/locales/tr/messages.po index de7b452a..5213d2fd 100644 --- a/apps/web/src/locales/tr/messages.po +++ b/apps/web/src/locales/tr/messages.po @@ -193,10 +193,6 @@ msgstr "Erişim token'ı (isteğe bağlı)" msgid "Account" msgstr "Hesap" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "Hesap varsayılanı" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "" #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API anahtarı" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "Kullanıcı ayarlarını kapat" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "Ses ayarlarını kapat" - #: src/components/AskCard.tsx msgid "Code" msgstr "Kod" @@ -934,7 +924,6 @@ msgstr "Parolayı doğrulayın" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "Bağlan" @@ -979,7 +968,6 @@ msgstr "Uygulamalarını bağla" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "Bağlandı" @@ -988,11 +976,6 @@ msgstr "Bağlandı" msgid "Connected · {0}" msgstr "Bağlı · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "{0} bağlandı." - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "Bağlandı. Araçları bir sonraki mesajından itibaren kullanılabilir. #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "Bağlanıyor…" @@ -1108,10 +1090,6 @@ msgstr "Bağlanılamadı" msgid "Could not connect this provider" msgstr "Bu sağlayıcı bağlanamadı" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "Bu ses sağlayıcısı bağlanamadı" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "" @@ -1177,10 +1155,6 @@ msgstr "OAuth bağlantısı kesilemedi" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "Bu ses sağlayıcısının bağlantısı kesilemedi" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "Bu dosya yüklenemedi." msgid "Could not load update status" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "Ses ayarları yüklenemedi" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "Terminal açılamadı" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "Deneme sesi çalınamadı" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "Beceri kaydedilemedi" msgid "Could not save that choice" msgstr "Bu seçim kaydedilemedi" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "Bu konuşma modeli kaydedilemedi" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "Bu ses kaydedilemedi" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "Sıfırlama e-postası gönderilemedi" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "Gönderilemedi" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "OAuth başlatılamadı" @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "Bağlantıyı kes" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "Bağlantı kesiliyor…" @@ -1989,18 +1941,6 @@ msgstr "{0} işlemlerini bana bırak" msgid "Hand to me" msgstr "Bana bırak" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "Aramayı sonlandır" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "" - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "" - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "" @@ -2019,14 +1959,6 @@ msgstr "Üstbilgi adı" msgid "Header value" msgstr "Üstbilgi değeri" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "Örnek dinle" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "Merhaba, yanıtları sesli okuduğumda böyle duyulacağım." - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "Dökümü gizle" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "Yüksek" @@ -2068,10 +1996,6 @@ msgstr "Nasıl kontrol edilir" msgid "I’m done" msgstr "Bitirdim" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "Bunu duyduysan ses hazır." - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "Görüntü yükleme alanı" @@ -2241,10 +2165,6 @@ msgstr "Önizleme yükleniyor…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "Ses sağlayıcıları yükleniyor…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "Mesaj…" msgid "Messaged {peer}" msgstr "{peer} botuna mesaj gönderildi" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "Mikrofon hatası" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "Minimal" @@ -2480,10 +2396,6 @@ msgstr "Bunları ortak hafızana taşı." msgid "Move to" msgstr "Taşı" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "Sesi kapat" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "OAuth bağlantısı başarısız" msgid "OAuth expired" msgstr "" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "{0} ile görüşmede" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "Çalışma alanın açılıyor…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "İsteğe bağlı" @@ -2831,18 +2737,10 @@ msgstr "Parola güncellendi" msgid "Passwords do not match" msgstr "Parolalar eşleşmiyor" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "Yeni bir anahtar yapıştır" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "Sunucundaki OpenAI uyumlu adresi yapıştır. Gerekirse Milo /v1 ekler." -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "API anahtarını yapıştır" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "" msgid "Pin" msgstr "Sabitle" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "Çalınıyor…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "Sağlayıcılar" @@ -2911,10 +2804,6 @@ msgstr "Tepki ver" msgid "Reactions" msgstr "Tepkiler" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "Yanıtları sesli oku" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "salt okunur" @@ -3076,10 +2965,6 @@ msgstr "Yeniden aç" msgid "Replace API key" msgstr "API anahtarını değiştir" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "Anahtarı değiştir" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "Kaydediliyor…" msgid "Say hi" msgstr "Merhaba de" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "Evet ya da hayır de veya bir cümleyle yanıtla." - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "Sunucu adı" msgid "Server URL" msgstr "Sunucu URL'si" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "Dökümü göster" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "Alan varsayılanı" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "Seslendir" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "Seslendir + yazıya dök" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "Yalnızca seslendir" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "Bu yanıtı seslendir" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "Konuşma modeli" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "Kaydı başlat" @@ -3571,10 +3427,6 @@ msgstr "Adımlar" msgid "Stop" msgstr "Durdur" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "Seslendirmeyi durdur" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "Öğretmeyi durdur" @@ -3769,10 +3621,6 @@ msgstr "Araç kaynakları" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "Döküm" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Treg token'ı" @@ -3806,10 +3654,6 @@ msgstr "" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "Sesi aç" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "Sabitlemeyi kaldır" @@ -3940,17 +3784,6 @@ msgstr "Görünüm" msgid "View chat" msgstr "Sohbeti görüntüle" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "Ses" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "Sesli sohbet" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/locales/zh-CN/messages.po b/apps/web/src/locales/zh-CN/messages.po index b016c657..1c4743b9 100644 --- a/apps/web/src/locales/zh-CN/messages.po +++ b/apps/web/src/locales/zh-CN/messages.po @@ -193,10 +193,6 @@ msgstr "访问令牌(可选)" msgid "Account" msgstr "账户" -#: src/pages/shell/bot-panel.tsx -msgid "Account default" -msgstr "账户默认" - #: src/pages/PluginsOverlay.tsx msgid "Account label" msgstr "" @@ -437,7 +433,6 @@ msgstr "API 已恢复,但更新未完成。请查看宿主日志。" #: src/components/integrations/IntegrationSetup.tsx #: src/lib/localized-provider-hint.ts #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "API key" msgstr "API 密钥" @@ -841,11 +836,6 @@ msgstr "" msgid "Close user settings" msgstr "关闭用户设置" -#: src/pages/SettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Close voice settings" -msgstr "关闭语音设置" - #: src/components/AskCard.tsx msgid "Code" msgstr "代码" @@ -934,7 +924,6 @@ msgstr "确认密码" #: src/components/integrations/IntegrationSetup.tsx #: src/pages/OnboardingApps.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connect" msgstr "连接" @@ -979,7 +968,6 @@ msgstr "连接你的应用" #: src/pages/ModelSettingsOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connected" msgstr "已连接" @@ -988,11 +976,6 @@ msgstr "已连接" msgid "Connected · {0}" msgstr "已连接 · {0}" -#. placeholder {0}: selected.name -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Connected {0}." -msgstr "已连接 {0}。" - #. placeholder {0}: selected.label #. placeholder {0}: selectedLabelRef.current ?? "this model" #: src/pages/ModelSettingsOverlay.tsx @@ -1007,7 +990,6 @@ msgstr "已连接,下一条消息起即可使用其工具。" #: src/pages/McpServersOverlay.tsx #: src/pages/OnboardingApps.tsx #: src/pages/shell/message-cards.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Connecting…" msgstr "正在连接…" @@ -1108,10 +1090,6 @@ msgstr "无法连接" msgid "Could not connect this provider" msgstr "无法连接此提供方" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not connect this voice provider" -msgstr "无法连接此语音提供方" - #: src/pages/Shell.tsx msgid "Could not connect to the computer screen" msgstr "" @@ -1177,10 +1155,6 @@ msgstr "无法断开 OAuth" msgid "Could not disconnect this provider" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not disconnect this voice provider" -msgstr "无法断开此语音提供方" - #: src/pages/shell/message-cards.tsx msgid "Could not dismiss" msgstr "" @@ -1275,10 +1249,6 @@ msgstr "无法加载此文件。" msgid "Could not load update status" msgstr "无法加载更新状态" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not load voice settings" -msgstr "无法加载语音设置" - #: src/components/computer/FilesApp.tsx msgid "Could not open file" msgstr "" @@ -1291,10 +1261,6 @@ msgstr "" msgid "Could not open terminal" msgstr "无法打开终端" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not play a test clip" -msgstr "无法播放测试片段" - #: src/pages/AccountSettingsOverlay.tsx #: src/pages/Auth.tsx msgid "Could not reach the server" @@ -1383,14 +1349,6 @@ msgstr "无法保存技能" msgid "Could not save that choice" msgstr "无法保存该选择" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that speech model" -msgstr "无法保存该语音模型" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Could not save that voice" -msgstr "无法保存该语音" - #: src/pages/shell/bot-credentials.tsx msgid "Could not save the credential" msgstr "" @@ -1407,10 +1365,6 @@ msgstr "" msgid "Could not send reset email" msgstr "无法发送重置邮件" -#: src/lib/call-session.ts -msgid "Could not send that" -msgstr "无法发送" - #: src/pages/McpServersOverlay.tsx msgid "Could not start OAuth" msgstr "无法开始 OAuth" @@ -1672,7 +1626,6 @@ msgstr "" #: src/pages/McpServersOverlay.tsx #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnect" msgstr "断开" @@ -1686,7 +1639,6 @@ msgid "Disconnected {0}." msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Disconnecting…" msgstr "正在断开…" @@ -1989,18 +1941,6 @@ msgstr "将 {0} 交给我" msgid "Hand to me" msgstr "交给我" -#: src/components/call/CallCard.tsx -msgid "Hang up" -msgstr "挂断" - -#: src/lib/call-session.ts -msgid "Hang up first, then enter the code on screen." -msgstr "请先挂断,然后输入屏幕上的代码。" - -#: src/lib/call-session.ts -msgid "Hang up, then enter the code on screen." -msgstr "请挂断,然后输入屏幕上的代码。" - #: src/pages/RoutineEditor.tsx msgid "header" msgstr "请求头" @@ -2019,14 +1959,6 @@ msgstr "请求头名称" msgid "Header value" msgstr "请求头值" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hear a sample" -msgstr "试听" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Hi, this is how I'll sound when I read replies out loud." -msgstr "你好,这是我朗读回复时的声音。" - #: src/pages/Shell.tsx msgid "Hide bots" msgstr "" @@ -2035,10 +1967,6 @@ msgstr "" msgid "Hide password" msgstr "隐藏密码" -#: src/components/call/VoiceChatCard.tsx -msgid "Hide transcript" -msgstr "隐藏文字记录" - #: src/pages/ModelSettingsOverlay.tsx msgid "High" msgstr "高" @@ -2068,10 +1996,6 @@ msgstr "如何检查" msgid "I’m done" msgstr "我做完了" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "If you heard that, voice is ready." -msgstr "如果听到了,说明语音已就绪。" - #: src/pages/shell/avatar-studio-popover.tsx msgid "Image upload area" msgstr "图片上传区域" @@ -2241,10 +2165,6 @@ msgstr "正在加载预览…" msgid "Loading tools…" msgstr "" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Loading voice providers…" -msgstr "正在加载语音提供方…" - #: src/App.tsx #: src/pages/Artifacts.tsx #: src/pages/IntegrationSetup.tsx @@ -2396,10 +2316,6 @@ msgstr "消息…" msgid "Messaged {peer}" msgstr "已发给 {peer}" -#: src/lib/call-session.ts -msgid "Microphone failed" -msgstr "麦克风失败" - #: src/pages/ModelSettingsOverlay.tsx msgid "Minimal" msgstr "最低" @@ -2480,10 +2396,6 @@ msgstr "把它们移到共享记忆。" msgid "Move to" msgstr "移动到" -#: src/components/call/CallCard.tsx -msgid "Mute" -msgstr "静音" - #: src/components/teach/SkillDraftCard.tsx #: src/pages/Artifacts.tsx #: src/pages/Auth.tsx @@ -2707,11 +2619,6 @@ msgstr "OAuth 连接失败" msgid "OAuth expired" msgstr "" -#. placeholder {0}: call.botName -#: src/components/call/CallCard.tsx -msgid "On a call with {0}" -msgstr "正在与 {0} 通话" - #: src/pages/RoutineEditor.tsx msgid "On a schedule" msgstr "按计划" @@ -2782,7 +2689,6 @@ msgid "Opening your Space…" msgstr "正在打开工作区…" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Optional" msgstr "可选" @@ -2831,18 +2737,10 @@ msgstr "密码已更新" msgid "Passwords do not match" msgstr "两次密码不一致" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste a replacement key" -msgstr "粘贴替换密钥" - #: src/pages/ModelSettingsOverlay.tsx msgid "Paste the OpenAI-compatible address from your server. Milo adds /v1 if needed." msgstr "粘贴服务器的 OpenAI 兼容地址。需要时 Milo 会补上 /v1。" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Paste your API key" -msgstr "粘贴你的 API 密钥" - #: src/pages/RoutineEditor.tsx #: src/pages/Routines.tsx msgid "Paused" @@ -2852,10 +2750,6 @@ msgstr "已暂停" msgid "Pin" msgstr "置顶" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Playing…" -msgstr "播放中…" - #: src/pages/RoutineEditor.tsx msgid "POST to" msgstr "POST 到" @@ -2887,7 +2781,6 @@ msgid "Protected input" msgstr "" #: src/pages/ModelSettingsOverlay.tsx -#: src/pages/VoiceSettingsOverlay.tsx msgid "Providers" msgstr "提供方" @@ -2911,10 +2804,6 @@ msgstr "回应" msgid "Reactions" msgstr "表情回应" -#: src/pages/shell/bot-panel.tsx -msgid "Read replies aloud" -msgstr "朗读回复" - #: src/pages/KnowledgeSection.tsx msgid "read-only" msgstr "只读" @@ -3076,10 +2965,6 @@ msgstr "重新打开" msgid "Replace API key" msgstr "替换 API 密钥" -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Replace key" -msgstr "替换密钥" - #: src/pages/shell/bot-credentials.tsx msgid "Replace value" msgstr "" @@ -3294,10 +3179,6 @@ msgstr "正在保存…" msgid "Say hi" msgstr "打个招呼" -#: src/lib/call-session.ts -msgid "Say yes or no, or answer in a sentence." -msgstr "回答是或否,或一句话说明。" - #: src/pages/ModelSettingsOverlay.tsx #: src/pages/PluginsOverlay.tsx #: src/pages/Shell.tsx @@ -3384,7 +3265,6 @@ msgstr "服务器名称" msgid "Server URL" msgstr "服务器 URL" -#: src/components/call/CallCard.tsx #: src/pages/SettingsOverlay.tsx #: src/pages/Shell.tsx #: src/pages/shell/bot-profile.tsx @@ -3442,10 +3322,6 @@ msgstr "显示密码" msgid "Show tool activity" msgstr "" -#: src/components/call/VoiceChatCard.tsx -msgid "Show transcript" -msgstr "显示文字记录" - #: src/lib/localized-provider-hint.ts #: src/pages/Auth.tsx #: src/pages/ModelSettingsOverlay.tsx @@ -3528,26 +3404,6 @@ msgstr "工作区默认" msgid "Spaces" msgstr "" -#: src/pages/Shell.tsx -msgid "Speak" -msgstr "朗读" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak + transcribe" -msgstr "朗读 + 转写" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speak only" -msgstr "仅朗读" - -#: src/pages/Shell.tsx -msgid "Speak this reply" -msgstr "朗读这条回复" - -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Speech model" -msgstr "语音模型" - #: src/components/teach/TeachComputerOverlay.tsx msgid "Start recording" msgstr "开始录制" @@ -3571,10 +3427,6 @@ msgstr "步骤" msgid "Stop" msgstr "停止" -#: src/pages/Shell.tsx -msgid "Stop speaking" -msgstr "停止朗读" - #: src/components/teach/TeachRecordingChrome.tsx msgid "Stop teaching" msgstr "停止示范" @@ -3769,10 +3621,6 @@ msgstr "工具源" msgid "Tools" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Transcript" -msgstr "文字记录" - #: src/pages/PluginsOverlay.tsx msgid "Treg token" msgstr "Treg token" @@ -3806,10 +3654,6 @@ msgstr "不可用" msgid "Uninstall" msgstr "" -#: src/components/call/CallCard.tsx -msgid "Unmute" -msgstr "取消静音" - #: src/pages/BotContextMenu.tsx msgid "Unpin" msgstr "取消置顶" @@ -3940,17 +3784,6 @@ msgstr "视图" msgid "View chat" msgstr "查看聊天" -#: src/pages/SettingsOverlay.tsx -#: src/pages/Shell.tsx -#: src/pages/shell/bot-panel.tsx -#: src/pages/VoiceSettingsOverlay.tsx -msgid "Voice" -msgstr "语音" - -#: src/components/call/VoiceChatCard.tsx -msgid "Voice chat" -msgstr "语音聊天" - #: src/components/UsageLimitNotice.tsx #: src/pages/Auth.tsx #: src/pages/OnboardingAgent.tsx diff --git a/apps/web/src/pages/SettingsOverlay.test.tsx b/apps/web/src/pages/SettingsOverlay.test.tsx index 84bbef01..204476af 100644 --- a/apps/web/src/pages/SettingsOverlay.test.tsx +++ b/apps/web/src/pages/SettingsOverlay.test.tsx @@ -35,7 +35,6 @@ vi.mock("./AccountSettingsOverlay", () => ({ UpdatesSettingsPanel: () => null, })); vi.mock("./AgentModelsPanel", () => ({ AgentModelsPanel: () => null })); -vi.mock("./VoiceSettingsOverlay", () => ({ VoiceSettingsOverlay: () => null })); import { SettingsOverlay } from "./SettingsOverlay"; @@ -64,7 +63,7 @@ async function navIds() { ); await act(async () => root.unmount()); container.remove(); - return ids.filter((id) => id !== "voice"); + return ids; } it("lists Usage, General, Allow list and Updates in the desktop app", async () => { diff --git a/apps/web/src/pages/SettingsOverlay.tsx b/apps/web/src/pages/SettingsOverlay.tsx index 3fc380a6..e1a41527 100644 --- a/apps/web/src/pages/SettingsOverlay.tsx +++ b/apps/web/src/pages/SettingsOverlay.tsx @@ -1,15 +1,14 @@ import { useLingui } from "@lingui/react/macro"; import type { AvatarStyle } from "@milo/contracts"; import { Button, Dialog, DialogClose, DialogContent, DialogTitle } from "@milo/ui-web"; -import { CloudDownload, Gauge, Settings, ShieldCheck, Volume2, XIcon } from "lucide-react"; +import { CloudDownload, Gauge, Settings, ShieldCheck, XIcon } from "lucide-react"; import { type ComponentType, useEffect, useRef, useState } from "react"; import { ApprovalRulesSettings } from "../components/ApprovalRulesSettings"; import { desktopBridge } from "../lib/desktop"; import { GeneralSettingsPanels, UpdatesSettingsPanel } from "./AccountSettingsOverlay"; import { AgentModelsPanel } from "./AgentModelsPanel"; -import { VoiceSettingsOverlay } from "./VoiceSettingsOverlay"; -export type SettingsSection = "general" | "usage" | "approvals" | "voice" | "updates"; +export type SettingsSection = "general" | "usage" | "approvals" | "updates"; type NavItem = { id: SettingsSection; @@ -25,7 +24,6 @@ export function SettingsOverlay({ onAvatarStyleChange, initialSection = "general", onClose, - onVoiceStatusMaybeChanged, }: { email?: string | null; name: string; @@ -33,7 +31,6 @@ export function SettingsOverlay({ onAvatarStyleChange: (style: AvatarStyle) => Promise; initialSection?: SettingsSection; onClose: () => void; - onVoiceStatusMaybeChanged?: () => void | Promise; // Still passed by the shell; nothing in v0 settings reads them. usage?: { runs: number; inputTokens: number; outputTokens: number } | null; isDeploymentOwner?: boolean; @@ -45,10 +42,8 @@ export function SettingsOverlay({ const panelRef = useRef(null); const usageRef = useRef(null); const [section, setSection] = useState(initialSection); - const [voiceBusy, setVoiceBusy] = useState(false); // The desktop app updates itself; a browser has nothing to update here. const showUpdates = Boolean(desktopBridge()?.update); - const panelBusy = voiceBusy; useEffect(() => { setSection(initialSection); @@ -64,7 +59,6 @@ export function SettingsOverlay({ { id: "usage", label: t`Usage`, icon: Gauge }, { id: "general", label: t`General`, icon: Settings }, { id: "approvals", label: t`Allow list`, icon: ShieldCheck }, - { id: "voice", label: t`Voice`, icon: Volume2 }, ...(showUpdates ? [{ id: "updates" as const, label: t`Updates`, icon: CloudDownload }] : []), ]; @@ -72,38 +66,14 @@ export function SettingsOverlay({ navItems.find((item) => item.id === section)?.label ?? (section === "general" ? t`General` : t`Settings`); - const closeLabel = - section === "usage" - ? t`Close usage settings` - : section === "voice" - ? t`Close voice settings` - : t`Close user settings`; - - async function refreshVoiceStatus() { - await onVoiceStatusMaybeChanged?.(); - } - - function leaveSettings(next: () => void) { - if (panelBusy) return; - void refreshVoiceStatus().finally(next); - } - - function requestClose() { - leaveSettings(onClose); - } - - const widePane = section === "voice"; + const closeLabel = section === "usage" ? t`Close usage settings` : t`Close user settings`; return ( { + onOpenChange={(open) => { if (open) return; - if (panelBusy) { - details.cancel(); - return; - } - requestClose(); + onClose(); }} > section === "usage" ? (usageRef.current ?? panelRef.current) : panelRef.current } - className={`flex max-h-[calc(100%-2rem)] flex-col gap-0 overflow-hidden rounded-2xl p-0 sm:max-h-[calc(100%-5rem)] ${ - widePane - ? "h-[min(760px,calc(100%-2rem))] w-[min(1080px,calc(100%-2rem))] sm:max-w-[1080px]" - : "h-[min(720px,calc(100%-2rem))] w-[min(920px,calc(100%-2rem))] sm:max-w-[920px]" - }`} + className="flex h-[min(720px,calc(100%-2rem))] max-h-[calc(100%-2rem)] w-[min(920px,calc(100%-2rem))] flex-col gap-0 overflow-hidden rounded-2xl p-0 sm:max-h-[calc(100%-5rem)] sm:max-w-[920px]" >
-
+
{section === "general" ? ( : null} {section === "updates" && showUpdates ? : null} - {section === "voice" ? ( - - ) : null}
diff --git a/apps/web/src/pages/Shell.tsx b/apps/web/src/pages/Shell.tsx index eb5e9fd4..cc9ad76c 100644 --- a/apps/web/src/pages/Shell.tsx +++ b/apps/web/src/pages/Shell.tsx @@ -19,7 +19,6 @@ import type { TaughtSkill, ThreadMessage, ThreadSnapshot, - VoiceStatus, } from "@milo/contracts"; import { ATTACHMENT_ALLOWED_MIME_TYPES, @@ -37,7 +36,6 @@ import { type ComposerMention, clampMentionHighlightIndex, groupBotsForSidebar, - groupVoiceChats, inferAttachmentMimeType, isActive, isPeerReceiptBlocks, @@ -58,7 +56,6 @@ import { type SlashActionId, searchHitThreadTarget, serializeComposerPrompt, - speechFromBlocks, truncateSlashDescription, userVisibleMessages, withLiveStreamingProgress, @@ -85,7 +82,6 @@ import { import { ArrowDown, ArrowUp, - AudioLines, Bell, Box, ChevronDown, @@ -146,8 +142,6 @@ import { computersAreUnavailable, } from "../components/ComputersUnavailableHint"; import { ComputerUpdateProgress } from "../components/ComputerUpdateProgress"; -import { CallCard } from "../components/call/CallCard"; -import { VoiceChatCard } from "../components/call/VoiceChatCard"; import { BOT_BUBBLE_CLASS, USER_BUBBLE_CLASS } from "../components/chat-bubble"; import { ComputerWorkspace } from "../components/computer/ComputerWorkspace"; import { MessageHoverMetadata } from "../components/MessageHoverMetadata"; @@ -180,7 +174,6 @@ import { rosterNotices, shouldNotifyBrowser, } from "../lib/browser-notifications"; -import { startCall, useCallSession } from "../lib/call-session"; import { newClientId } from "../lib/client-id"; import { embeddableScreenUrl, @@ -239,7 +232,6 @@ import { transcriptIsNearEnd, transcriptMovedDown, } from "../lib/transcript-scroll"; -import { speaker } from "../lib/tts"; import { ActivityList } from "./ActivityList"; import type { ContextMenuPosition } from "./BotContextMenu"; import { CreateGroupForm, GroupSettings, memberName } from "./GroupPanel"; @@ -323,8 +315,6 @@ const ATTACHMENT_ACCEPT = ATTACHMENT_ALLOWED_MIME_TYPES.join(","); /** Identity colour for bots the roster no longer knows about. */ const FALLBACK_BOT_COLOR = "#85858A"; const THREAD_SNAPSHOT_TIMEOUT_MS = 2_000; -/** Bound Settings leave so a hung voice status refresh cannot block dismissal. */ -const VOICE_STATUS_REFRESH_TIMEOUT_MS = 10_000; const MOBILE_SIDEBAR_SWIPE_EDGE_PX = 32; const MOBILE_SIDEBAR_SWIPE_DISTANCE_PX = 56; @@ -332,14 +322,6 @@ function threadSnapshotSignal(parent: AbortSignal): AbortSignal { return AbortSignal.any([parent, AbortSignal.timeout(THREAD_SNAPSHOT_TIMEOUT_MS)]); } -function voiceStatusRefreshTimeout(): Promise { - return new Promise((_, reject) => { - AbortSignal.timeout(VOICE_STATUS_REFRESH_TIMEOUT_MS).addEventListener("abort", () => { - reject(new DOMException("Voice status refresh timed out", "TimeoutError")); - }); - }); -} - const SIDEBAR_NAV_ROW_CLASS = "flex min-h-9 w-full items-center gap-2.5 rounded-[10px] px-2.5 py-2 text-start text-muted-foreground hover:bg-foreground/5 hover:text-foreground"; const SIDEBAR_NAV_ROW_CURRENT_CLASS = "bg-foreground/5 text-foreground"; @@ -551,9 +533,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { const [mcpOpen, setMcpOpen] = useState(false); const [settingsOpen, setSettingsOpen] = useState(false); const [settingsSection, setSettingsSection] = useState("general"); - const call = useCallSession(); - const [voiceStatus, setVoiceStatus] = useState(null); - const [speakingMessageId, setSpeakingMessageId] = useState(null); const [menuOpen, setMenuOpen] = useState(false); const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false); const mobileSidebarSwipeRef = useRef<{ startX: number; startY: number } | null>(null); @@ -720,8 +699,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { const pendingBrowserNotifications = useRef(new Map()); const computerVisible = useRef(false); computerVisible.current = panel === "computer" || computerOpen; - const autoSpoken = useRef(null); - const autoSpokenBotId = useRef(null); const inGroup = Boolean(groupId); const active = inGroup || view ? undefined : (bots.find((b) => b.id === botId) ?? bots[0]); @@ -1252,46 +1229,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { .catch(() => undefined); }, []); - useEffect(() => { - void rpc.voice - .status() - .then(setVoiceStatus) - .catch(() => undefined); - const unsubSpeech = speaker.subscribe((state) => { - setSpeakingMessageId(state.status === "idle" ? null : (state.messageId ?? null)); - }); - return () => { - unsubSpeech(); - }; - }, []); - - useEffect(() => { - if (!active || !snapshot || snapshot.botId !== active.id) return; - const lastBot = [...snapshot.messages].reverse().find((message) => message.role === "bot"); - if (autoSpokenBotId.current !== active.id) { - autoSpokenBotId.current = active.id; - autoSpoken.current = lastBot?.id ?? null; - return; - } - if (call?.botId === active.id || !active.autoSpeak) { - autoSpoken.current = lastBot?.id ?? null; - return; - } - if (snapshot.run && ["running", "queued", "leased"].includes(snapshot.run.status)) return; - if (!lastBot || lastBot.id === autoSpoken.current) return; - const text = speechFromBlocks(lastBot.blocks); - if (!text) return; - autoSpoken.current = lastBot.id; - void speaker.speak(text, { botId: active.id, messageId: lastBot.id }); - }, [ - snapshot?.messages, - snapshot?.run?.status, - snapshot?.botId, - active?.autoSpeak, - active?.id, - call?.botId, - ]); - useEffect(() => { if (!active) return; // Opening a bot clears the manual unread flag so it can auto-read again. @@ -1591,7 +1528,7 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { (spaceId: string, path: string) => { setMobileSidebarOpen(false); const previousSpaceId = selectedSpaceId(); - // Persist the active space (including primary) so voice/RPC headers match the chat. + // Persist the active space (including primary) so RPC headers match the chat. const selectionStored = selectSpace(spaceId); if (!selectionStored) return; const previousEffective = previousSpaceId ?? bootstrapMe?.spaceId; @@ -2357,18 +2294,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { setEditingRoutine(null); setPanel("routine"); }, []); - const speakingMessageIdRef = useRef(speakingMessageId); - speakingMessageIdRef.current = speakingMessageId; - const speakMessage = useCallback((message: ThreadMessage) => { - if (speakingMessageIdRef.current === message.id) { - speaker.stop(); - return; - } - const text = speechFromBlocks(message.blocks); - const id = message.botId ?? activeBotId.current; - if (text && id) void speaker.speak(text, { botId: id, messageId: message.id }); - }, []); - async function createGroup(input: { name: string; botIds: string[] }) { const group = await rpc.groups.create(input); setGroups((current) => @@ -3699,9 +3624,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { onRefresh={refreshActiveThread} onBotChanged={refreshBots} onAddRoutine={addSkillRoutine} - voiceReady={Boolean(voiceStatus?.ready)} - speakingMessageId={speakingMessageId} - onSpeak={speakMessage} onOpenComputer={onOpenComputer} /> )} @@ -3727,22 +3649,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { onRemoveAttachment={removeAttachment} onSend={sendMessage} onStop={stopRun} - onVoice={ - !inGroup && active - ? () => { - if (!voiceStatus?.ready) { - openSettings("voice"); - return; - } - startCall({ - botId: active.id, - botName: active.name, - botColor: active.color, - transcribe: Boolean(voiceStatus?.transcribe), - }); - } - : undefined - } replyTarget={activeReplyTarget} replyQuote={activeReplyQuote} replyTargetName={replyTargetName} @@ -3772,8 +3678,6 @@ export function ShellPage({ view }: { view?: ShellView } = {}) { )} - openSettings("voice")} /> - {panel === "create" ? ( { - try { - setVoiceStatus( - await Promise.race([rpc.voice.status(), voiceStatusRefreshTimeout()]), - ); - } catch { - // Prefer reopening Voice settings over starting a call with stale readiness. - setVoiceStatus(null); - } - }} onClose={() => { setSettingsOpen(false); setSettingsSection("general"); @@ -4671,9 +4565,6 @@ const Transcript = memo(function Transcript({ onRefresh, onBotChanged, onAddRoutine, - voiceReady, - speakingMessageId, - onSpeak, onOpenComputer, }: { scrollRef: RefObject; @@ -4700,9 +4591,6 @@ const Transcript = memo(function Transcript({ onRefresh: () => Promise; onBotChanged: () => Promise; onAddRoutine: (name: string, prompt: string) => void; - voiceReady: boolean; - speakingMessageId: string | null; - onSpeak: (message: ThreadMessage) => void; onOpenComputer: (botId?: string) => void; }) { const { t } = useLingui(); @@ -4961,17 +4849,7 @@ const Transcript = memo(function Transcript({ {loadingOlder ? t`Loading…` : t`Load earlier messages`} ) : null} - {groupVoiceChats(reactionView.visibleMessages).map((item) => { - if (item.kind === "voiceChat") { - return ( - - ); - } - const message = item.message; + {reactionView.visibleMessages.map((message) => { if (!messageHasVisibleBlocks(message.blocks, showToolActivity)) return null; const peerReceipt = isPeerReceiptBlocks(message.blocks); const messageReactions = reactionView.reactions.get(message.id); @@ -5041,9 +4919,6 @@ const Transcript = memo(function Transcript({ onRefresh={onRefresh} onBotChanged={onBotChanged} onAddRoutine={onAddRoutine} - voiceReady={voiceReady} - speaking={speakingMessageId === message.id} - onSpeak={() => onSpeak(message)} onOpenComputer={onOpenComputer} showToolActivity={showToolActivity} /> @@ -5207,7 +5082,6 @@ const Composer = memo(function Composer({ onRemoveAttachment, onSend, onStop, - onVoice, replyTarget, replyQuote, replyTargetName, @@ -5232,7 +5106,6 @@ const Composer = memo(function Composer({ onRemoveAttachment: (attachment: PendingAttachment) => void; onSend: (text: string, mentions?: ComposerMention[]) => Promise; onStop: () => Promise; - onVoice?: () => void; replyTarget?: ThreadMessage | null; replyQuote?: string | null; replyTargetName?: string; @@ -5832,19 +5705,6 @@ const Composer = memo(function Composer({ - {onVoice && draft.trim().length === 0 ? ( - - ) : null} {running ? (
- ) : null}
@@ -6518,16 +6362,6 @@ const MessageView = memo(function MessageView({
{block.text}
- {voiceReady ? ( - - ) : null} ); diff --git a/apps/web/src/pages/VoiceSettingsOverlay.test.tsx b/apps/web/src/pages/VoiceSettingsOverlay.test.tsx deleted file mode 100644 index 5cd786cc..00000000 --- a/apps/web/src/pages/VoiceSettingsOverlay.test.tsx +++ /dev/null @@ -1,155 +0,0 @@ -// @vitest-environment jsdom - -import type { ComponentProps, ReactNode } from "react"; -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { expect, it, vi } from "vitest"; - -const voice = vi.hoisted(() => ({ - catalog: vi.fn(), - credentials: vi.fn(), - status: vi.fn(), - voices: vi.fn(), - connect: vi.fn(), - disconnect: vi.fn(), - setVoice: vi.fn(), - setSpeechModel: vi.fn(), -})); - -vi.mock("../lib/rpc", () => ({ rpc: { voice } })); -vi.mock("@lingui/react/macro", () => { - const t = (parts: TemplateStringsArray) => parts.join(""); - return { useLingui: () => ({ t }), Trans: ({ children }: { children: ReactNode }) => children }; -}); -vi.mock("@milo/ui-web", () => { - const Container = ({ children }: { children?: ReactNode }) =>
{children}
; - return { - Button: ({ - variant: _variant, - size: _size, - ...props - }: ComponentProps<"button"> & { variant?: string; size?: string }) => - {credential ? ( - - ) : null} - - {credential ? ( - <> - - - Voice - - void chooseVoice(event.target.value)} - > - {voiceOptions.map((voice) => ( - - {voice.label} - {voice.description ? ` · ${voice.description}` : ""} - - ))} - - - {selected.id === "fish-audio" ? ( - - - Speech model - - setSpeechModel(event.target.value)} - onBlur={() => void saveSpeechModel()} - onKeyDown={(event) => { - if (event.key !== "Enter") return; - event.preventDefault(); - event.currentTarget.blur(); - }} - /> - - ) : null} - - - ) : null} - - ) : null} - - - - ); - - if (embedded) { - return ( -
- {body} -
- ); - } - - return ( - { - if (open) return; - if (busy) { - details.cancel(); - return; - } - onClose(); - }} - > - - {body} - - - ); -} diff --git a/apps/web/src/pages/shell/bot-panel.test.tsx b/apps/web/src/pages/shell/bot-panel.test.tsx index e7d5f3c2..f5adb7e1 100644 --- a/apps/web/src/pages/shell/bot-panel.test.tsx +++ b/apps/web/src/pages/shell/bot-panel.test.tsx @@ -9,7 +9,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("../../lib/rpc", () => ({ rpc: { - voice: { voices: vi.fn().mockResolvedValue([]) }, models: { credentials: vi.fn().mockResolvedValue([]), list: vi.fn().mockResolvedValue([]), @@ -89,8 +88,6 @@ function bot(description = "Billing", notifyOnFinish = true): Bot { computerMode: "team", updatedAt: "2026-09-01T00:00:00.000Z", createdAt: "2026-09-01T00:00:00.000Z", - voiceId: null, - autoSpeak: false, modelProvider: null, modelId: null, thinkingLevel: null, diff --git a/apps/web/src/pages/shell/bot-panel.tsx b/apps/web/src/pages/shell/bot-panel.tsx index d8ae9cdc..abeb2289 100644 --- a/apps/web/src/pages/shell/bot-panel.tsx +++ b/apps/web/src/pages/shell/bot-panel.tsx @@ -7,7 +7,6 @@ import type { ModelCatalogEntry, ModelCredential, ThinkingLevel, - VoiceInfo, } from "@milo/contracts"; import { BOT_DESCRIPTION_MAX_LENGTH, @@ -23,7 +22,6 @@ import { Textarea, Toggle, } from "@milo/ui-web"; -import { X } from "lucide-react"; import { lazy, Suspense, useEffect, useId, useRef, useState } from "react"; import { botProfilePatch } from "../../lib/bot-profile-patch"; import { thinkingLevelLabel } from "../../lib/model-catalog"; @@ -93,8 +91,6 @@ export function BotSettings({ color?: string; notifyOnFinish?: boolean; computerMode: ComputerMode; - autoSpeak?: boolean; - voiceId?: string | null; modelProvider?: string | null; modelId?: string | null; thinkingLevel?: ThinkingLevel | null; @@ -111,7 +107,7 @@ export function BotSettings({ // A roster refresh can skip replacing bots while a reorder is in flight, so // this prop keeps the description from when the panel opened. Later saves // compare against the description last saved here; otherwise a model or - // voice change treats that stale text as an edit and overwrites instructions. + // thinking change treats that stale text as an edit and overwrites instructions. const savedDescriptionRef = useRef(bot.description ?? ""); // The profile header owns the avatar, so saves here always carry the bot's current one. const color = bot.color; @@ -121,9 +117,6 @@ export function BotSettings({ setNotifyOnFinish(bot.notifyOnFinish ?? true); }, [bot.notifyOnFinish]); const [computerMode, setComputerMode] = useState(bot.computerMode); - const [autoSpeak, setAutoSpeak] = useState(bot.autoSpeak); - const [voiceId, setVoiceId] = useState(bot.voiceId ?? ""); - const [voices, setVoices] = useState([]); const [modelKey, setModelKey] = useState( bot.modelProvider && bot.modelId ? modelOptionKey(bot.modelProvider, bot.modelId) : "", ); @@ -145,10 +138,6 @@ export function BotSettings({ }) => Promise >(async () => undefined); useEffect(() => { - void rpc.voice - .voices({}) - .then(setVoices) - .catch(() => setVoices([])); void Promise.all([rpc.models.credentials(), rpc.models.list(), rpc.me()]) .then(([nextCredentials, nextCatalog, nextMe]) => { setCredentials(nextCredentials); @@ -250,15 +239,13 @@ export function BotSettings({ name: nextName || bot.name, title: nextTitle, // One field feeds both, so it only goes on the wire when it changed: a - // model, thinking or voice save must not overwrite longer instructions, + // model or thinking save must not overwrite longer instructions, // nor fail on a description that is already above its own limit. ...botProfilePatch(savedDescriptionRef.current, nextDescription), // Unchanged color stays off the wire so a legacy named value cannot fail a name save. ...(nextColor !== bot.color ? { color: nextColor } : {}), notifyOnFinish: nextNotify, computerMode, - autoSpeak, - voiceId: voiceId || null, modelProvider: selected?.provider ?? null, modelId: selected?.modelId ?? null, ...(modelMetaReady @@ -430,35 +417,6 @@ export function BotSettings({ ) : null} )} - - {voices.length ? ( - - ) : null} {advancedOpened ? : null} {error ?

{error}

: null} diff --git a/docs/ai-data-sharing-review.md b/docs/ai-data-sharing-review.md index 7b54c920..56cd633b 100644 --- a/docs/ai-data-sharing-review.md +++ b/docs/ai-data-sharing-review.md @@ -3,7 +3,7 @@ ## Scope The mobile client obtains permission before uploading attachments, submitting messages, -starting routines, or sending voice content. Consent is stored per account, Space, recipient, +or starting routines. Consent is stored per account, Space, recipient, and disclosure version. Read-only disclosure/grant endpoints do not change provider execution. Web, Electron, workers, helper model selection, and self-hosted server execution retain their existing behavior. There are no gateway blocklists, provider-routing overrides, or external @@ -15,7 +15,7 @@ using their existing controls. This flow is not a global data-access or run-revo ## Release gates -- Confirm the review account's actual model, voice, and memory configuration. +- Confirm the review account's actual model and memory configuration. - Verify the selected providers' agreements, retention, deletion, and security safeguards support the policy's equal-or-greater-protection commitment. A privacy link alone is not proof. - For OpenRouter or Vercel AI Gateway, verify actual downstream routing and provider agreements. @@ -30,7 +30,7 @@ using their existing controls. This flow is not a global data-access or run-revo Unknown custom providers have no invented provider-policy link. - Deploy the website policy together with the mobile release. - Review App Store Connect's App Privacy responses against deployed data flows. Specifically - assess Photos or Videos for retained attachments and Audio Data for voice processing, using + assess Photos or Videos for retained attachments, using [Apple's collection definitions](https://developer.apple.com/app-store/app-privacy-details/). - Run Expo compatibility checks and create a new signed iOS store build. @@ -41,13 +41,13 @@ Use synthetic content and a fresh review account on iPhone and an 11-inch iPad. 1. Send a first message. Confirm the alert names configured recipients, explains data and purposes, and opens the correct deployment policy. 2. Choose Not now. Confirm neither content upload nor message submission occurs and the draft - remains available. Repeat with an attachment and with voice. + remains available. Repeat with an attachment. 3. Choose Allow. Confirm the grant is saved before the mobile action proceeds. 4. Relaunch and verify the approved configuration does not prompt again. 5. Withdraw permission in Account → AI data sharing. Confirm the next mobile action prompts. Verify the screen explains that existing runs and routines are stopped separately. 6. Switch account, Space, server, or recipient endpoint. Confirm grants are not mixed. -7. Use desktop/web without mobile grants. Confirm messages, attachments, helpers, voice, memory, +7. Use desktop/web without mobile grants. Confirm messages, attachments, helpers, memory, and routines retain their previous behavior. 8. Verify OpenRouter, Vercel AI Gateway, and custom/local providers remain selectable and keep their existing routing settings. @@ -60,7 +60,7 @@ Replace bracketed fields after verification. Keep credentials in App Store Conne The mobile app requests permission before submitting content to configured AI services. The alert names recipients, describes the data and purpose, and lets users decline. To review: sign in, open [bot], enter a message, and tap Send. Choose Not now to verify that -submission is blocked, then send again and choose Allow. Voice requests permission separately. +submission is blocked, then send again and choose Allow. Account → AI data sharing withdraws permission for new mobile actions; stop already-authorized runs and disable routines using their controls. The policy is linked from the alert and Account. Tested build: [version/build]. Attached: [native iPad screenshot]. diff --git a/docs/self-host.md b/docs/self-host.md index 4eb89a3f..e2f34058 100644 --- a/docs/self-host.md +++ b/docs/self-host.md @@ -374,20 +374,13 @@ Product contracts stay compatible across cloud and self-hosted. ### Space privacy-boundary migration Before upgrading across migration `20260830200000_space_scope_names_and_user_credentials`, check -that every existing model and voice credential still belongs to a member of its Space. This query +that every existing model credential still belongs to a member of its Space. This query uses the pre-migration `workspaceId` column name and must return no rows: ```sql SELECT 'model' AS credential_type, credential."id", credential."userId", credential."workspaceId" AS "spaceId" FROM "user_model_credentials" AS credential -LEFT JOIN "space_members" AS membership - ON membership."spaceId" = credential."workspaceId" - AND membership."userId" = credential."userId" -WHERE membership."id" IS NULL -UNION ALL -SELECT 'voice', credential."id", credential."userId", credential."workspaceId" -FROM "user_voice_credentials" AS credential LEFT JOIN "space_members" AS membership ON membership."spaceId" = credential."workspaceId" AND membership."userId" = credential."userId" diff --git a/packages/adapter-kit/src/interfaces.ts b/packages/adapter-kit/src/interfaces.ts index 2fec9800..a7b59f68 100644 --- a/packages/adapter-kit/src/interfaces.ts +++ b/packages/adapter-kit/src/interfaces.ts @@ -49,14 +49,8 @@ import type { ScreenSession, SecretRecord, SnapshotRef, - SpeechClip, TerminalRequest, TransactionalEmail, - VoiceCapabilities, - VoiceInfo, - VoiceSynthesizeRequest, - VoiceTranscribeRequest, - VoiceVerifyResult, WebFetchCapabilities, WebFetchRequest, WebFetchResult, @@ -289,14 +283,6 @@ export interface ExecutionRunner { dispatch(runId: string, target: "cloud" | "self-hosted" | "desktop"): Promise; } -export interface VoiceProvider { - describe(): AdapterDescriptor; - verify(apiKey: string, context: AdapterContext): Promise; - listVoices(apiKey: string, context: AdapterContext): Promise; - synthesize(request: VoiceSynthesizeRequest, context: AdapterContext): Promise; - transcribe?(request: VoiceTranscribeRequest, context: AdapterContext): Promise<{ text: string }>; -} - /** * Provider-neutral web search. Builtin `web_search` routes here so backends * (keyless HTTP, model-native search, future paid APIs) can be swapped without diff --git a/packages/adapter-kit/src/registry.ts b/packages/adapter-kit/src/registry.ts index 61616566..f4eff30e 100644 --- a/packages/adapter-kit/src/registry.ts +++ b/packages/adapter-kit/src/registry.ts @@ -32,7 +32,6 @@ export const slots = { connector: "connector", auth: "connection-auth", runner: "runner", - voice: "voice", web: "web", browser: "browser", autoReview: "auto-review", diff --git a/packages/adapter-kit/src/types.ts b/packages/adapter-kit/src/types.ts index 2701206f..bcc72a2e 100644 --- a/packages/adapter-kit/src/types.ts +++ b/packages/adapter-kit/src/types.ts @@ -465,44 +465,6 @@ export interface AgentRuntimeCapabilities { model?: { provider: string; id: string }; } -export interface VoiceInfo { - id: string; - label: string; - description?: string; -} - -export interface SpeechClip { - bytes: Uint8Array; - mimeType: "audio/mpeg" | "audio/wav" | "audio/ogg"; -} - -export interface VoiceCapabilities { - catalog: boolean; - synthesize: boolean; - transcribe: boolean; -} - -export interface VoiceVerifyResult { - ok: boolean; - message?: string; -} - -export interface VoiceSynthesizeRequest { - text: string; - voiceId: string; - apiKey: string; - /** Connection speech model. Fish uses this, then `FISH_TTS_MODEL`, then s2.1-pro. */ - model?: string; - signal?: AbortSignal; -} - -export interface VoiceTranscribeRequest { - audio: Uint8Array; - mimeType: string; - apiKey: string; - signal?: AbortSignal; -} - export interface BackgroundJobPayloads { "run.continue": { runId: string }; "routine.wakeup": { routineId: string; scheduledFor: string }; diff --git a/packages/adapters/src/ai-consent.ts b/packages/adapters/src/ai-consent.ts index 535b99ca..c3a82dbf 100644 --- a/packages/adapters/src/ai-consent.ts +++ b/packages/adapters/src/ai-consent.ts @@ -4,7 +4,6 @@ import { CHATGPT_PLAN_PROVIDER } from "./chatgpt-plan.js"; import { CLAUDE_CODE_PROVIDER } from "./claude-code-cli.js"; import { localBaseUrl } from "./pi-local-provider.js"; import { listPiCatalog } from "./pi-models.js"; -import { voiceCatalogEntry } from "./voice-factory.js"; const PRIVACY_URLS: Record = { openrouter: "https://openrouter.ai/privacy", @@ -15,9 +14,6 @@ const PRIVACY_URLS: Record = { [CLAUDE_CODE_PROVIDER]: "https://www.anthropic.com/legal/privacy", google: "https://policies.google.com/privacy", "vercel-ai-gateway": "https://vercel.com/legal/privacy-policy", - elevenlabs: "https://elevenlabs.io/privacy-policy", - cartesia: "https://cartesia.ai/legal/privacy", - "fish-audio": "https://fish.audio/privacy/", }; /** Never expose endpoint paths, query parameters, user info, or credentials in a disclosure. */ @@ -30,7 +26,7 @@ export function aiRecipient(input: { if (input.provider === "scripted") return null; const endpoint = input.baseUrl ?? (input.provider === "local" ? localBaseUrl() : undefined); const origin = endpoint ? new URL(endpoint).origin : undefined; - const name = recipientName(input.provider, input.use); + const name = recipientName(input.provider); // Bind custom connections to the full endpoint without exposing private URL components. const key = createHash("sha256") .update(JSON.stringify([input.use, input.provider, endpoint ?? "", input.modelId ?? ""])) @@ -51,8 +47,7 @@ export function aiRecipient(input: { }; } -function recipientName(provider: string, use: AiDataUse) { - if (use === "voice") return voiceCatalogEntry(provider)?.name ?? provider; +function recipientName(provider: string) { if (provider === CLAUDE_CODE_PROVIDER) return "Claude Code"; return listPiCatalog().find((entry) => entry.provider === provider)?.providerName ?? provider; } diff --git a/packages/adapters/src/builtin-tools.ts b/packages/adapters/src/builtin-tools.ts index 97321073..59b687ec 100644 --- a/packages/adapters/src/builtin-tools.ts +++ b/packages/adapters/src/builtin-tools.ts @@ -650,25 +650,6 @@ export const builtinAgentTools: ConnectorTool[] = [ }, }, }, - { - name: "end_call", - description: - "End the current voice call. Call this when the user asks to hang up or end the call, or the conversation is clearly finished. Your farewell is spoken as the call ends, so do not also say goodbye in text; finish any remaining work in chat afterwards.", - inputSchema: { - type: "object", - properties: { - title: { - type: "string", - description: 'What the call was about, 2-5 words, e.g. "AI stack flow". Max 40 chars.', - }, - farewell: { - type: "string", - description: "One short sentence spoken as you hang up. Max 160 chars.", - }, - }, - required: ["title", "farewell"], - }, - }, { name: "skill_read", description: diff --git a/packages/adapters/src/cartesia-voice.ts b/packages/adapters/src/cartesia-voice.ts deleted file mode 100644 index df389009..00000000 --- a/packages/adapters/src/cartesia-voice.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { - AdapterContext, - AdapterDescriptor, - SpeechClip, - VoiceCapabilities, - VoiceInfo, - VoiceProvider, - VoiceSynthesizeRequest, - VoiceVerifyResult, -} from "@milo/adapter-kit"; -import { - readVoiceAudio, - readVoiceJson, - requireOk, - verifyVoiceHttpGet, - voiceDeadline, - voiceHttpError, -} from "./voice-http.js"; - -const API = "https://api.cartesia.ai"; -const VERSION = "2024-06-10"; -const MODEL = "sonic-3"; -// `/voices` only honours `limit` from this API version on. Under VERSION it returns the entire -// catalog as one array, which overruns the voice JSON read cap and fails the request outright. -// Synthesis stays pinned to VERSION so its request and response contract is untouched. -const VOICES_VERSION = "2026-08-14"; -const VOICE_PAGE_LIMIT = 100; -const VERIFY_PAGE_LIMIT = 1; -/** Bounds the catalog walk so a very large library cannot spin forever. */ -const VOICE_MAX_PAGES = 20; - -export class CartesiaVoiceProvider implements VoiceProvider { - describe(): AdapterDescriptor { - return { - id: "cartesia", - contractVersion: "1", - adapterVersion: "0.1.0", - capabilities: { catalog: true, synthesize: true, transcribe: false }, - }; - } - - async verify(apiKey: string, context: AdapterContext): Promise { - return verifyVoiceHttpGet({ - url: `${API}/voices?limit=${VERIFY_PAGE_LIMIT}`, - headers: cartesiaHeaders(apiKey, VOICES_VERSION), - signal: context.signal, - provider: "Cartesia", - }); - } - - async listVoices(apiKey: string, context: AdapterContext): Promise { - const signal = voiceDeadline(context.signal, 20_000); - const voices: Array> = []; - let startingAfter: string | undefined; - // `limit` is per page, so walk the cursor to keep voices past the first page in the picker - // while each response stays inside the voice JSON read cap. - for (let page = 0; page < VOICE_MAX_PAGES; page++) { - const params = new URLSearchParams({ limit: String(VOICE_PAGE_LIMIT) }); - if (startingAfter) params.set("starting_after", startingAfter); - const res = await fetch(`${API}/voices?${params}`, { - headers: cartesiaHeaders(apiKey, VOICES_VERSION), - signal, - }); - const body = await readVoiceJson(res, { requireValid: res.ok }); - if (!res.ok) throw new Error(voiceHttpError(res.status, "Cartesia", "listing voices", body)); - const items = voicesFrom(body); - voices.push(...items); - const next = nextVoicePage(body, items); - if (!next) break; - startingAfter = next; - } - return voices - .map((voice) => ({ - id: String(voice.id ?? voice.voice_id ?? ""), - label: String(voice.name ?? "Voice"), - description: typeof voice.description === "string" ? voice.description : undefined, - })) - .filter((voice) => voice.id); - } - - async synthesize(request: VoiceSynthesizeRequest, context: AdapterContext): Promise { - const signal = voiceDeadline(request.signal ?? context.signal, 60_000); - const res = await fetch(`${API}/tts/bytes`, { - method: "POST", - headers: { - ...cartesiaHeaders(request.apiKey), - "content-type": "application/json", - }, - body: JSON.stringify({ - model_id: MODEL, - transcript: request.text, - voice: { mode: "id", id: request.voiceId }, - // Cartesia's mp3 container takes bit_rate, not encoding: an encoding key rejects the request. - output_format: { container: "mp3", sample_rate: 44100, bit_rate: 128000 }, - }), - signal, - }); - await requireOk(res, "Cartesia", "speaking"); - return { bytes: await readVoiceAudio(res, signal), mimeType: "audio/mpeg" }; - } -} - -function cartesiaHeaders(apiKey: string, version: string = VERSION): Record { - return { "X-API-Key": apiKey, "Cartesia-Version": version }; -} - -/** The cursor for the next catalog page, or undefined when this was the last one. */ -function nextVoicePage( - body: unknown, - items: ReadonlyArray>, -): string | undefined { - if (items.length === 0 || !body || typeof body !== "object") return undefined; - const meta = body as { has_more?: unknown; next_page?: unknown }; - if (meta.has_more !== true) return undefined; - if (typeof meta.next_page === "string" && meta.next_page) return meta.next_page; - // Older payloads omit next_page and expect the last id as the cursor. - const last = items[items.length - 1]; - const id = String(last?.id ?? last?.voice_id ?? ""); - return id || undefined; -} - -function voicesFrom(body: unknown): Array> { - if (Array.isArray(body)) return body as Array>; - if (body && typeof body === "object") { - const record = body as Record; - if (Array.isArray(record.data)) return record.data as Array>; - if (Array.isArray(record.voices)) return record.voices as Array>; - } - return []; -} diff --git a/packages/adapters/src/elevenlabs-voice.ts b/packages/adapters/src/elevenlabs-voice.ts deleted file mode 100644 index f38f81a3..00000000 --- a/packages/adapters/src/elevenlabs-voice.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { - AdapterContext, - AdapterDescriptor, - SpeechClip, - VoiceCapabilities, - VoiceInfo, - VoiceProvider, - VoiceSynthesizeRequest, - VoiceTranscribeRequest, - VoiceVerifyResult, -} from "@milo/adapter-kit"; -import { - readVoiceAudio, - readVoiceJson, - requireOk, - speechUploadName, - verifyVoiceHttpGet, - voiceDeadline, - voiceHttpError, -} from "./voice-http.js"; - -const API = "https://api.elevenlabs.io/v1"; -const MODEL = "eleven_flash_v2_5"; -const FORMAT = "mp3_44100_64"; -const TRANSCRIBE_MODEL = "scribe_v1"; - -export class ElevenLabsVoiceProvider implements VoiceProvider { - describe(): AdapterDescriptor { - return { - id: "elevenlabs", - contractVersion: "1", - adapterVersion: "0.1.0", - capabilities: { catalog: true, synthesize: true, transcribe: true }, - }; - } - - async verify(apiKey: string, context: AdapterContext): Promise { - return verifyVoiceHttpGet({ - url: `${API}/voices`, - headers: { "xi-api-key": apiKey }, - signal: context.signal, - provider: "ElevenLabs", - }); - } - - async listVoices(apiKey: string, context: AdapterContext): Promise { - const res = await fetch(`${API}/voices`, { - headers: { "xi-api-key": apiKey }, - signal: voiceDeadline(context.signal, 20_000), - }); - const body = await readVoiceJson(res, { requireValid: res.ok }); - if (!res.ok) throw new Error(voiceHttpError(res.status, "ElevenLabs", "listing voices", body)); - const voices = (body as { voices?: Array> } | null)?.voices ?? []; - return voices - .map((voice) => ({ - id: String(voice.voice_id ?? ""), - label: String(voice.name ?? "Voice"), - description: - [asLabel(voice.labels, "accent"), asLabel(voice.labels, "description")] - .filter(Boolean) - .join(" · ") || undefined, - })) - .filter((voice) => voice.id); - } - - async synthesize(request: VoiceSynthesizeRequest, context: AdapterContext): Promise { - const signal = voiceDeadline(request.signal ?? context.signal, 60_000); - const res = await fetch( - `${API}/text-to-speech/${encodeURIComponent(request.voiceId)}?output_format=${FORMAT}`, - { - method: "POST", - headers: { - "xi-api-key": request.apiKey, - "content-type": "application/json", - accept: "audio/mpeg", - }, - body: JSON.stringify({ text: request.text, model_id: MODEL }), - signal, - }, - ); - await requireOk(res, "ElevenLabs", "speaking"); - return { bytes: await readVoiceAudio(res, signal), mimeType: "audio/mpeg" }; - } - - async transcribe( - request: VoiceTranscribeRequest, - context: AdapterContext, - ): Promise<{ text: string }> { - const form = new FormData(); - form.set("model_id", TRANSCRIBE_MODEL); - form.set( - "file", - new Blob([new Uint8Array(request.audio)], { type: request.mimeType || "audio/webm" }), - speechUploadName(request.mimeType), - ); - const res = await fetch(`${API}/speech-to-text`, { - method: "POST", - headers: { "xi-api-key": request.apiKey }, - body: form, - signal: voiceDeadline(request.signal ?? context.signal, 60_000), - }); - const body = await readVoiceJson(res, { requireValid: res.ok }); - if (!res.ok) throw new Error(voiceHttpError(res.status, "ElevenLabs", "transcribing", body)); - const text = String((body as { text?: unknown } | null)?.text ?? "").trim(); - return { text }; - } -} - -function asLabel(labels: unknown, key: string): string { - if (!labels || typeof labels !== "object") return ""; - const value = (labels as Record)[key]; - return typeof value === "string" ? value : ""; -} diff --git a/packages/adapters/src/executor-oauth-retire.test.ts b/packages/adapters/src/executor-oauth-retire.test.ts index a5009523..3f530f52 100644 --- a/packages/adapters/src/executor-oauth-retire.test.ts +++ b/packages/adapters/src/executor-oauth-retire.test.ts @@ -69,9 +69,6 @@ function oauthPrisma() { ).length, ), }, - userVoiceCredential: { - count: vi.fn(async () => 0), - }, spaceModelPreference: { deleteMany: vi.fn(async (args: { where: { userId: string; credentialId: string } }) => { const before = state.preferences.length; diff --git a/packages/adapters/src/executor.test.ts b/packages/adapters/src/executor.test.ts index ae6bc4d9..f31045aa 100644 --- a/packages/adapters/src/executor.test.ts +++ b/packages/adapters/src/executor.test.ts @@ -320,18 +320,6 @@ describe("run tool selection", () => { expect(toolNames("user")).toContain("task_catalog"); }); - it("offers end_call on a hang-up run so it can title the call", () => { - const callEnd = selectBuiltinToolsForRun({ - graphicalToolsAllowed: true, - groupId: null, - trigger: "call_end", - voiceCall: true, - }).map((tool) => tool.name); - expect(callEnd).toContain("end_call"); - expect(callEnd).toContain("schedule_create"); - expect(toolNames("call_end")).not.toContain("end_call"); - }); - it("keeps schedule tools in group chats and still blocks create on routines", () => { expect(toolNames("user", "group-1")).toEqual( expect.arrayContaining(["schedule_create", "schedule_list", "schedule_cancel"]), diff --git a/packages/adapters/src/executor.ts b/packages/adapters/src/executor.ts index ebba62ce..7d135330 100644 --- a/packages/adapters/src/executor.ts +++ b/packages/adapters/src/executor.ts @@ -51,8 +51,6 @@ import { assertTransition, blocksToAgentHistoryText, botMessageAllowsSilence, - CALL_CLIENT_NONCE_PREFIX, - callIdFromClientNonce, connectorKindFromToolName, containsSecret, createStreamingRedactor, @@ -63,7 +61,6 @@ import { HAND_OFF_TOOL_RESULT, humanizeToolName, inferAttachmentMimeType, - isCallClientNonce, isOneShotRoutineCrons, isTerminal, nextCronDateAcross, @@ -356,9 +353,6 @@ const READ_ONLY_AGENT_TOOLS = new Set([ "browser_snapshot", "list_secrets", ]); -/** Added to the turn prompt when the user spoke this message on a live voice call. */ -export const VOICE_CALL_INSTRUCTION = - "You are on a live voice call. Reply in one to three short spoken sentences. No markdown, lists, links, or option cards; do not use ask_user unless you truly cannot proceed. Answer directly from what you already know when you can; use tools or subagents only when the answer requires them. If the user asks to end the call or hang up, or the conversation is finished, call end_call with a short title and a one-sentence farewell instead of saying goodbye in text, then do any remaining work as a normal chat reply."; const MAX_MODEL_FILE_BYTES = 250_000; const TURN_ATTACHMENT_UNAVAILABLE = "An attachment in this message could not be loaded. Tell the user the attachment was unavailable and do not guess its contents."; @@ -3580,20 +3574,6 @@ export function createRunExecutor(deps: ExecutorDeps) { )); } } - // Calls carry no schema flag: the sending client encodes them in the clientNonce. - const sourceClientNonce = - (run.trigger === "user" || run.trigger === "follow_up") && run.sourceMessageId - ? (( - await deps.prisma.message.findUnique({ - where: { id: run.sourceMessageId }, - select: { clientNonce: true }, - }) - )?.clientNonce ?? null) - : null; - // A hang-up run has no source message: its own nonce carries the call it closes. - const callEndRun = run.trigger === "call_end"; - const callClientNonceForRun = callEndRun ? run.clientNonce : sourceClientNonce; - const voiceCall = callEndRun || isCallClientNonce(sourceClientNonce); const graphicalToolsAllowed = graphical && acceptsImages && !heldForTakeover; const pageBrowserAllowed = graphical && browser.describe().capabilities.page && !heldForTakeover; @@ -3602,7 +3582,6 @@ export function createRunExecutor(deps: ExecutorDeps) { pageBrowserAllowed, groupId: thread.groupId, trigger: run.trigger, - voiceCall, }); const exposedConnectorTools = discovered.filter( (tool) => !builtinAgentTools.some((builtin) => builtin.name === tool.name), @@ -5235,94 +5214,6 @@ export function createRunExecutor(deps: ExecutorDeps) { : "The server was registered without assigning it to this bot.", }); } - if (name === "end_call") { - const callId = callIdFromClientNonce(callClientNonceForRun); - const title = String(args.title ?? "") - .trim() - .slice(0, 40); - const farewell = String(args.farewell ?? "") - .trim() - .slice(0, 160); - // The client may have hung up first and already closed the card: title that - // marker instead of leaving a second one behind. The marker's deterministic - // nonce is the idempotency key, so a resumed run cannot double-publish. - const nonce = callId ? `${CALL_CLIENT_NONCE_PREFIX}${callId}:marker` : undefined; - const findMarker = async () => - nonce - ? await deps.prisma.message.findUnique({ - where: { threadId_clientNonce: { threadId: thread.id, clientNonce: nonce } }, - select: { id: true, blocks: true }, - }) - : null; - let existing = await findMarker(); - let markerId = ""; - let changed = true; - if (!existing) { - try { - const marker = await publishMessage( - deps, - run, - "bot", - [{ kind: "voice_call", ...(callId ? { callId } : {}), title, farewell }], - undefined, - nonce, - ); - markerId = marker.id; - } catch (error) { - if (!isUniqueViolation(error)) throw error; - existing = await findMarker(); - } - } - if (existing) { - const before = Array.isArray(existing.blocks) - ? (existing.blocks as MessageBlock[]) - : []; - const blocks = before.map((block) => - block.kind === "voice_call" && block.callId === callId - ? { ...block, title, ...(farewell ? { farewell } : {}) } - : block, - ); - changed = JSON.stringify(blocks) !== JSON.stringify(before); - if (changed) { - await deps.prisma.message.update({ - where: { id: existing.id }, - data: { blocks: blocks as Prisma.InputJsonValue }, - }); - await deps.events.append({ - spaceId: run.spaceId, - threadId: thread.id, - botId: bot.id, - runId: run.id, - type: "thread.message.updated", - payload: { messageId: existing.id, role: "bot", blocks, callId }, - }); - } - markerId = existing.id; - } - if (changed) { - await deps.events.append({ - spaceId: run.spaceId, - threadId: thread.id, - botId: bot.id, - runId: run.id, - type: "thread.call.ended", - payload: { - botId: bot.id, - threadId: thread.id, - runId: run.id, - callId, - title, - farewell, - messageId: markerId, - }, - }); - } - return finish({ - ok: callEndRun - ? "The call is already closed and now carries your title. The user is reading, not listening: finish any remaining work as a normal chat reply with full formatting." - : "Call ended and your farewell was spoken. The user is now reading, not listening: finish any remaining work as a normal chat reply with full formatting.", - }); - } if (name === "list_secrets") return listBotSecrets(deps.prisma, run); if (name === "forget_secret") { const parsed = BotSecretName.safeParse(args.name); @@ -5879,8 +5770,6 @@ export function createRunExecutor(deps: ExecutorDeps) { basePrompt, takeoverResume?.promptNote, approvalContinuation, - // A hang-up turn is read, not heard: no spoken-reply constraint. - voiceCall && !callEndRun ? VOICE_CALL_INSTRUCTION : undefined, // Per-turn, not in the system prompt: the timestamp changes every call and would break the cacheable prefix. formatCurrentTimeInstruction(), ] @@ -6867,8 +6756,6 @@ export function selectBuiltinToolsForRun(options: { pageBrowserAllowed?: boolean; groupId: string | null; trigger: string; - /** Hanging up is only offered to a turn the caller spoke on a live call. */ - voiceCall?: boolean; }) { return filterBuiltinToolsForRun( filterBuiltinToolsForThread( @@ -6879,7 +6766,7 @@ export function selectBuiltinToolsForRun(options: { options.groupId, ), options.trigger, - ).filter((tool) => options.voiceCall || tool.name !== "end_call"); + ); } export const PAGE_BROWSER_TOOL_NAMES = new Set([ @@ -7252,7 +7139,6 @@ async function persistMessageInTransaction( messageId: message.id, role, blocks, - callId: callIdFromClientNonce(clientNonce), }, }); return { message, eventSeq: event.seq }; diff --git a/packages/adapters/src/fish-audio-voice.ts b/packages/adapters/src/fish-audio-voice.ts deleted file mode 100644 index 64d94a73..00000000 --- a/packages/adapters/src/fish-audio-voice.ts +++ /dev/null @@ -1,310 +0,0 @@ -import type { - AdapterContext, - AdapterDescriptor, - SpeechClip, - VoiceCapabilities, - VoiceInfo, - VoiceProvider, - VoiceSynthesizeRequest, - VoiceTranscribeRequest, - VoiceVerifyResult, -} from "@milo/adapter-kit"; -import { getLogger } from "@milo/logging"; -import { - readVoiceAudio, - readVoiceJson, - speechUploadName, - verifyVoiceHttpGet, - voiceDeadline, - voiceHttpError, -} from "./voice-http.js"; - -const API = "https://api.fish.audio"; -const MODEL_PAGE_SIZE = 100; -/** Top-scored public voices for the picker — not a full catalog crawl. */ -const PUBLIC_MODEL_PAGES = 5; -/** User-owned libraries are smaller; still hard-capped. */ -const OWN_MODEL_PAGES = 20; -const LIST_VOICES_DEADLINE_MS = 20_000; -const DEFAULT_TTS_MODEL = "s2.1-pro"; -/** Header-safe Fish model id. A connection override wins over `FISH_TTS_MODEL`. */ -const TTS_MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; -const UPSTREAM_DETAIL_LIMIT = 500; -let invalidTtsModelWarned = false; - -export class FishAudioVoiceProvider implements VoiceProvider { - /** Advertise Fish Audio's model catalog, speech synthesis, and transcription support. */ - describe(): AdapterDescriptor { - return { - id: "fish-audio", - contractVersion: "1", - adapterVersion: "0.1.0", - capabilities: { catalog: true, synthesize: true, transcribe: true }, - }; - } - - /** Verify the user's Fish Audio API key against the model catalog endpoint. */ - async verify(apiKey: string, context: AdapterContext): Promise { - return verifyVoiceHttpGet({ - url: `${API}/model?page_size=1&page_number=1`, - headers: fishAudioHeaders(apiKey), - signal: context.signal, - provider: "Fish Audio", - }); - } - - /** Return user-owned then bounded public Fish Audio voices as Milo choices. */ - async listVoices(apiKey: string, context: AdapterContext): Promise { - const signal = voiceDeadline(context.signal, LIST_VOICES_DEADLINE_MS); - const listContext = { ...context, signal }; - const [publicModels, ownModels] = await Promise.all([ - fetchModels(apiKey, listContext, false), - fetchModels(apiKey, listContext, true), - ]); - const seen = new Set(); - return [...ownModels, ...publicModels].map(modelToVoice).filter((voice): voice is VoiceInfo => { - if (!voice || seen.has(voice.id)) return false; - seen.add(voice.id); - return true; - }); - } - - /** Synthesize one Milo utterance as bounded MP3 audio. */ - async synthesize(request: VoiceSynthesizeRequest, context: AdapterContext): Promise { - const signal = voiceDeadline(request.signal ?? context.signal, 60_000); - const model = resolveFishSpeechModel(request.model); - const res = await fetch(`${API}/v1/tts`, { - method: "POST", - headers: { - ...fishAudioHeaders(request.apiKey), - "content-type": "application/json", - accept: "audio/mpeg", - model, - }, - body: JSON.stringify({ - text: request.text, - reference_id: request.voiceId, - format: "mp3", - mp3_bitrate: 64, - latency: "balanced", - normalize: true, - }), - signal, - }); - if (!res.ok) { - rejectFish(res.status, "speaking", await readFishResponse(res), request.apiKey, model); - } - return { bytes: await readVoiceAudio(res, signal), mimeType: "audio/mpeg" }; - } - - /** Transcribe a browser recording through Fish Audio's multipart ASR endpoint. */ - async transcribe( - request: VoiceTranscribeRequest, - context: AdapterContext, - ): Promise<{ text: string }> { - const form = new FormData(); - form.set( - "audio", - new Blob([new Uint8Array(request.audio)], { type: request.mimeType || "audio/webm" }), - speechUploadName(request.mimeType), - ); - form.set("ignore_timestamps", "true"); - const res = await fetch(`${API}/v1/asr`, { - method: "POST", - headers: fishAudioHeaders(request.apiKey), - body: form, - signal: voiceDeadline(request.signal ?? context.signal, 60_000), - }); - const body = await readFishResponse(res); - if (!res.ok) rejectFish(res.status, "transcribing", body, request.apiKey); - return { text: String((body as { text?: unknown } | null)?.text ?? "").trim() }; - } -} - -/** Fetch public or user-owned Fish Audio voice models within a page budget. */ -async function fetchModels( - apiKey: string, - context: AdapterContext, - own: boolean, -): Promise>> { - const maxPages = own ? OWN_MODEL_PAGES : PUBLIC_MODEL_PAGES; - const models: Array> = []; - for (let pageNumber = 1; pageNumber <= maxPages; pageNumber++) { - const params = new URLSearchParams({ - page_size: String(MODEL_PAGE_SIZE), - page_number: String(pageNumber), - sort_by: "score", - }); - if (own) params.set("self", "true"); - const res = await fetch(`${API}/model?${params}`, { - headers: fishAudioHeaders(apiKey), - signal: context.signal, - }); - const body = await readFishResponse(res); - if (!res.ok) rejectFish(res.status, "listing voices", body, apiKey); - const items = modelsFrom(body); - models.push(...items); - if (items.length === 0 || !modelPageHasMore(body, pageNumber, items.length)) break; - } - return models; -} - -/** Decide whether another Fish Audio model page should be requested. */ -function modelPageHasMore(body: unknown, pageNumber: number, itemCount: number): boolean { - if (!body || typeof body !== "object") return false; - const meta = body as { has_more?: unknown; total?: unknown }; - if (typeof meta.has_more === "boolean") return meta.has_more; - if (typeof meta.total === "number" && Number.isFinite(meta.total)) { - return pageNumber * MODEL_PAGE_SIZE < meta.total; - } - return itemCount === MODEL_PAGE_SIZE; -} - -/** Build the authorization header shared by Fish Audio requests. */ -function fishAudioHeaders(apiKey: string): Record { - return { authorization: `Bearer ${apiKey}` }; -} - -/** True when `value` can be sent as the Fish `model` header. */ -export function isFishSpeechModelId(value: string): boolean { - return TTS_MODEL_PATTERN.test(value); -} - -/** Connection override, then `FISH_TTS_MODEL`, then s2.1-pro. */ -function resolveFishSpeechModel(override?: string | null): string { - const requested = override?.trim() ?? ""; - if (requested && isFishSpeechModelId(requested)) return requested; - return deploymentFishSpeechModel(); -} - -/** `FISH_TTS_MODEL` when it is a single model id; otherwise s2.1-pro. */ -function deploymentFishSpeechModel(): string { - const configured = process.env.FISH_TTS_MODEL?.trim() ?? ""; - if (!configured) return DEFAULT_TTS_MODEL; - if (isFishSpeechModelId(configured)) return configured; - if (!invalidTtsModelWarned) { - invalidTtsModelWarned = true; - getLogger().warn("Ignoring FISH_TTS_MODEL because it is not a model id", { - provider: "fish-audio", - }); - } - return DEFAULT_TTS_MODEL; -} - -/** Read a Fish body. Error responses still return a safe message when the read fails. */ -async function readFishResponse(res: Response): Promise { - try { - return await readVoiceJson(res, { requireValid: res.ok, rawOnInvalid: !res.ok }); - } catch (error) { - if (res.ok) throw error; - return fishUnreadBody(error); - } -} - -function fishUnreadBody(error: unknown): { message: string } { - if (error instanceof Error && error.message === "Voice response is too large.") { - return { message: error.message }; - } - return { message: "response body could not be read" }; -} - -/** Log the upstream Fish status and message, then raise the user-facing error. */ -function rejectFish( - status: number, - what: string, - body: unknown, - apiKey: string, - model?: string, -): never { - const detail = fishErrorDetail(body, apiKey); - getLogger().error("Fish Audio request failed", { - provider: "fish-audio", - operation: what, - "http.status": status, - ...(model ? { "fish.model": model } : {}), - ...(detail ? { "error.detail": detail } : {}), - }); - throw new Error( - voiceHttpError( - status, - "Fish Audio", - what, - typeof body === "string" || !detail ? null : { message: detail }, - ), - ); -} - -/** Upstream message, or a short raw body when Fish did not return JSON. */ -function fishErrorDetail(body: unknown, apiKey: string): string { - const text = typeof body === "string" ? body : upstreamMessage(body) || jsonFallback(body); - return scrubSecret(text, apiKey).replace(/\s+/g, " ").trim().slice(0, UPSTREAM_DETAIL_LIMIT); -} - -function upstreamMessage(body: unknown): string { - if (!body || typeof body !== "object") return ""; - const record = body as Record; - for (const key of ["detail", "message", "error"] as const) { - const value = record[key]; - if (typeof value === "string" && value.trim()) return value.trim(); - if ( - value && - typeof value === "object" && - typeof (value as { message?: unknown }).message === "string" - ) { - const message = (value as { message: string }).message.trim(); - if (message) return message; - } - } - return ""; -} - -function jsonFallback(body: unknown): string { - if (!body || typeof body !== "object") return ""; - try { - return JSON.stringify(body); - } catch { - return ""; - } -} - -function scrubSecret(text: string, apiKey: string): string { - const secret = apiKey.trim(); - if (secret.length < 8) return text; - return text.split(secret).join("[Redacted]"); -} - -/** Extract object-shaped model entries from a Fish Audio list response. */ -function modelsFrom(body: unknown): Array> { - if (!body || typeof body !== "object") return []; - const items = (body as { items?: unknown }).items; - return Array.isArray(items) - ? items.filter((item): item is Record => - Boolean(item && typeof item === "object"), - ) - : []; -} - -/** Convert a Fish Audio model into the provider-neutral voice shape. */ -function modelToVoice(model: Record): VoiceInfo | null { - if (model.dmca_taken_down === true || model.state === "failed") return null; - const id = asText(model._id) || asText(model.id); - if (!id) return null; - const label = asText(model.title) || asText(model.name) || "Voice"; - const description = - [asText(model.description), languageLabel(model.languages)].filter(Boolean).join(" · ") || - undefined; - return { id, label, description }; -} - -/** Read a trimmed string field from an untyped provider response. */ -function asText(value: unknown): string { - return typeof value === "string" ? value.trim() : ""; -} - -/** Format the model language list for the voice picker description. */ -function languageLabel(value: unknown): string { - if (!Array.isArray(value)) return ""; - return value - .filter((item): item is string => typeof item === "string" && item.trim().length > 0) - .join(", "); -} diff --git a/packages/adapters/src/index.ts b/packages/adapters/src/index.ts index c1a5a101..77c70849 100644 --- a/packages/adapters/src/index.ts +++ b/packages/adapters/src/index.ts @@ -19,7 +19,6 @@ export * from "./browser-provider-factory.js"; export * from "./browser-tools.js"; export * from "./builtin-skills.js"; export * from "./builtin-tools.js"; -export * from "./cartesia-voice.js"; export * from "./chatgpt-plan.js"; export * from "./chatgpt-sign-in-emulator.js"; export * from "./child-bots.js"; @@ -43,14 +42,12 @@ export * from "./deployment-model.js"; export * from "./desktop-sandbox.js"; export * from "./destination-emulator.js"; export * from "./docker-sandbox.js"; -export * from "./elevenlabs-voice.js"; export * from "./email-emulator.js"; export * from "./executor.js"; export * from "./expo-push.js"; export * from "./fake-browser.js"; export * from "./fake-sandbox.js"; export * from "./fake-web.js"; -export * from "./fish-audio-voice.js"; export * from "./github-webhook-emulator.js"; export * from "./graphql-connectors.js"; export * from "./group-handoff.js"; @@ -72,7 +69,6 @@ export * from "./model-usage-limits.js"; export * from "./model-vision.js"; export * from "./none-sandbox.js"; export * from "./openai-compatible-url.js"; -export * from "./openai-voice.js"; export * from "./page-browser-session.js"; export * from "./pi-catalog-availability.js"; export * from "./pi-codex-catalog.js"; @@ -96,14 +92,12 @@ export * from "./scratchpad-context.js"; export * from "./scratchpad-tools.js"; export * from "./scripted-auto-review.js"; export * from "./scripted-runtime.js"; -export * from "./scripted-voice.js"; export * from "./secrets.js"; export * from "./skill-tools.js"; export * from "./smtp-email.js"; export * from "./task-catalog.js"; export * from "./teaching-session.js"; export * from "./third-party-connector-emulator.js"; -export * from "./voice-factory.js"; export * from "./wakeup.js"; export * from "./web-limits.js"; export * from "./web-provider-factory.js"; diff --git a/packages/adapters/src/openai-voice.ts b/packages/adapters/src/openai-voice.ts deleted file mode 100644 index 3153d2d5..00000000 --- a/packages/adapters/src/openai-voice.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { - AdapterContext, - AdapterDescriptor, - SpeechClip, - VoiceCapabilities, - VoiceInfo, - VoiceProvider, - VoiceSynthesizeRequest, - VoiceTranscribeRequest, - VoiceVerifyResult, -} from "@milo/adapter-kit"; -import { - readVoiceAudio, - readVoiceJson, - requireOk, - speechUploadName, - verifyVoiceHttpGet, - voiceDeadline, - voiceHttpError, -} from "./voice-http.js"; - -const API = "https://api.openai.com/v1"; -const TTS_MODEL = "gpt-4o-mini-tts"; -const STT_MODEL = "gpt-4o-mini-transcribe"; - -const OPENAI_VOICES: VoiceInfo[] = [ - { id: "alloy", label: "Alloy", description: "Neutral" }, - { id: "ash", label: "Ash", description: "Clear" }, - { id: "ballad", label: "Ballad", description: "Warm" }, - { id: "coral", label: "Coral", description: "Bright" }, - { id: "echo", label: "Echo", description: "Even" }, - { id: "fable", label: "Fable", description: "Narrative" }, - { id: "onyx", label: "Onyx", description: "Deep" }, - { id: "nova", label: "Nova", description: "Energetic" }, - { id: "sage", label: "Sage", description: "Calm" }, - { id: "shimmer", label: "Shimmer", description: "Soft" }, - { id: "verse", label: "Verse", description: "Expressive" }, -]; - -export class OpenAIVoiceProvider implements VoiceProvider { - describe(): AdapterDescriptor { - return { - id: "openai", - contractVersion: "1", - adapterVersion: "0.1.0", - capabilities: { catalog: true, synthesize: true, transcribe: true }, - }; - } - - async verify(apiKey: string, context: AdapterContext): Promise { - return verifyVoiceHttpGet({ - url: `${API}/models`, - headers: { authorization: `Bearer ${apiKey}` }, - signal: context.signal, - provider: "OpenAI", - }); - } - - async listVoices(_apiKey: string, _context: AdapterContext): Promise { - return OPENAI_VOICES; - } - - async synthesize(request: VoiceSynthesizeRequest, context: AdapterContext): Promise { - const signal = voiceDeadline(request.signal ?? context.signal, 60_000); - const res = await fetch(`${API}/audio/speech`, { - method: "POST", - headers: { - authorization: `Bearer ${request.apiKey}`, - "content-type": "application/json", - }, - body: JSON.stringify({ - model: TTS_MODEL, - voice: request.voiceId, - input: request.text, - response_format: "mp3", - }), - signal, - }); - await requireOk(res, "OpenAI", "speaking"); - return { bytes: await readVoiceAudio(res, signal), mimeType: "audio/mpeg" }; - } - - async transcribe( - request: VoiceTranscribeRequest, - context: AdapterContext, - ): Promise<{ text: string }> { - const form = new FormData(); - form.set("model", STT_MODEL); - form.set( - "file", - new Blob([new Uint8Array(request.audio)], { type: request.mimeType || "audio/webm" }), - speechUploadName(request.mimeType), - ); - const res = await fetch(`${API}/audio/transcriptions`, { - method: "POST", - headers: { authorization: `Bearer ${request.apiKey}` }, - body: form, - signal: voiceDeadline(request.signal ?? context.signal, 60_000), - }); - const body = await readVoiceJson(res, { requireValid: res.ok }); - if (!res.ok) throw new Error(voiceHttpError(res.status, "OpenAI", "transcribing", body)); - return { text: String((body as { text?: unknown } | null)?.text ?? "").trim() }; - } -} diff --git a/packages/adapters/src/scripted-voice.ts b/packages/adapters/src/scripted-voice.ts deleted file mode 100644 index cdeeaeb8..00000000 --- a/packages/adapters/src/scripted-voice.ts +++ /dev/null @@ -1,62 +0,0 @@ -import type { - AdapterContext, - AdapterDescriptor, - SpeechClip, - VoiceCapabilities, - VoiceInfo, - VoiceProvider, - VoiceSynthesizeRequest, - VoiceTranscribeRequest, - VoiceVerifyResult, -} from "@milo/adapter-kit"; - -export const SCRIPTED_VOICE_ID = "alloy-test"; -export const SCRIPTED_TRANSCRIPT = "hello from the test microphone"; - -/** A tiny MPEG frame so `/api/voice/speak` can return `audio/mpeg` without a live vendor. */ -export const SCRIPTED_MPEG = Uint8Array.from([ - 0xff, 0xfb, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -]); - -export const SCRIPTED_VOICE_CATALOG_ENTRY = { - id: "scripted", - name: "Scripted", - description: "Deterministic fixture for tests. No billed speech.", - transcribe: true, -} as const; - -export class ScriptedVoiceProvider implements VoiceProvider { - describe(): AdapterDescriptor { - return { - id: "scripted", - contractVersion: "1", - adapterVersion: "0.1.0", - capabilities: { catalog: true, synthesize: true, transcribe: true }, - }; - } - - async verify(apiKey: string, _context: AdapterContext): Promise { - if (apiKey.trim().length < 8) { - return { ok: false, message: "That key is too short." }; - } - return { ok: true }; - } - - async listVoices(_apiKey: string, _context: AdapterContext): Promise { - return [{ id: SCRIPTED_VOICE_ID, label: "Scripted", description: "Test voice" }]; - } - - async synthesize( - _request: VoiceSynthesizeRequest, - _context: AdapterContext, - ): Promise { - return { bytes: new Uint8Array(SCRIPTED_MPEG), mimeType: "audio/mpeg" }; - } - - async transcribe( - _request: VoiceTranscribeRequest, - _context: AdapterContext, - ): Promise<{ text: string }> { - return { text: SCRIPTED_TRANSCRIPT }; - } -} diff --git a/packages/adapters/src/voice-factory.test.ts b/packages/adapters/src/voice-factory.test.ts deleted file mode 100644 index 86c235e5..00000000 --- a/packages/adapters/src/voice-factory.test.ts +++ /dev/null @@ -1,693 +0,0 @@ -import { createLogger, createTestSink, installLogger } from "@milo/logging"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { CartesiaVoiceProvider } from "./cartesia-voice.js"; -import { ElevenLabsVoiceProvider } from "./elevenlabs-voice.js"; -import { FishAudioVoiceProvider } from "./fish-audio-voice.js"; -import { OpenAIVoiceProvider } from "./openai-voice.js"; -import { - SCRIPTED_MPEG, - SCRIPTED_TRANSCRIPT, - SCRIPTED_VOICE_ID, - ScriptedVoiceProvider, -} from "./scripted-voice.js"; -import { - createVoiceProvider, - isVoiceProviderId, - listVoiceCatalog, - VOICE_CATALOG, -} from "./voice-factory.js"; -import { MAX_SYNTHESIZED_AUDIO_BYTES, MAX_VOICE_JSON_BYTES } from "./voice-http.js"; - -const ctx = { - operationId: "voice", - traceId: "voice", - spaceId: "w", - userId: "u", - signal: new AbortController().signal, -}; - -const previousRuntime = process.env.AGENT_RUNTIME; - -afterEach(() => { - vi.unstubAllGlobals(); - vi.unstubAllEnvs(); - if (previousRuntime === undefined) delete process.env.AGENT_RUNTIME; - else process.env.AGENT_RUNTIME = previousRuntime; - installLogger(createLogger({ service: "rakazo", level: "off", sinks: [] })); -}); - -describe("createVoiceProvider", () => { - it("exposes the hosted catalog behind one factory", () => { - process.env.AGENT_RUNTIME = "pi"; - expect(VOICE_CATALOG.map((entry) => entry.id)).toEqual([ - "elevenlabs", - "openai", - "cartesia", - "fish-audio", - ]); - expect(listVoiceCatalog().map((entry) => entry.id)).toEqual([ - "elevenlabs", - "openai", - "cartesia", - "fish-audio", - ]); - expect(createVoiceProvider("elevenlabs").describe().id).toBe("elevenlabs"); - expect(createVoiceProvider("openai").describe().capabilities.transcribe).toBe(true); - expect(createVoiceProvider("cartesia").describe().capabilities.transcribe).toBe(false); - expect(createVoiceProvider("fish-audio").describe().capabilities.transcribe).toBe(true); - expect(isVoiceProviderId("elevenlabs")).toBe(true); - expect(isVoiceProviderId("scripted")).toBe(false); - expect(isVoiceProviderId("piper")).toBe(false); - expect(() => createVoiceProvider("piper")).toThrow(/unknown voice provider/i); - expect(() => createVoiceProvider("scripted")).toThrow(/unknown voice provider/i); - }); - - it("adds the scripted fixture only when the agent runtime is scripted", () => { - process.env.AGENT_RUNTIME = "scripted"; - expect(listVoiceCatalog().some((entry) => entry.id === "scripted")).toBe(true); - expect(isVoiceProviderId("scripted")).toBe(true); - expect(createVoiceProvider("scripted").describe().id).toBe("scripted"); - }); -}); - -describe("ElevenLabsVoiceProvider", () => { - it("verifies against /voices so restricted speech keys still pass", async () => { - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - json: async () => ({ voices: [{ voice_id: "abc", name: "Rachel" }] }), - }); - vi.stubGlobal("fetch", fetchMock); - const provider = new ElevenLabsVoiceProvider(); - await expect(provider.verify("sk_test_key", ctx)).resolves.toEqual({ ok: true }); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/voices"); - }); - - it("synthesizes one utterance as mp3 bytes", async () => { - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - const provider = new ElevenLabsVoiceProvider(); - const clip = await provider.synthesize( - { text: "Hello there.", voiceId: "abc", apiKey: "sk_test_key" }, - ctx, - ); - expect(clip.mimeType).toBe("audio/mpeg"); - expect([...clip.bytes]).toEqual([1, 2, 3]); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/text-to-speech/abc"); - }); - - it("transcribes through Scribe", async () => { - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue(new Response(JSON.stringify({ text: "hello there" }))), - ); - const provider = new ElevenLabsVoiceProvider(); - await expect( - provider.transcribe!( - { audio: new Uint8Array([1]), mimeType: "audio/webm", apiKey: "sk" }, - ctx, - ), - ).resolves.toEqual({ text: "hello there" }); - }); -}); - -describe("OpenAIVoiceProvider", () => { - it("returns a static voice catalog without a network round trip", async () => { - const provider = new OpenAIVoiceProvider(); - const voices = await provider.listVoices("sk-test", ctx); - expect(voices.some((voice) => voice.id === "alloy")).toBe(true); - }); - - it("posts speech to /audio/speech", async () => { - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([9]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - const clip = await new OpenAIVoiceProvider().synthesize( - { text: "Hi", voiceId: "alloy", apiKey: "sk-test" }, - ctx, - ); - expect(clip.mimeType).toBe("audio/mpeg"); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/audio/speech"); - }); - - it("names Firefox ogg recordings from the mime type", async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ text: "hello" }))); - vi.stubGlobal("fetch", fetchMock); - await new OpenAIVoiceProvider().transcribe!( - { audio: new Uint8Array([1]), mimeType: "audio/ogg;codecs=opus", apiKey: "sk-test" }, - ctx, - ); - const form = fetchMock.mock.calls[0]?.[1]?.body as FormData; - const file = form.get("file") as File; - expect(file.name).toBe("speech.ogg"); - }); -}); - -describe("CartesiaVoiceProvider", () => { - it("maps the voices list from either array or { data } payloads", async () => { - vi.stubGlobal( - "fetch", - vi - .fn() - .mockResolvedValue( - new Response(JSON.stringify({ data: [{ id: "sonic", name: "Katie" }] })), - ), - ); - const provider = new CartesiaVoiceProvider(); - const voices = await provider.listVoices("sk-test", ctx); - expect(voices).toEqual([{ id: "sonic", label: "Katie", description: undefined }]); - }); - - // An unbounded /voices request returns the whole catalog, overruns the voice JSON read cap - // and fails connecting the provider outright. - it("bounds the voices request so the catalog cannot overrun the read cap", async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [] }))); - vi.stubGlobal("fetch", fetchMock); - const provider = new CartesiaVoiceProvider(); - - await provider.verify("sk-test", ctx); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("limit=1"); - - await provider.listVoices("sk-test", ctx); - expect(String(fetchMock.mock.calls[1]?.[0])).toMatch(/\/voices\?limit=\d+$/); - - // `limit` is ignored by the version synthesis is pinned to, so both reads must ask for a - // version that paginates. - for (const call of fetchMock.mock.calls) { - const headers = (call[1] as { headers: Record }).headers; - expect(headers["Cartesia-Version"]).toBe("2026-08-14"); - } - }); - - it("follows the catalog cursor so voices past the first page are listed", async () => { - const fetchMock = vi - .fn() - .mockResolvedValueOnce( - new Response( - JSON.stringify({ data: [{ id: "a", name: "A" }], has_more: true, next_page: "a" }), - ), - ) - .mockResolvedValueOnce( - new Response(JSON.stringify({ data: [{ id: "b", name: "B" }], has_more: false })), - ); - vi.stubGlobal("fetch", fetchMock); - - const voices = await new CartesiaVoiceProvider().listVoices("sk-test", ctx); - - expect(voices.map((voice) => voice.id)).toEqual(["a", "b"]); - expect(String(fetchMock.mock.calls[1]?.[0])).toContain("starting_after=a"); - // The walk stops on the page that reports no more, rather than requesting forever. - expect(fetchMock).toHaveBeenCalledTimes(2); - const firstSignal = (fetchMock.mock.calls[0]?.[1] as { signal?: AbortSignal } | undefined) - ?.signal; - const secondSignal = (fetchMock.mock.calls[1]?.[1] as { signal?: AbortSignal } | undefined) - ?.signal; - expect(firstSignal).toBeInstanceOf(AbortSignal); - expect(secondSignal).toBe(firstSignal); - }); - - it("stops catalog walks at the page ceiling when has_more stays true", async () => { - const fetchMock = vi.fn().mockImplementation(async () => { - const page = fetchMock.mock.calls.length; - return new Response( - JSON.stringify({ - data: [{ id: `v${page}`, name: `Voice ${page}` }], - has_more: true, - next_page: `v${page}`, - }), - ); - }); - vi.stubGlobal("fetch", fetchMock); - - const voices = await new CartesiaVoiceProvider().listVoices("sk-test", ctx); - - expect(fetchMock).toHaveBeenCalledTimes(20); - expect(voices.map((voice) => voice.id)).toEqual( - Array.from({ length: 20 }, (_, index) => `v${index + 1}`), - ); - const signals = fetchMock.mock.calls.map( - (call) => (call[1] as { signal?: AbortSignal } | undefined)?.signal, - ); - expect(signals[0]).toBeInstanceOf(AbortSignal); - expect(signals.every((signal) => signal === signals[0])).toBe(true); - }); - - it("keeps synthesis on the pinned API version", async () => { - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([1]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - - await new CartesiaVoiceProvider().synthesize( - { text: "Hi", voiceId: "sonic", apiKey: "sk-test" }, - ctx, - ); - - const init = fetchMock.mock.calls[0]?.[1] as { headers: Record } | undefined; - expect(init?.headers["Cartesia-Version"]).toBe("2024-06-10"); - }); - - it("posts bytes to /tts/bytes", async () => { - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([4, 5]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - const clip = await new CartesiaVoiceProvider().synthesize( - { text: "Hi", voiceId: "sonic", apiKey: "sk-test" }, - ctx, - ); - expect([...clip.bytes]).toEqual([4, 5]); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/tts/bytes"); - // mp3 takes bit_rate, not encoding: the documented shape is the only one Cartesia accepts. - const body = JSON.parse((fetchMock.mock.calls[0]?.[1] as { body: string })?.body ?? "{}"); - expect(body.output_format).toEqual({ - container: "mp3", - sample_rate: 44100, - bit_rate: 128000, - }); - expect(body.model_id).toBe("sonic-3"); - }); -}); - -describe("FishAudioVoiceProvider", () => { - it("lists own then public voice models without duplicates", async () => { - const fetchMock = vi - .fn() - .mockResolvedValueOnce( - new Response( - JSON.stringify({ - items: [{ _id: "public-id", title: "Public Voice", languages: ["en", "fr"] }], - }), - ), - ) - .mockResolvedValueOnce( - new Response( - JSON.stringify({ - items: [ - { _id: "private-id", title: "Private Voice", description: "My clone" }, - { _id: "public-id", title: "Duplicate" }, - { _id: "failed-id", title: "Failed", state: "failed" }, - ], - }), - ), - ); - vi.stubGlobal("fetch", fetchMock); - - const voices = await new FishAudioVoiceProvider().listVoices("sk-test", ctx); - - expect(voices).toEqual([ - { id: "private-id", label: "Private Voice", description: "My clone" }, - { id: "public-id", label: "Duplicate" }, - ]); - expect(String(fetchMock.mock.calls[0]?.[0])).toContain("page_size=100"); - expect(String(fetchMock.mock.calls[1]?.[0])).toContain("self=true"); - }); - - it("pages through Fish Audio model listings until has_more is false", async () => { - const fetchMock = vi.fn().mockImplementation(async (input: RequestInfo | URL) => { - const url = new URL(String(input)); - const page = Number(url.searchParams.get("page_number") ?? "1"); - const own = url.searchParams.get("self") === "true"; - const prefix = own ? "own" : "pub"; - return new Response( - JSON.stringify({ - total: 2, - has_more: page < 2, - items: [{ _id: `${prefix}-${page}`, title: `${own ? "Own" : "Public"} ${page}` }], - }), - ); - }); - vi.stubGlobal("fetch", fetchMock); - - const voices = await new FishAudioVoiceProvider().listVoices("sk-test", ctx); - - expect(voices.map((voice) => voice.id)).toEqual(["own-1", "own-2", "pub-1", "pub-2"]); - expect(voices.some((voice) => voice.label === "Public 2")).toBe(true); - expect(voices.some((voice) => voice.label === "Own 2")).toBe(true); - expect(fetchMock).toHaveBeenCalledTimes(4); - expect( - fetchMock.mock.calls - .map((call) => String(call[0])) - .filter((url) => url.includes("page_number=2")), - ).toHaveLength(2); - }); - - it("keeps paging when total implies more pages without has_more", async () => { - const fetchMock = vi.fn().mockImplementation(async (input: RequestInfo | URL) => { - const url = new URL(String(input)); - const page = Number(url.searchParams.get("page_number") ?? "1"); - const own = url.searchParams.get("self") === "true"; - if (own) { - return new Response( - JSON.stringify({ total: 1, items: [{ _id: "own-only", title: "Own" }] }), - ); - } - return new Response( - JSON.stringify({ - total: 101, - items: - page === 1 - ? Array.from({ length: 100 }, (_, index) => ({ - _id: `pub-${index + 1}`, - title: `Public ${index + 1}`, - })) - : [{ _id: "pub-101", title: "Public 101" }], - }), - ); - }); - vi.stubGlobal("fetch", fetchMock); - - const voices = await new FishAudioVoiceProvider().listVoices("sk-test", ctx); - - expect(voices.some((voice) => voice.id === "pub-101")).toBe(true); - expect(voices.some((voice) => voice.label === "Public 101")).toBe(true); - expect( - fetchMock.mock.calls.some( - (call) => - String(call[0]).includes("page_number=2") && !String(call[0]).includes("self=true"), - ), - ).toBe(true); - }); - - it("stops catalog crawls at page caps when has_more stays true", async () => { - const publicPages = 5; - const ownPages = 20; - const fetchMock = vi.fn().mockImplementation(async (input: RequestInfo | URL) => { - const url = new URL(String(input)); - const page = Number(url.searchParams.get("page_number") ?? "1"); - const own = url.searchParams.get("self") === "true"; - const prefix = own ? "own" : "pub"; - const start = (page - 1) * 100; - return new Response( - JSON.stringify({ - total: 1_000_000, - has_more: true, - items: Array.from({ length: 100 }, (_, index) => ({ - _id: `${prefix}-${start + index + 1}`, - title: `${own ? "Own" : "Public"} ${start + index + 1}`, - })), - }), - ); - }); - vi.stubGlobal("fetch", fetchMock); - - const voices = await new FishAudioVoiceProvider().listVoices("sk-test", ctx); - - expect(voices).toHaveLength(ownPages * 100 + publicPages * 100); - expect(voices[0]?.id).toBe("own-1"); - expect(voices.at(ownPages * 100)?.id).toBe("pub-1"); - expect( - fetchMock.mock.calls.filter((call) => String(call[0]).includes("self=true")), - ).toHaveLength(ownPages); - expect( - fetchMock.mock.calls.filter((call) => !String(call[0]).includes("self=true")), - ).toHaveLength(publicPages); - }); - - it("synthesizes with the Fish Audio TTS contract", async () => { - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([7, 8]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - - const clip = await new FishAudioVoiceProvider().synthesize( - { text: "Hi", voiceId: "voice-id", apiKey: "sk-test" }, - ctx, - ); - - expect(clip.mimeType).toBe("audio/mpeg"); - expect([...clip.bytes]).toEqual([7, 8]); - expect(String(fetchMock.mock.calls[0]?.[0])).toBe("https://api.fish.audio/v1/tts"); - const init = fetchMock.mock.calls[0]?.[1] as RequestInit; - expect((init.headers as Record).model).toBe("s2.1-pro"); - expect(JSON.parse(String(init.body))).toMatchObject({ - text: "Hi", - reference_id: "voice-id", - format: "mp3", - }); - }); - - it("sends FISH_TTS_MODEL when the key cannot use s2.1-pro", async () => { - vi.stubEnv("FISH_TTS_MODEL", "s1"); - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([1]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - - await new FishAudioVoiceProvider().synthesize( - { text: "Hi", voiceId: "voice-id", apiKey: "sk-test" }, - ctx, - ); - - const init = fetchMock.mock.calls[0]?.[1] as RequestInit; - expect((init.headers as Record).model).toBe("s1"); - }); - - it("uses the connection speech model instead of FISH_TTS_MODEL", async () => { - vi.stubEnv("FISH_TTS_MODEL", "s1"); - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([1]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - - await new FishAudioVoiceProvider().synthesize( - { text: "Hi", voiceId: "voice-id", apiKey: "sk-test", model: "s2-pro" }, - ctx, - ); - await new FishAudioVoiceProvider().synthesize( - { text: "Hi", voiceId: "voice-id", apiKey: "sk-other", model: "s1" }, - ctx, - ); - - const headers = (call: number) => { - const init = fetchMock.mock.calls[call]?.[1] as RequestInit | undefined; - return (init?.headers ?? {}) as Record; - }; - expect(headers(0).model).toBe("s2-pro"); - expect(headers(1).model).toBe("s1"); - }); - - it("ignores a connection speech model that is not a model id", async () => { - vi.stubEnv("FISH_TTS_MODEL", "s1"); - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([1]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - - await new FishAudioVoiceProvider().synthesize( - { text: "Hi", voiceId: "voice-id", apiKey: "sk-test", model: "s2\ninjected" }, - ctx, - ); - - const init = fetchMock.mock.calls[0]?.[1] as RequestInit; - expect((init.headers as Record).model).toBe("s1"); - }); - - it("keeps s2.1-pro when FISH_TTS_MODEL is not a model id", async () => { - vi.stubEnv("FISH_TTS_MODEL", "s1\ninjected"); - const fetchMock = vi.fn().mockResolvedValue({ - ok: true, - arrayBuffer: async () => new Uint8Array([1]).buffer, - }); - vi.stubGlobal("fetch", fetchMock); - - await new FishAudioVoiceProvider().synthesize( - { text: "Hi", voiceId: "voice-id", apiKey: "sk-test" }, - ctx, - ); - - const init = fetchMock.mock.calls[0]?.[1] as RequestInit; - expect((init.headers as Record).model).toBe("s2.1-pro"); - }); - - it("logs the upstream Fish status and message without the API key", async () => { - const apiKey = "sk-fishaudiokey12345"; - const sink = createTestSink(); - installLogger(createLogger({ service: "rakazo-api", sinks: [sink] })); - vi.stubEnv("FISH_TTS_MODEL", "s1"); - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue( - new Response( - JSON.stringify({ - message: `model s1 is not enabled for ${apiKey}`, - status: 502, - }), - { status: 502, headers: { "content-type": "application/json" } }, - ), - ), - ); - - const error = await new FishAudioVoiceProvider() - .synthesize({ text: "Hi", voiceId: "voice-id", apiKey }, ctx) - .catch((caught: unknown) => caught); - - expect(error).toBeInstanceOf(Error); - expect((error as Error).message).toBe( - "speaking failed: model s1 is not enabled for [Redacted]", - ); - expect((error as Error).message).not.toContain(apiKey); - - const event = sink.events.find((entry) => entry.message === "Fish Audio request failed"); - expect(event).toMatchObject({ - provider: "fish-audio", - operation: "speaking", - "http.status": 502, - "fish.model": "s1", - "error.detail": "model s1 is not enabled for [Redacted]", - }); - expect(JSON.stringify(event)).not.toContain(apiKey); - }); - - it.each([ - [ - "speaking", - (provider: FishAudioVoiceProvider) => - provider.synthesize({ text: "Hi", voiceId: "voice-id", apiKey: "sk-test" }, ctx), - ], - [ - "transcribing", - (provider: FishAudioVoiceProvider) => - provider.transcribe!( - { audio: new Uint8Array([1]), mimeType: "audio/webm", apiKey: "sk-test" }, - ctx, - ), - ], - ["listing voices", (provider: FishAudioVoiceProvider) => provider.listVoices("sk-test", ctx)], - ])("logs Fish %s status when the error body cannot be read", async (operation, call) => { - const sink = createTestSink(); - installLogger(createLogger({ service: "rakazo-api", sinks: [sink] })); - const cancel = vi.fn(() => new Promise(() => undefined)); - vi.stubGlobal( - "fetch", - vi.fn().mockImplementation( - () => - new Response(new ReadableStream({ cancel }), { - status: 502, - headers: { "content-length": String(MAX_VOICE_JSON_BYTES + 1) }, - }), - ), - ); - - await expect(call(new FishAudioVoiceProvider())).rejects.toThrow( - `${operation} failed: Voice response is too large.`, - ); - - const event = sink.events.find((entry) => entry.message === "Fish Audio request failed"); - expect(event).toMatchObject({ - operation, - "http.status": 502, - "error.detail": "Voice response is too large.", - }); - expect(cancel).toHaveBeenCalled(); - }); - - it("logs a non-JSON Fish body when speaking fails", async () => { - const apiKey = "sk-fishaudiokey12345"; - const sink = createTestSink(); - installLogger(createLogger({ service: "rakazo-api", sinks: [sink] })); - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue(new Response(`gateway down ${apiKey}`, { status: 502 })), - ); - - await expect( - new FishAudioVoiceProvider().synthesize({ text: "Hi", voiceId: "voice-id", apiKey }, ctx), - ).rejects.toThrow("speaking failed (502)"); - - const event = sink.events.find((entry) => entry.message === "Fish Audio request failed"); - expect(event).toMatchObject({ - "http.status": 502, - "error.detail": "gateway down [Redacted]", - "fish.model": "s2.1-pro", - }); - expect(JSON.stringify(event)).not.toContain(apiKey); - }); - - it("transcribes through Fish Audio ASR", async () => { - const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ text: "hello" }))); - vi.stubGlobal("fetch", fetchMock); - - await expect( - new FishAudioVoiceProvider().transcribe!( - { audio: new Uint8Array([1]), mimeType: "audio/ogg;codecs=opus", apiKey: "sk-test" }, - ctx, - ), - ).resolves.toEqual({ text: "hello" }); - - expect(String(fetchMock.mock.calls[0]?.[0])).toBe("https://api.fish.audio/v1/asr"); - const init = fetchMock.mock.calls[0]?.[1] as RequestInit; - const form = init.body as FormData; - expect((form.get("audio") as File).name).toBe("speech.ogg"); - expect(form.get("ignore_timestamps")).toBe("true"); - }); -}); - -describe("hosted voice response limits", () => { - it.each([ - ["ElevenLabs", () => new ElevenLabsVoiceProvider(), "voice"], - ["OpenAI", () => new OpenAIVoiceProvider(), "alloy"], - ["Cartesia", () => new CartesiaVoiceProvider(), "sonic"], - ["Fish Audio", () => new FishAudioVoiceProvider(), "voice"], - ])( - "rejects an oversized %s speech response before buffering it", - async (_name, create, voiceId) => { - const cancel = vi.fn().mockResolvedValue(undefined); - vi.stubGlobal( - "fetch", - vi.fn().mockResolvedValue({ - ok: true, - headers: new Headers({ - "content-length": String(MAX_SYNTHESIZED_AUDIO_BYTES + 1), - }), - body: { cancel }, - }), - ); - - await expect( - create().synthesize({ text: "Hi", voiceId, apiKey: "sk-test" }, ctx), - ).rejects.toThrow("Voice response is too large."); - expect(cancel).toHaveBeenCalledOnce(); - }, - ); -}); - -describe("ScriptedVoiceProvider", () => { - it("verifies, lists, speaks, and transcribes without a network", async () => { - const provider = new ScriptedVoiceProvider(); - await expect(provider.verify("short", ctx)).resolves.toEqual({ - ok: false, - message: "That key is too short.", - }); - await expect(provider.verify("fake-scripted-voice-key", ctx)).resolves.toEqual({ ok: true }); - expect(await provider.listVoices("fake-scripted-voice-key", ctx)).toEqual([ - { id: SCRIPTED_VOICE_ID, label: "Scripted", description: "Test voice" }, - ]); - const clip = await provider.synthesize( - { text: "Hello", voiceId: SCRIPTED_VOICE_ID, apiKey: "fake-scripted-voice-key" }, - ctx, - ); - expect(clip.mimeType).toBe("audio/mpeg"); - expect([...clip.bytes]).toEqual([...SCRIPTED_MPEG]); - await expect( - provider.transcribe( - { - audio: new Uint8Array([1]), - mimeType: "audio/webm", - apiKey: "fake-scripted-voice-key", - }, - ctx, - ), - ).resolves.toEqual({ text: SCRIPTED_TRANSCRIPT }); - }); -}); diff --git a/packages/adapters/src/voice-factory.ts b/packages/adapters/src/voice-factory.ts deleted file mode 100644 index a6eccfc5..00000000 --- a/packages/adapters/src/voice-factory.ts +++ /dev/null @@ -1,97 +0,0 @@ -import type { VoiceProvider } from "@milo/adapter-kit"; -import { CartesiaVoiceProvider } from "./cartesia-voice.js"; -import { ElevenLabsVoiceProvider } from "./elevenlabs-voice.js"; -import { FishAudioVoiceProvider } from "./fish-audio-voice.js"; -import { OpenAIVoiceProvider } from "./openai-voice.js"; -import { SCRIPTED_VOICE_CATALOG_ENTRY, ScriptedVoiceProvider } from "./scripted-voice.js"; - -export const VOICE_CATALOG = [ - { - id: "elevenlabs", - name: "ElevenLabs", - description: "Highest quality and cloning. Flash v2.5 for conversational calls.", - transcribe: true, - }, - { - id: "openai", - name: "OpenAI", - description: "Simple TTS plus Whisper-class transcription. Reuse an OpenAI key.", - transcribe: true, - }, - { - id: "cartesia", - name: "Cartesia", - description: "Lowest-latency Sonic voices for interruptible calls.", - transcribe: false, - }, - { - id: "fish-audio", - name: "Fish Audio", - description: "Voice models, cloning, and expressive speech with optional transcription.", - transcribe: true, - }, -] as const; - -export { SCRIPTED_VOICE_CATALOG_ENTRY }; - -export type HostedVoiceProviderId = (typeof VOICE_CATALOG)[number]["id"]; -export type VoiceProviderId = HostedVoiceProviderId | "scripted"; - -export function scriptedVoiceEnabled() { - return process.env.AGENT_RUNTIME === "scripted"; -} - -export function listVoiceCatalog() { - return scriptedVoiceEnabled() - ? [...VOICE_CATALOG, SCRIPTED_VOICE_CATALOG_ENTRY] - : [...VOICE_CATALOG]; -} - -export function voiceCatalogEntry(id: string) { - if (id === SCRIPTED_VOICE_CATALOG_ENTRY.id) return SCRIPTED_VOICE_CATALOG_ENTRY; - return VOICE_CATALOG.find((entry) => entry.id === id); -} - -export function isVoiceProviderId(value: string): value is VoiceProviderId { - if (value === "scripted") return scriptedVoiceEnabled(); - return VOICE_CATALOG.some((entry) => entry.id === value); -} - -/** Construct the provider adapter selected by a persisted voice credential. */ -export function createVoiceProvider(kind: string): VoiceProvider { - switch (kind) { - case "elevenlabs": - return new ElevenLabsVoiceProvider(); - case "openai": - return new OpenAIVoiceProvider(); - case "cartesia": - return new CartesiaVoiceProvider(); - case "fish-audio": - return new FishAudioVoiceProvider(); - case "scripted": - if (!scriptedVoiceEnabled()) break; - return new ScriptedVoiceProvider(); - default: - break; - } - throw new Error( - `Unknown voice provider "${kind}". Use elevenlabs | openai | cartesia | fish-audio.`, - ); -} - -export class NoVoiceConfigured extends Error { - readonly reason: "key" | "voice"; - - constructor(reason: "key" | "voice") { - super( - reason === "key" - ? "Add a voice provider key in Voice settings to turn on speaking." - : "Pick a voice in Voice settings.", - ); - this.reason = reason; - this.name = "NoVoiceConfigured"; - } -} - -export const MAX_SPEAK_CHARS = 2000; -export const MAX_TRANSCRIBE_BYTES = 8 * 1024 * 1024; diff --git a/packages/adapters/src/voice-http.test.ts b/packages/adapters/src/voice-http.test.ts deleted file mode 100644 index 68adbf71..00000000 --- a/packages/adapters/src/voice-http.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { - MAX_VOICE_JSON_BYTES, - readVoiceJson, - speechUploadName, - verifyVoiceHttpGet, - voiceDeadline, -} from "./voice-http.js"; - -describe("voiceDeadline", () => { - it("aborts when the client signal aborts", () => { - const client = new AbortController(); - const combined = voiceDeadline(client.signal, 20_000); - expect(combined.aborted).toBe(false); - client.abort(); - expect(combined.aborted).toBe(true); - }); - - it("aborts when the deadline elapses even if the client stays connected", async () => { - const combined = voiceDeadline(new AbortController().signal, 1); - await new Promise((resolve, reject) => { - const guard = setTimeout(() => reject(new Error("deadline did not abort")), 1_000); - combined.addEventListener( - "abort", - () => { - clearTimeout(guard); - resolve(); - }, - { once: true }, - ); - }); - expect(combined.aborted).toBe(true); - }); -}); - -describe("speechUploadName", () => { - it("keeps webm recordings as webm even when they name an opus codec", () => { - expect(speechUploadName("audio/webm;codecs=opus")).toBe("speech.webm"); - }); - - it("maps Firefox ogg capture to an ogg filename", () => { - expect(speechUploadName("audio/ogg; codecs=opus")).toBe("speech.ogg"); - }); -}); - -describe("verifyVoiceHttpGet", () => { - afterEach(() => { - vi.unstubAllGlobals(); - }); - - it("returns ok when the provider accepts the key", async () => { - const fetch = vi.fn().mockResolvedValue(new Response(null, { status: 200 })); - vi.stubGlobal("fetch", fetch); - - await expect( - verifyVoiceHttpGet({ - url: "https://api.example/voices", - headers: { authorization: "Bearer key" }, - signal: new AbortController().signal, - provider: "Example", - }), - ).resolves.toEqual({ ok: true }); - expect(fetch).toHaveBeenCalledOnce(); - const [, init] = fetch.mock.calls[0]!; - expect(init.method).toBeUndefined(); - expect(init.headers).toEqual({ authorization: "Bearer key" }); - expect(init.signal).toBeInstanceOf(AbortSignal); - }); - - it("returns the key-rejected message without throwing", async () => { - vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 401 }))); - - await expect( - verifyVoiceHttpGet({ - url: "https://api.example/voices", - headers: {}, - signal: new AbortController().signal, - provider: "ElevenLabs", - }), - ).resolves.toEqual({ - ok: false, - message: "ElevenLabs rejected that key. Check the key and that it has speech permissions.", - }); - }); - - it("includes the provider detail when checking the key fails", async () => { - vi.stubGlobal( - "fetch", - vi - .fn() - .mockResolvedValue( - new Response(JSON.stringify({ detail: "voice quota" }), { status: 500 }), - ), - ); - - await expect( - verifyVoiceHttpGet({ - url: "https://api.example/voices", - headers: {}, - signal: new AbortController().signal, - provider: "OpenAI", - }), - ).resolves.toEqual({ - ok: false, - message: "checking that key failed: voice quota", - }); - }); - - it("returns the unreachable message when fetch fails", async () => { - vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("connect ECONNREFUSED"))); - - await expect( - verifyVoiceHttpGet({ - url: "https://api.example/voices", - headers: {}, - signal: new AbortController().signal, - provider: "Cartesia", - }), - ).resolves.toEqual({ - ok: false, - message: "Couldn't reach Cartesia to check that key. Check your connection.", - }); - }); -}); - -describe("readVoiceJson", () => { - it("rejects an oversized provider response without waiting for cancellation", async () => { - const cancel = vi.fn(() => new Promise(() => undefined)); - const response = new Response(new ReadableStream({ cancel }), { - headers: { "content-length": String(MAX_VOICE_JSON_BYTES + 1) }, - }); - - await expect(readVoiceJson(response)).rejects.toThrow("Voice response is too large."); - expect(cancel).toHaveBeenCalledOnce(); - }); - - it("rejects malformed successful JSON when the caller requires a payload", async () => { - await expect(readVoiceJson(new Response("not json"), { requireValid: true })).rejects.toThrow( - "Voice provider returned invalid JSON.", - ); - }); - - it("keeps malformed error bodies optional", async () => { - await expect(readVoiceJson(new Response("not json"))).resolves.toBeNull(); - }); - - it("returns malformed text when the caller wants the raw error", async () => { - await expect( - readVoiceJson(new Response("upstream down"), { rawOnInvalid: true }), - ).resolves.toBe("upstream down"); - }); -}); diff --git a/packages/adapters/src/voice-http.ts b/packages/adapters/src/voice-http.ts deleted file mode 100644 index 179bb321..00000000 --- a/packages/adapters/src/voice-http.ts +++ /dev/null @@ -1,155 +0,0 @@ -import type { VoiceVerifyResult } from "@milo/adapter-kit"; -import { readBodyCapped } from "./web-ssrf.js"; - -/** A 2,000-character utterance should stay far below this, even at high MP3 bitrates. */ -export const MAX_SYNTHESIZED_AUDIO_BYTES = 16 * 1024 * 1024; -export const MAX_VOICE_JSON_BYTES = 1024 * 1024; - -/** Client disconnect plus a hard deadline — `context.signal` is always set. */ -export function voiceDeadline(signal: AbortSignal, ms: number): AbortSignal { - return AbortSignal.any([signal, AbortSignal.timeout(ms)]); -} - -export async function readVoiceAudio(res: Response, signal?: AbortSignal): Promise { - return readVoiceBytes(res, MAX_SYNTHESIZED_AUDIO_BYTES, signal); -} - -async function readVoiceBytes( - res: Response, - maxBytes: number, - signal?: AbortSignal, -): Promise { - const declared = Number(res.headers?.get("content-length") ?? 0); - if (Number.isFinite(declared) && declared > maxBytes) { - cancelResponseBody(res); - throw new Error("Voice response is too large."); - } - try { - return await readBodyCapped(res, maxBytes, signal); - } catch (error) { - if (error instanceof Error && error.message === "Response is too large") { - throw new Error("Voice response is too large."); - } - throw error; - } -} - -function cancelResponseBody(res: Response): void { - try { - void Promise.resolve(res.body?.cancel()).catch(() => undefined); - } catch { - // Provider response cleanup is best-effort and must not delay the size error. - } -} - -export function speechUploadName(mimeType?: string): string { - const mime = (mimeType ?? "").split(";")[0]?.trim().toLowerCase() ?? ""; - if (mime.includes("webm")) return "speech.webm"; - if (mime.includes("ogg") || mime.includes("opus")) return "speech.ogg"; - if (mime.includes("wav")) return "speech.wav"; - if (mime.includes("mpeg") || mime.includes("mp3")) return "speech.mp3"; - if (mime.includes("mp4") || mime.includes("m4a") || mime.includes("aac")) return "speech.m4a"; - return "speech.webm"; -} - -export async function readVoiceJson( - res: Response, - options: { requireValid?: boolean; rawOnInvalid?: boolean } = {}, -): Promise { - let bytes: Uint8Array; - try { - bytes = await readVoiceBytes(res, MAX_VOICE_JSON_BYTES); - } catch (error) { - if (error instanceof Error && error.message === "Voice response is too large.") throw error; - if (options.requireValid) throw new Error("Voice provider response could not be read."); - return null; - } - const text = new TextDecoder().decode(bytes); - try { - return JSON.parse(text); - } catch { - if (options.requireValid) throw new Error("Voice provider returned invalid JSON."); - return options.rawOnInvalid ? text : null; - } -} - -function detail(body: unknown): string { - if (!body || typeof body !== "object") return ""; - const record = body as Record; - if (typeof record.detail === "string" && record.detail.trim()) return record.detail.trim(); - if ( - record.detail && - typeof record.detail === "object" && - typeof (record.detail as { message?: unknown }).message === "string" - ) { - return String((record.detail as { message: string }).message).trim(); - } - if (typeof record.message === "string" && record.message.trim()) return record.message.trim(); - if (typeof record.error === "string" && record.error.trim()) return record.error.trim(); - if ( - record.error && - typeof record.error === "object" && - typeof (record.error as { message?: unknown }).message === "string" - ) { - return String((record.error as { message: string }).message).trim(); - } - return ""; -} - -export function voiceUnreachable(provider: string): string { - return `Couldn't reach ${provider} to check that key. Check your connection.`; -} - -export function voiceHttpError( - status: number, - provider: string, - what: string, - body: unknown, -): string { - const theirs = detail(body); - if (status === 401 || status === 403) { - return `${provider} rejected that key. Check the key and that it has speech permissions.`; - } - if (status === 429) - return theirs || `${provider} is rate-limiting this account. Wait a moment and try again.`; - if (status === 402) return theirs || `${provider} says this account is out of credit.`; - return theirs ? `${what} failed: ${theirs}` : `${what} failed (${status})`; -} - -export async function requireOk(res: Response, provider: string, what: string): Promise { - if (res.ok) return res; - throw new Error(voiceHttpError(statusFor(res), provider, what, await readVoiceJson(res))); -} - -export async function verifyVoiceHttpGet(options: { - url: string; - headers: Record; - signal: AbortSignal; - provider: string; -}): Promise { - try { - const res = await fetch(options.url, { - headers: options.headers, - signal: voiceDeadline(options.signal, 20_000), - }); - if (res.ok) return { ok: true }; - return { - ok: false, - message: voiceHttpError( - res.status, - options.provider, - "checking that key", - await readVoiceJson(res), - ), - }; - } catch { - return { - ok: false, - message: voiceUnreachable(options.provider), - }; - } -} - -function statusFor(res: Response) { - return res.status; -} diff --git a/packages/contracts/src/ai-consent.ts b/packages/contracts/src/ai-consent.ts index e7f6dcee..2f85d387 100644 --- a/packages/contracts/src/ai-consent.ts +++ b/packages/contracts/src/ai-consent.ts @@ -2,13 +2,11 @@ import * as z from "zod"; export const AI_DISCLOSURE_VERSION = "2026-09-14"; export const AI_PRIVACY_URL = "https://rakazo.com/privacy/"; -export const AiDataUseSchema = z.enum(["model", "voice"]); +export const AiDataUseSchema = z.enum(["model"]); export type AiDataUse = z.infer; export const AI_DATA_DISCLOSURES: Record = { model: "Messages, relevant conversation history, bot instructions, memories, attachments, screenshots, and connected-app content used by your bots are sent to generate responses and carry out tasks, including scheduled tasks.", - voice: - "Audio you record is sent for transcription. Text you choose to play, including bot responses, is sent to generate speech.", }; export const AiConsentQuerySchema = z .object({ diff --git a/packages/contracts/src/domain.ts b/packages/contracts/src/domain.ts index df99476b..4b66e848 100644 --- a/packages/contracts/src/domain.ts +++ b/packages/contracts/src/domain.ts @@ -59,8 +59,6 @@ export const BotSchema = z.object({ computerMode: ComputerModeSchema, updatedAt: z.string(), createdAt: z.string(), - voiceId: z.string().nullable(), - autoSpeak: z.boolean(), modelProvider: z.string().nullable(), modelId: z.string().nullable(), thinkingLevel: ThinkingLevelSchema.nullable(), @@ -253,8 +251,6 @@ export const UpdateBotInput = z color: BotAvatarValueSchema.optional(), pinned: z.boolean().optional(), sectionId: Id.nullable().optional(), - voiceId: z.string().max(120).nullable().optional(), - autoSpeak: z.boolean().optional(), modelProvider: z.string().trim().min(1).max(80).nullable().optional(), modelId: z.string().trim().min(1).max(200).nullable().optional(), thinkingLevel: ThinkingLevelSchema.nullable().optional(), @@ -928,42 +924,6 @@ export const ModelCatalogEntrySchema = z.object({ }); export type ModelCatalogEntry = z.infer; -export const VoiceCatalogEntrySchema = z.object({ - id: z.string(), - name: z.string(), - description: z.string(), - transcribe: z.boolean(), -}); -export type VoiceCatalogEntry = z.infer; - -export const VoiceInfoSchema = z.object({ - id: z.string(), - label: z.string(), - description: z.string().optional(), -}); -export type VoiceInfo = z.infer; - -export const VoiceCredentialSchema = z.object({ - id: Id, - provider: z.string(), - hasKey: z.boolean(), - isDefault: z.boolean(), - voiceId: z.string(), - /** Fish speech-model override. Empty uses the deployment default. */ - speechModel: z.string(), - transcribe: z.boolean(), -}); -export type VoiceCredential = z.infer; - -export const VoiceStatusSchema = z.object({ - configured: z.boolean(), - ready: z.boolean(), - transcribe: z.boolean(), - provider: z.string().nullable(), - voiceId: z.string(), -}); -export type VoiceStatus = z.infer; - export const DeploymentSettingsSchema = z.object({ ownerUserId: Id.nullable(), signupsEnabled: z.boolean(), diff --git a/packages/contracts/src/index.test.ts b/packages/contracts/src/index.test.ts index f98653f8..49d57821 100644 --- a/packages/contracts/src/index.test.ts +++ b/packages/contracts/src/index.test.ts @@ -230,7 +230,6 @@ describe("contracts", () => { expect(appContract.botSections.update).toBeTruthy(); expect(appContract.threads.subscribe).toBeTruthy(); expect(appContract.threads.clear).toBeTruthy(); - expect(appContract.voice.prepare).toBeTruthy(); expect(appContract.agentSecrets.list).toBeTruthy(); expect(appContract.agentSecrets.put).toBeTruthy(); expect(appContract.agentSecrets.remove).toBeTruthy(); diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 9fd31873..f0c1c504 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -72,10 +72,6 @@ import { UpdateBotInput, UpdateGroupInput, UsageRecordSchema, - VoiceCatalogEntrySchema, - VoiceCredentialSchema, - VoiceInfoSchema, - VoiceStatusSchema, } from "./domain.js"; import { ComputerEgressPolicySchema, ComputerEgressSchema } from "./egress.js"; import { ComputerCommandSchema, ProductEventSchema } from "./events.js"; @@ -337,24 +333,10 @@ export const appContract = { .input( threadTarget.safeExtend({ text: z.string().min(1), - /** Carries the call id, so a turn taken mid-run stays in the call's card. */ clientNonce: z.string().min(1).max(200).optional(), }), ) .output(z.object({ ok: z.literal(true) })), - /** The client hung up: close the call card and let the bot finish what was asked on it. */ - endCall: oc - // ":" separates the call id from the nonce suffix, so it can never appear inside one. - .input( - botId.safeExtend({ - callId: z - .string() - .min(1) - .max(200) - .regex(/^[^:]+$/), - }), - ) - .output(z.object({ ok: z.literal(true) })), clear: oc.input(threadTarget).output(z.object({ ok: z.literal(true) })), answer: oc .input( @@ -785,42 +767,6 @@ export const appContract = { runs: { list: oc.input(z.object({ filter: z.enum(["active", "recent"]) })).output(RunsListOutputSchema), }, - voice: { - catalog: oc.output(z.array(VoiceCatalogEntrySchema)), - status: oc.output(VoiceStatusSchema), - credentials: oc.output(z.array(VoiceCredentialSchema)), - connect: oc - .input( - z.object({ - provider: z.string(), - apiKey: z.string().min(8), - voiceId: z.string().max(120).optional(), - speechModel: z.string().max(64).optional(), - }), - ) - .output(VoiceCredentialSchema), - disconnect: oc - .input(z.object({ provider: z.string().min(1) })) - .output(z.object({ ok: z.literal(true) })), - setVoice: oc - .input(z.object({ voiceId: z.string().min(1).max(120), provider: z.string().optional() })) - .output(VoiceStatusSchema), - setSpeechModel: oc - .input(z.object({ provider: z.string().min(1), speechModel: z.string().max(64) })) - .output(VoiceCredentialSchema), - voices: oc - .input(z.object({ provider: z.string().optional() })) - .output(z.array(VoiceInfoSchema)), - prepare: oc - .input( - z.object({ - text: z.string().max(20000), - voiceId: z.string().max(120).optional(), - botId: Id.optional(), - }), - ) - .output(z.object({ ready: z.boolean(), utterances: z.array(z.string()) })), - }, agentSecrets: { list: oc.output(z.array(AgentSecretSchema)), put: oc.input(AgentSecretInputSchema).output(AgentSecretSchema), diff --git a/packages/core/src/ai-consent.test.ts b/packages/core/src/ai-consent.test.ts index 65586efa..ceefefe6 100644 --- a/packages/core/src/ai-consent.test.ts +++ b/packages/core/src/ai-consent.test.ts @@ -15,14 +15,6 @@ const status: AiConsentStatus = { privacyUrl: "https://example.com/privacy", allowed: false, }, - { - key: "voice", - name: "Example Voice", - use: "voice", - detail: "", - privacyUrl: "https://example.com/privacy", - allowed: false, - }, ], }; @@ -85,7 +77,6 @@ describe("foreground AI consent", () => { expect(prompt).not.toHaveBeenCalled(); expect(aiDataUsesForProcedure("threads/get")).toEqual([]); expect(aiDataUsesForProcedure("threads/send")).toEqual(["model"]); - expect(aiDataUsesForProcedure("voice/prepare")).toEqual(["voice"]); expect( aiDataUsesForProcedure("routines/update", { routineId: "routine", active: false }), ).toEqual([]); @@ -123,7 +114,7 @@ describe("foreground AI consent", () => { keys: ["model"], }); }); - it("does not share a pending grant across account-space scopes or recipients", async () => { + it("does not share a pending grant across account-space scopes", async () => { const prompt = vi.fn(async () => true); const allow = vi.fn(async () => undefined); const statuses = [ @@ -137,25 +128,20 @@ describe("foreground AI consent", () => { scope: "account-b-space", recipients: [status.recipients[0]!], }, - { - ...status, - scope: "account-a-space", - recipients: [status.recipients[1]!], - }, ]; await Promise.all( statuses.map((current) => ensureAiDataConsent({ - uses: ["model", "voice"], + uses: ["model"], status: async () => current, prompt, allow, }), ), ); - expect(prompt).toHaveBeenCalledTimes(3); - expect(allow).toHaveBeenCalledTimes(3); + expect(prompt).toHaveBeenCalledTimes(2); + expect(allow).toHaveBeenCalledTimes(2); }); it("does not share a grant across independent API contexts", async () => { const prompt = vi.fn(async () => true); diff --git a/packages/core/src/ai-consent.ts b/packages/core/src/ai-consent.ts index ca77ceac..4eceb7ba 100644 --- a/packages/core/src/ai-consent.ts +++ b/packages/core/src/ai-consent.ts @@ -34,7 +34,6 @@ export function aiDataUsesForProcedure(procedure: string, input?: unknown): AiDa ].includes(path) ) return ["model"]; - if (["voice/prepare", "voice/speak", "voice/transcribe"].includes(path)) return ["voice"]; return []; } diff --git a/packages/core/src/barge-in.test.ts b/packages/core/src/barge-in.test.ts deleted file mode 100644 index 5443bb16..00000000 --- a/packages/core/src/barge-in.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { afterEach, describe, expect, it } from "vitest"; -import { isCallBargeIn, isInterimCallBargeIn } from "./barge-in.js"; -import { spokenMemory } from "./echo.js"; - -const SPOKEN = "I'm here and hearing you"; - -describe("call barge-in", () => { - afterEach(() => { - spokenMemory.clear(); - }); - - it.each(["stop", "Stop!", "WAIT", "hold on", "Hold on.", "pause", "no"])( - "lets the interruption %j cut a reply short", - (text) => { - expect(isCallBargeIn(text)).toBe(true); - }, - ); - - it("lets a sentence cut a reply short", () => { - expect(isCallBargeIn("wait, what about the deploy")).toBe(true); - expect(isInterimCallBargeIn("what about the deploy")).toBe(true); - }); - - it("keeps playing through a one-word backchannel", () => { - expect(isCallBargeIn("yeah")).toBe(false); - expect(isInterimCallBargeIn("yeah")).toBe(false); - expect(isInterimCallBargeIn("stop")).toBe(false); - }); - - it("ignores the reply leaking back at the playback threshold", () => { - spokenMemory.remember(SPOKEN); - expect(isCallBargeIn("I am here what about that")).toBe(false); - expect(isInterimCallBargeIn("I am here and hearing")).toBe(false); - }); - - it("ignores an empty transcript", () => { - expect(isCallBargeIn(" ")).toBe(false); - expect(isInterimCallBargeIn("")).toBe(false); - }); -}); diff --git a/packages/core/src/barge-in.ts b/packages/core/src/barge-in.ts deleted file mode 100644 index a890a64a..00000000 --- a/packages/core/src/barge-in.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { spokenMemory } from "./echo.js"; - -/** Lower echo match while audio plays: most of what the mic hears is the speaker. */ -const PLAYBACK_ECHO_RATIO = 0.4; -/** The only one-word turns worth cutting a reply short for. */ -const INTERRUPT_WORDS = new Set(["stop", "wait", "hold on", "pause", "no"]); - -/** - * How long an interim phrase must stand before it cuts playback. - * The final transcript arrives later, after the reply has already finished. - */ -export const INTERIM_BARGE_IN_MS = 300; - -/** A sentence, or one interruption word, that is not the reply leaking back into the mic. */ -export function isCallBargeIn(text: string): boolean { - if (spokenMemory.isEcho(text, PLAYBACK_ECHO_RATIO)) return false; - const cleaned = cleanWords(text); - return cleaned.includes(" ") || INTERRUPT_WORDS.has(cleaned); -} - -/** An interim is revised word by word, so one stray word never cuts playback. */ -export function isInterimCallBargeIn(text: string): boolean { - return cleanWords(text).includes(" ") && !spokenMemory.isEcho(text, PLAYBACK_ECHO_RATIO); -} - -function cleanWords(text: string): string { - return text - .toLowerCase() - .replace(/[^\p{L}\p{N}\s]+/gu, " ") - .trim() - .replace(/\s+/g, " "); -} diff --git a/packages/core/src/call-nonce.test.ts b/packages/core/src/call-nonce.test.ts deleted file mode 100644 index 83e81fef..00000000 --- a/packages/core/src/call-nonce.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { callClientNonce, callIdFromClientNonce, isCallClientNonce } from "./call-nonce.js"; - -describe("call client nonce", () => { - it("round-trips the call id", () => { - const nonce = callClientNonce("call-1"); - expect(isCallClientNonce(nonce)).toBe(true); - expect(callIdFromClientNonce(nonce)).toBe("call-1"); - }); - - it("stays unique per message within one call", () => { - expect(callClientNonce("call-1")).not.toBe(callClientNonce("call-1")); - }); - - it("rejects a call id that would blur the nonce format", () => { - expect(() => callClientNonce("call:1")).toThrow(); - }); - - it("reads the id up to the unique suffix, not the first colon", () => { - expect(callIdFromClientNonce("call:call:1:abc")).toBe("call:1"); - expect(callIdFromClientNonce("call:call-1")).toBeUndefined(); - }); - - it("rejects plain nonces and other prefixed nonces", () => { - for (const nonce of [null, undefined, "", "abc-123", "user-progress:run-1:0:x:y"]) { - expect(isCallClientNonce(nonce)).toBe(false); - expect(callIdFromClientNonce(nonce)).toBeUndefined(); - } - }); -}); diff --git a/packages/core/src/call-nonce.ts b/packages/core/src/call-nonce.ts deleted file mode 100644 index 1a8d24bc..00000000 --- a/packages/core/src/call-nonce.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * clientNonce prefix for messages a client sends from a live voice call. The - * nonce is the only channel that carries the call's identity: the server reads - * it to answer in spoken sentences, and clients group one call's exchange into - * a single transcript card. - */ -export const CALL_CLIENT_NONCE_PREFIX = "call:"; - -export function callClientNonce(callId: string): string { - if (callId.includes(":")) throw new Error(`callId must not contain ":": ${callId}`); - const unique = - globalThis.crypto?.randomUUID?.() ?? - `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; - return `${CALL_CLIENT_NONCE_PREFIX}${callId}:${unique}`; -} - -export function isCallClientNonce(clientNonce: string | null | undefined): boolean { - return Boolean(clientNonce?.startsWith(CALL_CLIENT_NONCE_PREFIX)); -} - -export function callIdFromClientNonce(clientNonce: string | null | undefined): string | undefined { - if (!clientNonce || !isCallClientNonce(clientNonce)) return undefined; - const rest = clientNonce.slice(CALL_CLIENT_NONCE_PREFIX.length); - const suffixAt = rest.lastIndexOf(":"); - return suffixAt === -1 ? undefined : rest.slice(0, suffixAt) || undefined; -} diff --git a/packages/core/src/echo.test.ts b/packages/core/src/echo.test.ts deleted file mode 100644 index 2422e18d..00000000 --- a/packages/core/src/echo.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { isEchoOfSpeech, SpokenMemory } from "./echo.js"; - -const SPOKEN = "I'm here and hearing you…"; - -describe("isEchoOfSpeech", () => { - it("catches a fragment of the reply that just played", () => { - expect(isEchoOfSpeech("I am here in", SPOKEN)).toBe(true); - }); - - it("catches a fragment with filler around it", () => { - expect(isEchoOfSpeech("hey I am here and here", SPOKEN)).toBe(true); - }); - - it("keeps a genuine short turn", () => { - expect(isEchoOfSpeech("what should we do next", SPOKEN)).toBe(false); - }); - - it("keeps a long turn that happens to share words", () => { - expect( - isEchoOfSpeech( - "I am not sure you are hearing me so let me say the whole thing again from the top", - SPOKEN, - ), - ).toBe(false); - }); - - it("drops a looser overlap only at the playback threshold", () => { - expect(isEchoOfSpeech("I am here what about that", SPOKEN)).toBe(false); - expect(isEchoOfSpeech("I am here what about that", SPOKEN, 0.4)).toBe(true); - }); - - it("keeps everything when nothing was spoken", () => { - expect(isEchoOfSpeech("I am here in", "")).toBe(false); - }); - - const NEWSPAPER = "Happy to, but I'm not sure which newspaper you mean"; - - it("catches a 2-word echo that leads the spoken line", () => { - expect(isEchoOfSpeech("happy to", NEWSPAPER)).toBe(true); - }); - - it("catches a 2-word echo adjacent mid-line", () => { - expect(isEchoOfSpeech("tell me", "…just tell me the client…")).toBe(true); - }); - - it("catches a 2-word echo further in the line", () => { - expect(isEchoOfSpeech("new project", "…tell me which new project you meant…")).toBe(true); - }); - - it("drops a 2-word pair that isn't adjacent in the line", () => { - expect(isEchoOfSpeech("hello there", NEWSPAPER)).toBe(false); - }); - - it("keeps a single word, never an echo", () => { - expect(isEchoOfSpeech("yes", NEWSPAPER)).toBe(false); - }); - - it("drops a 2-word pair that only appears non-adjacently", () => { - expect(isEchoOfSpeech("happy sure", NEWSPAPER)).toBe(false); - }); -}); - -describe("SpokenMemory", () => { - it("catches an echo of a reply the bot has already spoken past", () => { - const memory = new SpokenMemory(); - memory.remember(SPOKEN, 0); - memory.remember("Booked for Friday", 1_000); - - expect(memory.isEcho("hey I am here and here", undefined, 2_000)).toBe(true); - }); - - it("catches a line the mic heard across two spoken sentences", () => { - const memory = new SpokenMemory(); - memory.remember("Okay, give me a second", 0); - memory.remember("I am checking the deploy now", 500); - - expect(memory.isEcho("a second I am checking", undefined, 1_000)).toBe(true); - }); - - it("forgets what was spoken more than the window ago", () => { - const memory = new SpokenMemory(); - memory.remember(SPOKEN, 0); - - expect(memory.isEcho("hey I am here and here", undefined, 14_000)).toBe(true); - expect(memory.isEcho("hey I am here and here", undefined, 16_000)).toBe(false); - }); - - it("keeps a genuine turn, and everything once cleared", () => { - const memory = new SpokenMemory(); - memory.remember(SPOKEN, 0); - - expect(memory.isEcho("what should we do next", undefined, 100)).toBe(false); - memory.clear(); - expect(memory.isEcho("hey I am here and here", undefined, 100)).toBe(false); - }); -}); diff --git a/packages/core/src/echo.ts b/packages/core/src/echo.ts deleted file mode 100644 index 1cfb1122..00000000 --- a/packages/core/src/echo.ts +++ /dev/null @@ -1,103 +0,0 @@ -/** A heard line longer than this is a real turn, however much it overlaps the reply. */ -const MAX_ECHO_WORDS = 12; -/** Fewer matched words than this is coincidence, not the speaker leaking into the mic. */ -const MIN_ECHO_WORDS = 3; -const ECHO_MATCH_RATIO = 0.6; - -const CONTRACTIONS: Record = { - m: "am", - re: "are", - s: "is", - ll: "will", - ve: "have", - d: "would", -}; - -/** Dictation writes out what speech contracts, so "I'm" must compare equal to "I am". */ -function words(text: string): string[] { - return text - .toLowerCase() - .replace(/n['’]t\b/g, " not") - .replace(/['’](m|re|s|ll|ve|d)\b/g, (_match, tail: string) => ` ${CONTRACTIONS[tail]}`) - .replace(/[^\p{L}\p{N}\s]+/gu, " ") - .split(/\s+/) - .filter(Boolean); -} - -/** - * True when a transcript is the microphone catching the reply that just played. - * - * `threshold` is the share of heard words that must match; lower it while audio is - * still playing, when far more of what the mic picks up is the speaker. - * - * ponytail: in-order word overlap, no acoustics. It can still drop a short genuine - * turn that quotes the reply back; move to an energy/echo-cancellation signal from - * the audio graph if that shows up in practice. - */ -export function isEchoOfSpeech( - heard: string, - spoken: string, - threshold = ECHO_MATCH_RATIO, -): boolean { - const heardWords = words(heard); - const spokenWords = words(spoken); - if (heardWords.length > MAX_ECHO_WORDS || !spokenWords.length) return false; - if (heardWords.length === 2) { - return spokenWords.some( - (word, i) => word === heardWords[0] && spokenWords[i + 1] === heardWords[1], - ); - } - let cursor = 0; - let matched = 0; - for (const word of heardWords) { - const at = spokenWords.indexOf(word, cursor); - if (at === -1) continue; - matched += 1; - cursor = at + 1; - } - if (matched < MIN_ECHO_WORDS) return false; - return matched / heardWords.length >= threshold; -} - -/** How long a spoken line can still come back through the microphone. */ -const ECHO_MEMORY_MS = 15_000; -/** More than one call's worth of turns inside the window; older ones are dropped. */ -const ECHO_MEMORY_MAX = 16; - -/** - * Every line the speaker played recently. Matching only against the last one misses - * the common case: by the time the microphone delivers an echo, a newer reply has - * already taken that slot. - */ -export class SpokenMemory { - private entries: { text: string; at: number }[] = []; - - remember(text: string, now = Date.now()): void { - const trimmed = text.trim(); - if (!trimmed) return; - this.entries.push({ text: trimmed, at: now }); - this.prune(now); - } - - clear(): void { - this.entries = []; - } - - /** - * ponytail: one in-order match against the window's lines joined in order. That - * subsumes every consecutive run inside it, so a heard line spanning two replies - * matches without comparing each pair — at the cost of also matching words picked - * from lines further apart. Compare runs pairwise if that drops real turns. - */ - isEcho(heard: string, threshold?: number, now = Date.now()): boolean { - this.prune(now); - return isEchoOfSpeech(heard, this.entries.map((entry) => entry.text).join(". "), threshold); - } - - private prune(now: number): void { - const cutoff = now - ECHO_MEMORY_MS; - this.entries = this.entries.filter((entry) => entry.at >= cutoff).slice(-ECHO_MEMORY_MAX); - } -} - -export const spokenMemory = new SpokenMemory(); diff --git a/packages/core/src/farewell.test.ts b/packages/core/src/farewell.test.ts deleted file mode 100644 index a977240e..00000000 --- a/packages/core/src/farewell.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { isFarewell } from "./farewell.js"; - -describe("isFarewell", () => { - it.each([ - "That's all", - "ok thanks, bye!", - "Goodbye", - "that'll be all for now", - "hang up", - "End the call.", - "alright, I'm done, thanks", - ])("hears %j as the end of the call", (text) => { - expect(isFarewell(text)).toBe(true); - }); - - it.each([ - "bye the way, can you check the deploy", - "that's all wrong, redo it", - "tell me about goodbye songs", - "I'm done with the draft, what's next", - "", - "before we wrap up that's all I had on the deploy today", - ])("keeps the call going for %j", (text) => { - expect(isFarewell(text)).toBe(false); - }); -}); diff --git a/packages/core/src/farewell.ts b/packages/core/src/farewell.ts deleted file mode 100644 index 755e8a63..00000000 --- a/packages/core/src/farewell.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** Lead-ins and tails that may wrap a closing phrase without changing what it means. */ -const FILLER = [ - "thank you", - "for today", - "for now", - "alright", - "perfect", - "thanks", - "great", - "okay", - "cool", - "bye", - "ok", -]; - -const CLOSING = [ - "that'll be all", - "that will be all", - "that's all for now", - "that's everything", - "that's all", - "that's it", - "talk to you later", - "catch you later", - "talk later", - "goodbye", - "good bye", - "see you", - "see ya", - "end the call", - "end call", - "hang up", - "i'm done", - "we're done", - "nothing else", - "bye", -]; - -const filler = FILLER.join("|"); -// Whole-utterance only: a closing phrase alone, give or take filler on either side. -const FAREWELL = new RegExp(`^(?:(?:${filler}) )*(?:${CLOSING.join("|")})(?: (?:${filler}))*$`); -const MAX_WORDS = 8; - -/** True when the whole utterance is the caller saying goodbye, not a sentence mentioning one. */ -export function isFarewell(text: string): boolean { - const words = text - .toLowerCase() - .replace(/[‘’]/g, "'") - .replace(/[^a-z0-9'\s]+/g, " ") - .trim() - .split(/\s+/) - .filter(Boolean); - if (!words.length || words.length > MAX_WORDS) return false; - return FAREWELL.test(words.join(" ")); -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 24019391..5e4a338d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -7,21 +7,17 @@ export * from "./async.js"; export * from "./attachments.js"; export * from "./avatar-motion.js"; export * from "./avatar-shape.js"; -export * from "./barge-in.js"; export * from "./bot-avatar-colors.js"; export * from "./bot-avatar-shapes.js"; export * from "./bot-messages.js"; export * from "./bot-sections.js"; -export * from "./call-nonce.js"; export * from "./compose-update.js"; export * from "./composer-mention-picker.js"; export * from "./composer-mentions.js"; export * from "./composer-slash.js"; export * from "./computer-updates.js"; export * from "./cron.js"; -export * from "./echo.js"; export * from "./events.js"; -export * from "./farewell.js"; export * from "./featured-connectors.js"; export * from "./group-mentions.js"; export * from "./http-response.js"; @@ -42,7 +38,6 @@ export * from "./search.js"; export * from "./secrets-guard.js"; export * from "./self-update.js"; export * from "./signup-policy.js"; -export * from "./speech-text.js"; export * from "./stuck-work.js"; export * from "./teach-playbook.js"; export * from "./teach-recording.js"; @@ -50,4 +45,3 @@ export * from "./text-direction.js"; export * from "./thread-message-updates.js"; export * from "./thread-subscription.js"; export * from "./tool-activity.js"; -export * from "./voice-chat-groups.js"; diff --git a/packages/core/src/speech-text.test.ts b/packages/core/src/speech-text.test.ts deleted file mode 100644 index acb66f7e..00000000 --- a/packages/core/src/speech-text.test.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - narrateTool, - speakable, - speechFromBlocks, - spokenDecision, - toUtterances, -} from "./speech-text.js"; - -describe("speakable", () => { - it("names a code block instead of reading it", () => { - const out = speakable( - "Here's the fix:\n\n```ts\nconst x: number = 1;\nif (x) throw new Error('no');\n```\n\nThat's it.", - ); - expect(out).toContain("TypeScript code block"); - expect(out).not.toContain("const x"); - expect(out).not.toContain("throw"); - expect(out).toContain("That's it."); - }); - - it("closes an unterminated fence rather than swallowing the rest", () => { - const out = speakable("Working on it:\n\n```sh\nnpm test"); - expect(out).toContain("Working on it"); - expect(out).toContain("code block"); - expect(out).not.toContain("npm test"); - }); - - it("keeps a link's words and drops its URL", () => { - expect(speakable("See [the README](https://example.com/a/b?c=d) for more")).toBe( - "See the README for more", - ); - }); - - it("turns a bare URL into a noun", () => { - expect(speakable("Deployed to https://status.example.com/health now")).toBe( - "Deployed to a link now", - ); - }); - - it("says the file, not the path to it", () => { - expect(speakable("I changed server/drivers/acp/core.ts today")).toBe("I changed core.ts today"); - }); - - it("keeps short inline code but not long snippets", () => { - expect(speakable("Run `pnpm test` first")).toBe("Run pnpm test first"); - const long = speakable(`Use \`${"x".repeat(60)}\` here`); - expect(long).toBe("Use that snippet here"); - }); - - it("strips list scaffolding but keeps the pause between items", () => { - const out = speakable("- first thing\n- second thing\n- third thing"); - expect(out).toBe("first thing. second thing. third thing"); - }); - - it("reads a table as rows, not pipes", () => { - const out = speakable("| Name | State |\n| --- | --- |\n| Scout | idle |"); - expect(out).not.toContain("|"); - expect(out).not.toContain("---"); - expect(out).toContain("Scout, idle"); - }); - - it("drops emphasis markers, emoji and checkboxes", () => { - expect(speakable("**Done** ✅ — [x] shipped the _thing_")).toBe("Done — shipped the thing"); - }); - - it("gives a heading a full stop so the voice breathes", () => { - expect(speakable("## Results\nAll green")).toBe("Results. All green"); - }); - - it("collapses the punctuation its own substitutions create", () => { - expect(speakable("Done.\n\n\n- one\n\n- two")).toBe("Done. one. two"); - }); - - it("is empty for empty input", () => { - expect(speakable("")).toBe(""); - expect(speakable(" \n\n ")).toBe(""); - }); - - it("joins message blocks into something a voice can read", () => { - expect( - speechFromBlocks([ - { kind: "text", text: "Done." }, - { kind: "ask", text: "Ship it?", status: "pending" }, - ]), - ).toContain("Ship it?"); - }); -}); - -describe("toUtterances", () => { - it("splits on sentences", () => { - const out = toUtterances("The tests pass now. I changed two files. Want me to push it?"); - expect(out).toHaveLength(3); - expect(out[0]).toBe("The tests pass now."); - expect(out[2]).toBe("Want me to push it?"); - }); - - it("does not split inside a decimal or an abbreviation", () => { - const out = toUtterances( - "It dropped to 11.7 seconds per step, i.e. about half of what it was before.", - ); - expect(out).toHaveLength(1); - }); - - it("glues a fragment onto its neighbour", () => { - const out = toUtterances("Yes. The whole suite is green and nothing else changed."); - expect(out).toHaveLength(1); - expect(out[0]).toContain("Yes."); - }); - - it("breaks a runaway sentence at a clause, never mid-word", () => { - const long = `I looked at ${Array.from({ length: 40 }, (_, i) => `item ${i}`).join(", ")} and finished.`; - const out = toUtterances(long, { maxChars: 120 }); - expect(out.length).toBeGreaterThan(1); - for (const piece of out) expect(piece.length).toBeLessThanOrEqual(140); - expect(out.join(" ")).toContain("item 39"); - }); - - it("runs its input through the spoken register first", () => { - const out = toUtterances("Fixed it.\n\n```js\nconsole.log(1)\n```\n\nShipped."); - expect(out.join(" ")).not.toContain("console.log"); - }); - - it("is empty for text that speaks to nothing", () => { - expect(toUtterances("```\ncode only\n```")).not.toContain("code only"); - expect(toUtterances("")).toEqual([]); - }); -}); - -describe("narrateTool", () => { - it("turns tool names into something worth hearing", () => { - expect(narrateTool("Bash")).toBe("running a command"); - expect(narrateTool("Read")).toBe("reading a file"); - expect(narrateTool("Edit")).toBe("editing a file"); - expect(narrateTool("WebSearch")).toBe("searching the web"); - expect(narrateTool("screenshot")).toBe("looking at the screen"); - expect(narrateTool("computer_observe")).toBe("looking at the screen"); - expect(narrateTool("browser_snapshot")).toBe("using the page"); - expect(narrateTool("write_file")).toBe("writing a file"); - expect(narrateTool("run_subagent")).toBe("starting a subagent"); - }); - - it("sees through an MCP tool prefix", () => { - expect(narrateTool("mcp__computer__click")).toBe("using the computer"); - expect(narrateTool("mcp__agents__ask_bot")).toBe("asking a teammate"); - }); - - it("stays quiet for chips the user is already told about another way", () => { - expect(narrateTool("auto-approved Bash:git (always allowed)")).toBeNull(); - expect(narrateTool("error: claude exited 1")).toBeNull(); - expect(narrateTool("")).toBeNull(); - }); - - it("falls back to naming an unknown tool, without reading its argv", () => { - expect(narrateTool("deploy_thing")).toBe("running deploy_thing"); - expect(narrateTool('curl -X POST "https://x/y" --data @{}')).toBeNull(); - }); -}); - -describe("spokenDecision", () => { - it("accepts a clear yes or no and refuses a sentence that merely contains one", () => { - expect(spokenDecision("yes")).toBe("yes"); - expect(spokenDecision("No thanks")).toBe("no"); - expect(spokenDecision("I'm sure that's fine, go look at the logs")).toBeNull(); - expect(spokenDecision("")).toBeNull(); - }); -}); diff --git a/packages/core/src/speech-text.ts b/packages/core/src/speech-text.ts deleted file mode 100644 index 14c2fdb2..00000000 --- a/packages/core/src/speech-text.ts +++ /dev/null @@ -1,230 +0,0 @@ -import type { MessageBlock } from "@milo/contracts"; - -/** A fenced block becomes a mention of itself, with its language if known. */ -function describeCodeBlock(fence: string): string { - const lang = - fence - .trim() - .split(/\s+/)[0] - ?.replace(/[^a-z0-9+#]/gi, "") ?? ""; - const spoken: Record = { - ts: "TypeScript", - tsx: "TypeScript", - js: "JavaScript", - jsx: "JavaScript", - py: "Python", - sh: "shell", - bash: "shell", - zsh: "shell", - json: "JSON", - yml: "YAML", - yaml: "YAML", - sql: "SQL", - rs: "Rust", - go: "Go", - swift: "Swift", - diff: "diff", - }; - const name = spoken[lang.toLowerCase()]; - return name ? `. (a ${name} code block) ` : ". (a code block) "; -} - -/** `a/b/c/file.ts` → `file.ts`. A path's directories are for the eye. */ -function shortenPaths(text: string): string { - return text.replace(/(?:[\w.@-]+\/){1,}([\w.-]+\.\w{1,6})\b/g, "$1"); -} - -const ENDS_SENTENCE = /[.!?:;]\s*$/; - -/** - * Markdown (or any agent output) → a line a voice can read. - * - * Say the prose, name the artifacts, drop the syntax. Pure and synchronous - * so it stays easy to tune against real transcripts. - */ -export function speakable(input: string): string { - if (!input) return ""; - let text = input; - - text = text.replace(/```([^\n]*)\n[\s\S]*?(?:```|$)/g, (_m, fence: string) => - describeCodeBlock(fence), - ); - text = text.replace(/~~~([^\n]*)\n[\s\S]*?(?:~~~|$)/g, (_m, fence: string) => - describeCodeBlock(fence), - ); - - text = text.replace(/!\[([^\]]*)\]\([^)]*\)/g, (_m, alt: string) => - alt ? `. (image: ${alt}) ` : ". (an image) ", - ); - text = text.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1"); - text = text.replace(/\s]+>/g, " a link "); - text = text.replace(/\bhttps?:\/\/\S+/g, " a link "); - - text = text.replace(/^\s*\|?[\s:-]*\|[\s|:-]*$/gm, ""); - text = text.replace(/^\s*\|(.+)\|\s*$/gm, (_m, row: string) => - row - .split("|") - .map((cell) => cell.trim()) - .filter(Boolean) - .join(", "), - ); - - text = text.replace(/`([^`\n]+)`/g, (_m, code: string) => - code.length <= 40 ? code : " that snippet ", - ); - - text = text.replace(/^\s{0,3}#{1,6}\s+(.*)$/gm, (_m, head: string) => - ENDS_SENTENCE.test(head) ? head : `${head.trim()}.`, - ); - - text = text.replace(/^\s*[-*+]\s+/gm, ""); - text = text.replace(/^\s*\d+[.)]\s+/gm, ""); - text = text.replace(/^\s*>\s?/gm, ""); - text = text.replace(/^\s*(?:[-*_]\s*){3,}$/gm, ""); - - text = text.replace(/(\*\*|__)(.*?)\1/g, "$2"); - text = text.replace(/(\*|_)(?=\S)(.*?)(?<=\S)\1/g, "$2"); - text = text.replace(/~~(.*?)~~/g, "$1"); - - text = text.replace(/\[[ xX]\]\s*/g, ""); - - text = shortenPaths(text); - - text = text.replace( - /[\u{1F000}-\u{1FAFF}]|[\u{2600}-\u{27BF}]|[\u{FE00}-\u{FE0F}]|[\u{2190}-\u{21FF}\u{2B00}-\u{2BFF}]/gu, - "", - ); - - text = text.replace(/\n{2,}/g, ". "); - text = text.replace(/\n/g, ". "); - - text = text.replace(/\s+/g, " "); - text = text.replace(/\s+([.,!?;:])/g, "$1"); - text = text.replace(/(?:\.\s*){2,}/g, ". "); - text = text.replace(/,\s*\./g, "."); - text = text.trim(); - - return /[\p{L}\p{N}]/u.test(text) ? text : ""; -} - -const BOUNDARY = - /(? s.trim()) - .filter(Boolean); - - const out: string[] = []; - for (const piece of rough) { - const parts = piece.length <= maxChars ? [piece] : splitLong(piece, maxChars); - for (const part of parts) { - const prev = out[out.length - 1]; - if (prev && (prev.length < minChars || part.length < minChars)) { - out[out.length - 1] = `${prev} ${part}`; - } else { - out.push(part); - } - } - } - return out; -} - -function splitLong(text: string, maxChars: number): string[] { - const out: string[] = []; - let rest = text; - while (rest.length > maxChars) { - const window = rest.slice(0, maxChars); - const at = Math.max( - window.lastIndexOf(", "), - window.lastIndexOf("; "), - window.lastIndexOf(" — "), - ); - const cut = at > maxChars / 2 ? at + 1 : window.lastIndexOf(" "); - if (cut <= 0) break; - out.push(rest.slice(0, cut).trim()); - rest = rest.slice(cut).trim(); - } - if (rest) out.push(rest); - return out; -} - -/** A tool-activity chip as a spoken progress line. Null when it is not worth hearing. */ -export function narrateTool(toolName: string): string | null { - const name = toolName.replace(/^mcp__[^_]+__/, "").trim(); - if (!name) return null; - if (/^(auto-approved|error):/i.test(name)) return null; - - const bare = name.toLowerCase(); - const verbs: Array<[RegExp, string]> = [ - [/^(bash|shell|terminal|run_command|execute|computer_exec)$/, "running a command"], - [/^(read|read_file|view|list_files)$/, "reading a file"], - [/^(write|write_file|create_file)$/, "writing a file"], - [/^(edit|apply_patch|str_replace|multiedit)$/, "editing a file"], - [/^(grep|search|glob|find)$/, "searching"], - [/^(web_?search|websearch)$/, "searching the web"], - [/^(web_?fetch|fetch)$/, "reading a page"], - [/^(screenshot|computer_observe)$/, "looking at the screen"], - [/^(browser_navigate|browser_snapshot|browser_act)$/, "using the page"], - [/^(click|type_text|press_key|scroll|computer_batch|computer_act)$/, "using the computer"], - [/^open_url$/, "opening a page"], - [/^list_bots$/, "checking who's around"], - [/^ask_bot$/, "asking a teammate"], - [/^run_subagent$/, "starting a subagent"], - [/^spawn_bot$/, "creating a bot"], - [/^create_space$/, "creating a space"], - [/^(archive_bot|delete_bot)$/, "archiving a bot"], - [/^remember$/, "writing a memory"], - [/^save_shared_memory$/, "saving shared memory"], - [/^attach_file$/, "attaching a file"], - [/^request_takeover$/, "asking you to take over"], - ]; - for (const [pattern, phrase] of verbs) { - if (pattern.test(bare)) return phrase; - } - const short = shortenPaths(name).slice(0, 40); - return /^[\w .:/-]+$/.test(short) ? `running ${short}` : null; -} - -export function speechFromBlocks(blocks: MessageBlock[]): string { - return blocks - .map((block) => { - if (block.kind === "text" || block.kind === "progress" || block.kind === "meta") - return block.text; - if (block.kind === "ask") return block.text; - if (block.kind === "computer") return block.text; - if (block.kind === "subagent") { - if (block.status === "running") return `${block.name} is working on ${block.task}`; - if (block.status === "failed") return `${block.name} failed`; - return block.result || `${block.name} finished`; - } - if (block.kind === "card") { - return block.lines.map((line) => `${line.k}: ${line.v}`).join(". "); - } - return ""; - }) - .filter(Boolean) - .join("\n"); -} - -const YES = /^(yes|yeah|yep|yup|ok|okay|sure|do it|go ahead|approve|confirmed|affirmative)\b/i; -const NO = /^(no|nope|nah|cancel|stop|don't|do not|reject|deny|negative)\b/i; - -/** Consent must never be inferred from a sentence that merely contained "sure". */ -export function spokenDecision(transcript: string): "yes" | "no" | null { - const text = transcript.trim(); - if (!text) return null; - if (YES.test(text) && text.split(/\s+/).length <= 6) return "yes"; - if (NO.test(text) && text.split(/\s+/).length <= 6) return "no"; - return null; -} diff --git a/packages/core/src/voice-chat-groups.test.ts b/packages/core/src/voice-chat-groups.test.ts deleted file mode 100644 index 49e54987..00000000 --- a/packages/core/src/voice-chat-groups.test.ts +++ /dev/null @@ -1,189 +0,0 @@ -import type { ThreadMessage } from "@milo/contracts"; -import { describe, expect, it } from "vitest"; -import { - groupVoiceChats, - latestSpokenCallReply, - voiceChatDuration, - voiceChatSummary, -} from "./voice-chat-groups.js"; - -let seq = 0; -function message(fields: Partial & { role: ThreadMessage["role"] }): ThreadMessage { - seq += 1; - return { - id: `message-${seq}`, - threadId: "thread-1", - seq, - blocks: [{ kind: "text", text: "Hello" }], - createdAt: new Date(Date.UTC(2026, 7, 16, 0, 0, seq)).toISOString(), - ...fields, - }; -} - -describe("groupVoiceChats", () => { - it("keeps two calls in separate groups", () => { - const items = groupVoiceChats([ - message({ role: "user", callId: "call-1" }), - message({ role: "user", callId: "call-2" }), - ]); - - expect(items.map((item) => item.kind)).toEqual(["voiceChat", "voiceChat"]); - expect(items.flatMap((item) => (item.kind === "voiceChat" ? [item.callId] : []))).toEqual([ - "call-1", - "call-2", - ]); - }); - - it("breaks a group when a typed message lands between call turns", () => { - const items = groupVoiceChats([ - message({ role: "user", callId: "call-1" }), - message({ role: "user" }), - message({ role: "user", callId: "call-1" }), - ]); - - expect(items.map((item) => item.kind)).toEqual(["voiceChat", "message", "voiceChat"]); - }); - - it("does not speak a typed concurrent reply into the call", () => { - const callTurn = message({ role: "user", callId: "call-1", runId: "run-1" }); - const callReply = message({ role: "bot", runId: "run-1" }); - const typed = message({ role: "user", runId: "run-1" }); - const typedReply = message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "text", text: "Typed answer" }], - }); - - expect(latestSpokenCallReply([callTurn, callReply], "call-1")?.id).toBe(callReply.id); - expect(latestSpokenCallReply([callTurn, callReply, typed, typedReply], "call-1")?.id).toBe( - callReply.id, - ); - }); - - it("stops offering a spoken reply once the hang-up marker closed the card", () => { - const callTurn = message({ role: "user", callId: "call-1", runId: "run-1" }); - const callReply = message({ role: "bot", runId: "run-1" }); - const marker = message({ - role: "bot", - runId: "run-1", - callId: "call-1", - blocks: [{ kind: "voice_call", callId: "call-1", title: "Done", farewell: "Bye" }], - }); - const wrapUp = message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "text", text: "Here is the list" }], - }); - - expect(latestSpokenCallReply([callTurn, callReply, marker, wrapUp], "call-1")).toBeUndefined(); - }); - - it("numbers the segments a typed message split a call into, and keeps them across pages", () => { - const opening = message({ role: "user", callId: "call-1" }); - const resumed = message({ role: "user", callId: "call-1" }); - const page = [opening, message({ role: "user" }), resumed]; - - expect( - groupVoiceChats(page).flatMap((item) => (item.kind === "voiceChat" ? [item.key] : [])), - ).toEqual(["call:call-1", "call:call-1:2"]); - - // An older page lands in front and extends the first segment: the keys hold. - const older = [message({ role: "bot", callId: "call-1" }), ...page]; - expect( - groupVoiceChats(older).flatMap((item) => (item.kind === "voiceChat" ? [item.key] : [])), - ).toEqual(["call:call-1", "call:call-1:2"]); - }); - - it("joins the bot reply to the call by runId", () => { - const items = groupVoiceChats([ - message({ role: "user", callId: "call-1", runId: "run-1" }), - message({ role: "bot", runId: "run-1" }), - message({ role: "user" }), - ]); - - expect(items).toHaveLength(2); - expect(items[0]?.kind === "voiceChat" && items[0].messages).toHaveLength(2); - expect(items[1]?.kind).toBe("message"); - }); - - it("leaves a typed message and its reply out of the card even on the call's run", () => { - const items = groupVoiceChats([ - message({ role: "user", callId: "call-1", runId: "run-1" }), - message({ role: "bot", runId: "run-1" }), - message({ role: "user", runId: "run-1" }), - message({ role: "bot", runId: "run-1" }), - ]); - - expect(items.map((item) => item.kind)).toEqual(["voiceChat", "message", "message"]); - expect(items[0]?.kind === "voiceChat" && items[0].messages).toHaveLength(2); - }); - - it("closes the group at the call marker and leaves later work of that run outside", () => { - const items = groupVoiceChats([ - message({ role: "user", callId: "call-1", runId: "run-1" }), - message({ role: "bot", runId: "run-1" }), - message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "voice_call", callId: "call-1", title: "Made a list", farewell: "Bye" }], - }), - message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "text", text: "Here is the list" }], - }), - ]); - - const group = items[0]; - expect(items.map((item) => item.kind)).toEqual(["voiceChat", "message"]); - expect(group?.kind === "voiceChat" && group.messages).toHaveLength(3); - expect(group?.kind === "voiceChat" && group.marker?.id).toBe( - group?.kind === "voiceChat" ? group.messages[2]?.id : undefined, - ); - }); -}); - -describe("voiceChatSummary", () => { - it("takes the first sentence of the first spoken bot reply", () => { - const [group] = groupVoiceChats([ - message({ role: "user", callId: "call-1", runId: "run-1" }), - message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "text", text: "Deploy is green. I also restarted the worker." }], - }), - ]); - - expect(group?.kind === "voiceChat" && voiceChatSummary(group)).toBe("Deploy is green."); - }); - - it("prefers the title the bot hung up with", () => { - const [group] = groupVoiceChats([ - message({ role: "user", callId: "call-1", runId: "run-1" }), - message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "text", text: "Deploy is green. I also restarted the worker." }], - }), - message({ - role: "bot", - runId: "run-1", - blocks: [{ kind: "voice_call", callId: "call-1", title: "Deploy check", farewell: "Bye" }], - }), - ]); - - expect(group?.kind === "voiceChat" && voiceChatSummary(group)).toBe("Deploy check"); - }); -}); - -describe("voiceChatDuration", () => { - it("counts whole seconds between the first and last turn", () => { - const start = message({ role: "user", callId: "call-1", runId: "run-1" }); - const end = message({ role: "bot", runId: "run-1" }); - const [group] = groupVoiceChats([start, end]); - - expect(group?.kind === "voiceChat" && voiceChatDuration(group)).toBe( - Math.round((Date.parse(end.createdAt) - Date.parse(start.createdAt)) / 1000), - ); - }); -}); diff --git a/packages/core/src/voice-chat-groups.ts b/packages/core/src/voice-chat-groups.ts deleted file mode 100644 index 52e3d1b3..00000000 --- a/packages/core/src/voice-chat-groups.ts +++ /dev/null @@ -1,125 +0,0 @@ -import type { MessageBlock } from "@milo/contracts"; -import { speechFromBlocks } from "./speech-text.js"; - -/** The fields grouping reads; web `ThreadMessage` and mobile `MobileMessage` both satisfy it. */ -export type VoiceChatMessage = { - id: string; - role: string; - runId?: string; - callId?: string; - createdAt?: string; - blocks: MessageBlock[]; -}; - -export type VoiceChatGroup = { - kind: "voiceChat"; - /** - * List key: `call:` for a call's first group, `call::` for the - * later segments a typed message split it into. Keying off the first message would - * change when an older page extends a segment, remounting the card. - */ - key: string; - callId: string; - messages: T[]; - /** The `voice_call` message the bot left when it hung up; it closes the group. */ - marker?: T; -}; -export type ThreadItem = - | { kind: "message"; message: T } - | VoiceChatGroup; - -const SUMMARY_MAX = 120; - -/** - * Collapses each run of consecutive call messages into one group: a user - * message carrying the call's `callId`, or a bot reply to a run already in the - * group. Anything else ends the run — a typed user message breaks the group - * even when it reuses the run of a call turn. The bot's `voice_call` marker - * closes the group, so the work it does after hanging up renders as chat. - */ -export function groupVoiceChats(messages: T[]): ThreadItem[] { - const items: ThreadItem[] = []; - let open: VoiceChatGroup | undefined; - let openRunIds = new Set(); - const segments = new Map(); - for (const message of messages) { - if (open) { - const joinsByRun = Boolean( - message.role === "bot" && message.runId && openRunIds.has(message.runId), - ); - if (message.callId === open.callId || joinsByRun) { - open.messages.push(message); - if (isCallMarker(message)) { - open.marker = message; - open = undefined; - continue; - } - if (message.callId === open.callId && message.runId) openRunIds.add(message.runId); - continue; - } - open = undefined; - } - if (message.callId) { - const segment = (segments.get(message.callId) ?? 0) + 1; - segments.set(message.callId, segment); - open = { - kind: "voiceChat", - key: segment === 1 ? `call:${message.callId}` : `call:${message.callId}:${segment}`, - callId: message.callId, - messages: [message], - }; - openRunIds = new Set(message.runId ? [message.runId] : []); - items.push(open); - continue; - } - items.push({ kind: "message", message }); - } - return items; -} - -/** Newest bot turn still inside this call's open card. Typed turns and wrap-up sit outside. */ -export function latestSpokenCallReply( - messages: T[], - callId: string, -): T | undefined { - const groups = groupVoiceChats(messages).filter( - (item): item is VoiceChatGroup => item.kind === "voiceChat" && item.callId === callId, - ); - const group = groups.at(-1); - if (!group || group.marker) return undefined; - for (let index = group.messages.length - 1; index >= 0; index -= 1) { - const message = group.messages[index]; - if (message?.role === "bot") return message; - } - return undefined; -} - -function isCallMarker(message: VoiceChatMessage): boolean { - return message.role === "bot" && message.blocks[0]?.kind === "voice_call"; -} - -/** The title the bot hung up with, else the first sentence of its first spoken reply. */ -export function voiceChatSummary(group: VoiceChatGroup): string { - const marker = group.marker?.blocks[0]; - const title = marker?.kind === "voice_call" ? marker.title.trim() : ""; - if (title) return title; - const reply = group.messages.find( - (message) => message.role === "bot" && message !== group.marker, - ); - const spoken = reply ? speechFromBlocks(reply.blocks).trim() : ""; - if (!spoken) return ""; - const end = spoken.search(/[.!?](\s|$)/u); - const sentence = end === -1 ? spoken : spoken.slice(0, end + 1); - return sentence.length > SUMMARY_MAX - ? `${sentence.slice(0, SUMMARY_MAX - 1).trimEnd()}…` - : sentence; -} - -/** Whole seconds between the call's first and last message. */ -export function voiceChatDuration(group: VoiceChatGroup): number { - const first = group.messages[0]; - const last = group.messages[group.messages.length - 1]; - if (!first || !last) return 0; - const seconds = (Date.parse(last.createdAt ?? "") - Date.parse(first.createdAt ?? "")) / 1000; - return Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0; -} diff --git a/packages/db/prisma/migrations/20261020120000_drop_voice/migration.sql b/packages/db/prisma/migrations/20261020120000_drop_voice/migration.sql new file mode 100644 index 00000000..df28b207 --- /dev/null +++ b/packages/db/prisma/migrations/20261020120000_drop_voice/migration.sql @@ -0,0 +1,18 @@ +-- Voice is removed from the product. This permanently deletes every stored +-- voice provider key (encrypted secrets of kind 'voice') and voice settings. +DROP TABLE "space_voice_preferences"; +DROP TABLE "user_voice_credentials"; +DELETE FROM "secrets" WHERE "kind" = 'voice'; + +ALTER TABLE "bots" DROP COLUMN "voiceId", +DROP COLUMN "autoSpeak"; + +-- Model keys are now the only account-level secrets. +ALTER TABLE "secrets" DROP CONSTRAINT "secrets_scope_check"; +ALTER TABLE "secrets" + ADD CONSTRAINT "secrets_scope_check" + CHECK ( + ("kind" = 'model' AND "spaceId" IS NULL) + OR ("kind" <> 'model' AND "spaceId" IS NOT NULL) + ) NOT VALID; +ALTER TABLE "secrets" VALIDATE CONSTRAINT "secrets_scope_check"; diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 279683d0..e8b89b12 100644 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -36,7 +36,6 @@ model User { members Member[] invitations Invitation[] modelCredentials UserModelCredential[] - voiceCredentials UserVoiceCredential[] secrets Secret[] mcpServers McpServer[] botSections BotSection[] @@ -231,7 +230,6 @@ model SpaceMember { role String @default("member") createdAt DateTime modelPreferences SpaceModelPreference[] - voicePreferences SpaceVoicePreference[] aiDataConsents AiDataConsent[] @@unique([spaceId, userId]) @@ -290,20 +288,6 @@ model UserModelCredential { @@map("user_model_credentials") } -model UserVoiceCredential { - id String @id @default(cuid()) - userId String - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - provider String - secretId String - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - preferences SpaceVoicePreference[] - - @@unique([id, userId]) - @@index([userId, provider, updatedAt]) - @@map("user_voice_credentials") -} model SpaceModelPreference { id String @id @default(cuid()) @@ -325,26 +309,6 @@ model SpaceModelPreference { @@map("space_model_preferences") } -model SpaceVoicePreference { - id String @id @default(cuid()) - spaceId String - userId String - spaceMember SpaceMember @relation(fields: [spaceId, userId], references: [spaceId, userId], onDelete: Cascade) - credentialId String - credential UserVoiceCredential @relation(fields: [credentialId, userId], references: [id, userId], onDelete: Cascade) - voiceId String @default("") - // Fish speech-model override. Null keeps the deployment default. - speechModel String? - isDefault Boolean @default(false) - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt - - @@unique([spaceId, userId, credentialId]) - @@index([spaceId, userId, isDefault, updatedAt]) - @@index([credentialId]) - // Partial unique index space_voice_preferences_default_key is created in SQL. - @@map("space_voice_preferences") -} model Bot { screenGeneration Int @default(0) @@ -373,8 +337,6 @@ model Bot { computerId String? computer Computer? @relation(fields: [computerId], references: [id], onDelete: SetNull) computerSwitching Boolean @default(false) - voiceId String? - autoSpeak Boolean @default(false) modelProvider String? modelId String? thinkingLevel String? diff --git a/packages/db/src/credential-secrets.test.ts b/packages/db/src/credential-secrets.test.ts index f76fa5f8..2c7896f2 100644 --- a/packages/db/src/credential-secrets.test.ts +++ b/packages/db/src/credential-secrets.test.ts @@ -2,17 +2,16 @@ import { describe, expect, it, vi } from "vitest"; import type { PrismaClient } from "./client.js"; import { deleteUnreferencedCredentialSecret, retireModelCredential } from "./credential-secrets.js"; -function credentialSecretPrisma(modelReferences: number, voiceReferences: number) { +function credentialSecretPrisma(modelReferences: number) { return { userModelCredential: { count: vi.fn().mockResolvedValue(modelReferences) }, - userVoiceCredential: { count: vi.fn().mockResolvedValue(voiceReferences) }, secret: { deleteMany: vi.fn().mockResolvedValue({ count: 1 }) }, } as unknown as PrismaClient; } describe("deleteUnreferencedCredentialSecret", () => { - it("deletes a replaced secret after both credential kinds release it", async () => { - const prisma = credentialSecretPrisma(0, 0); + it("deletes a replaced secret after no model credential still references it", async () => { + const prisma = credentialSecretPrisma(0); await deleteUnreferencedCredentialSecret(prisma, { credentialKind: "model", @@ -23,17 +22,14 @@ describe("deleteUnreferencedCredentialSecret", () => { expect(prisma.userModelCredential.count).toHaveBeenCalledWith({ where: { id: { not: "credential" }, secretId: "secret" }, }); - expect(prisma.userVoiceCredential.count).toHaveBeenCalledWith({ - where: { secretId: "secret" }, - }); expect(prisma.secret.deleteMany).toHaveBeenCalledWith({ where: { id: "secret" } }); }); - it("keeps a secret while either credential kind still references it", async () => { - const prisma = credentialSecretPrisma(0, 1); + it("keeps a secret while another model credential still references it", async () => { + const prisma = credentialSecretPrisma(1); await deleteUnreferencedCredentialSecret(prisma, { - credentialKind: "voice", + credentialKind: "model", credentialId: "credential", secretId: "secret", }); @@ -62,7 +58,6 @@ function retirePrisma(state: { credentials: StoredCredentialRow[]; preferences: StoredPreferenceRow[]; secrets: StoredSecretRow[]; - voiceCredentials?: StoredCredentialRow[]; }) { const tx = { userModelCredential: { @@ -84,13 +79,6 @@ function retirePrisma(state: { ).length, ), }, - userVoiceCredential: { - count: vi.fn( - async (args: { where: { secretId: string } }) => - (state.voiceCredentials ?? []).filter((row) => row.secretId === args.where.secretId) - .length, - ), - }, spaceModelPreference: { deleteMany: vi.fn(async (args: { where: { userId: string; credentialId: string } }) => { const before = state.preferences.length; @@ -169,7 +157,7 @@ describe("retireModelCredential", () => { it("keeps a secret still referenced by another credential", async () => { const state = { - credentials: [codexCredential(), codexCredential({ id: "cred-voice-shared" })], + credentials: [codexCredential(), codexCredential({ id: "cred-shared" })], preferences: [codexPreference()], secrets: [{ id: "secret-codex" }], }; @@ -181,7 +169,7 @@ describe("retireModelCredential", () => { secretId: "secret-codex", }); - expect(state.credentials).toEqual([codexCredential({ id: "cred-voice-shared" })]); + expect(state.credentials).toEqual([codexCredential({ id: "cred-shared" })]); expect(state.secrets).toEqual([{ id: "secret-codex" }]); }); diff --git a/packages/db/src/credential-secrets.ts b/packages/db/src/credential-secrets.ts index d93e8ba5..35d5b7e7 100644 --- a/packages/db/src/credential-secrets.ts +++ b/packages/db/src/credential-secrets.ts @@ -2,34 +2,23 @@ import type { PrismaClient } from "./client.js"; import { Prisma } from "./client.js"; import { withTransactionRetry } from "./transaction-retry.js"; -type CredentialSecretClient = Pick< - PrismaClient, - "secret" | "userModelCredential" | "userVoiceCredential" ->; +type CredentialSecretClient = Pick; export async function deleteUnreferencedCredentialSecret( prisma: CredentialSecretClient, input: { - credentialKind: "model" | "voice"; + credentialKind: "model"; credentialId: string; secretId: string; }, ): Promise { - const [modelReferences, voiceReferences] = await Promise.all([ - prisma.userModelCredential.count({ - where: { - secretId: input.secretId, - ...(input.credentialKind === "model" ? { id: { not: input.credentialId } } : {}), - }, - }), - prisma.userVoiceCredential.count({ - where: { - secretId: input.secretId, - ...(input.credentialKind === "voice" ? { id: { not: input.credentialId } } : {}), - }, - }), - ]); - if (modelReferences + voiceReferences === 0) { + const modelReferences = await prisma.userModelCredential.count({ + where: { + secretId: input.secretId, + id: { not: input.credentialId }, + }, + }); + if (modelReferences === 0) { await prisma.secret.deleteMany({ where: { id: input.secretId } }); } } diff --git a/packages/db/src/events.ts b/packages/db/src/events.ts index 722a9b29..0b5dedfd 100644 --- a/packages/db/src/events.ts +++ b/packages/db/src/events.ts @@ -9,7 +9,6 @@ import { } from "@milo/contracts"; import { blocksToAgentHistoryText, - callIdFromClientNonce, isApprovalAskBlock, isConversationalRun, isSecretAskBlock, @@ -445,9 +444,6 @@ export async function sendUserMessage( messageId: message.id, role: "user", blocks: input.blocks, - // Carries the call id on the live event so a spoken turn groups into the - // call card immediately, instead of after a refetch reads the nonce. - callId: callIdFromClientNonce(message.clientNonce), }, }); return { message, task, run, busy, event }; diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 8e4dbdcc..233f4456 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -13,4 +13,3 @@ export * from "./repos.js"; export * from "./scope.js"; export * from "./spaces.js"; export * from "./transaction-retry.js"; -export * from "./voice-credentials.js"; diff --git a/packages/db/src/repos.ts b/packages/db/src/repos.ts index 041adcc8..48c7b48d 100644 --- a/packages/db/src/repos.ts +++ b/packages/db/src/repos.ts @@ -48,8 +48,6 @@ function mapBot( updatedAt: Date; thread: { id: string; unread: boolean } | null; computer: { scope: string } | null; - voiceId?: string | null; - autoSpeak?: boolean; modelProvider?: string | null; modelId?: string | null; thinkingLevel?: string | null; @@ -82,8 +80,6 @@ function mapBot( computerMode: bot.computer ? parseComputerMode(bot.computer.scope) : "team", createdAt: bot.createdAt.toISOString(), updatedAt: bot.updatedAt.toISOString(), - voiceId: bot.voiceId ?? null, - autoSpeak: bot.autoSpeak ?? false, modelProvider: bot.modelProvider ?? null, modelId: bot.modelId ?? null, thinkingLevel: (bot.thinkingLevel as Bot["thinkingLevel"]) ?? null, diff --git a/packages/db/src/spaces.ts b/packages/db/src/spaces.ts index a254c10e..33614cf6 100644 --- a/packages/db/src/spaces.ts +++ b/packages/db/src/spaces.ts @@ -69,7 +69,6 @@ type SpaceClient = Pick< | "space" | "spaceMember" | "spaceModelPreference" - | "spaceVoicePreference" | "memoryDocument" | "notificationPreference" | "bot" @@ -132,43 +131,21 @@ async function copyProviderPreferences( prisma: SpaceClient, input: { sourceSpaceId: string; targetSpaceId: string; userId: string; createdAt: Date }, ): Promise { - const [modelPreferences, voicePreferences] = await Promise.all([ - prisma.spaceModelPreference.findMany({ - where: { spaceId: input.sourceSpaceId, userId: input.userId }, - }), - prisma.spaceVoicePreference.findMany({ - where: { spaceId: input.sourceSpaceId, userId: input.userId }, - }), - ]); - await Promise.all([ - modelPreferences.length - ? prisma.spaceModelPreference.createMany({ - data: modelPreferences.map((preference) => ({ - spaceId: input.targetSpaceId, - userId: input.userId, - credentialId: preference.credentialId, - modelId: preference.modelId, - isDefault: preference.isDefault, - createdAt: input.createdAt, - updatedAt: input.createdAt, - })), - }) - : Promise.resolve(), - voicePreferences.length - ? prisma.spaceVoicePreference.createMany({ - data: voicePreferences.map((preference) => ({ - spaceId: input.targetSpaceId, - userId: input.userId, - credentialId: preference.credentialId, - voiceId: preference.voiceId, - speechModel: preference.speechModel, - isDefault: preference.isDefault, - createdAt: input.createdAt, - updatedAt: input.createdAt, - })), - }) - : Promise.resolve(), - ]); + const modelPreferences = await prisma.spaceModelPreference.findMany({ + where: { spaceId: input.sourceSpaceId, userId: input.userId }, + }); + if (modelPreferences.length === 0) return; + await prisma.spaceModelPreference.createMany({ + data: modelPreferences.map((preference) => ({ + spaceId: input.targetSpaceId, + userId: input.userId, + credentialId: preference.credentialId, + modelId: preference.modelId, + isDefault: preference.isDefault, + createdAt: input.createdAt, + updatedAt: input.createdAt, + })), + }); } /** Create a sibling privacy boundary for a member of the active organization. */ diff --git a/packages/db/src/voice-credentials.test.ts b/packages/db/src/voice-credentials.test.ts deleted file mode 100644 index 9f306c76..00000000 --- a/packages/db/src/voice-credentials.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; -import type { PrismaClient } from "./client.js"; -import { selectSpaceVoicePreference } from "./voice-credentials.js"; - -const scope = { userId: "user", spaceId: "space" }; - -function preferenceClient() { - const updateMany = vi.fn().mockResolvedValue({ count: 0 }); - const upsert = vi.fn().mockResolvedValue({ id: "preference" }); - const prisma = { spaceVoicePreference: { updateMany, upsert } } as unknown as PrismaClient; - return { prisma, upsert }; -} - -describe("selectSpaceVoicePreference", () => { - it("leaves the speech model unchanged when the caller omits it", async () => { - const { prisma, upsert } = preferenceClient(); - - await selectSpaceVoicePreference(prisma, scope, "credential", "voice"); - - expect(upsert).toHaveBeenCalledWith( - expect.objectContaining({ - create: expect.objectContaining({ voiceId: "voice", isDefault: true }), - update: { voiceId: "voice", isDefault: true }, - }), - ); - const call = upsert.mock.calls[0]?.[0] as { create: Record }; - expect(call.create).not.toHaveProperty("speechModel"); - }); - - it("stores a speech model override with the voice preference", async () => { - const { prisma, upsert } = preferenceClient(); - - await selectSpaceVoicePreference(prisma, scope, "credential", "voice", "s1"); - - expect(upsert).toHaveBeenCalledWith( - expect.objectContaining({ - create: expect.objectContaining({ speechModel: "s1" }), - update: { voiceId: "voice", isDefault: true, speechModel: "s1" }, - }), - ); - }); - - it("clears a speech model override", async () => { - const { prisma, upsert } = preferenceClient(); - - await selectSpaceVoicePreference(prisma, scope, "credential", "voice", null); - - expect(upsert).toHaveBeenCalledWith( - expect.objectContaining({ - update: { voiceId: "voice", isDefault: true, speechModel: null }, - }), - ); - }); -}); diff --git a/packages/db/src/voice-credentials.ts b/packages/db/src/voice-credentials.ts deleted file mode 100644 index f5813666..00000000 --- a/packages/db/src/voice-credentials.ts +++ /dev/null @@ -1,108 +0,0 @@ -import type { PrismaClient } from "./client.js"; -import { newestCredentialOrder } from "./model-credentials.js"; - -export const newestVoiceCredentialOrder = newestCredentialOrder; - -type VoiceCredentialScope = { userId: string; spaceId: string }; - -export async function selectSpaceVoicePreference( - prisma: Pick, - scope: VoiceCredentialScope, - credentialId: string, - voiceId: string, - speechModel?: string | null, -) { - await prisma.spaceVoicePreference.updateMany({ - where: { - spaceId: scope.spaceId, - userId: scope.userId, - isDefault: true, - credentialId: { not: credentialId }, - }, - data: { isDefault: false }, - }); - const speechModelData = speechModel === undefined ? {} : { speechModel }; - return prisma.spaceVoicePreference.upsert({ - where: { - spaceId_userId_credentialId: { - spaceId: scope.spaceId, - userId: scope.userId, - credentialId, - }, - }, - create: { - spaceId: scope.spaceId, - userId: scope.userId, - credentialId, - voiceId, - isDefault: true, - ...speechModelData, - }, - update: { voiceId, isDefault: true, ...speechModelData }, - }); -} - -function withVoicePreference< - T extends { - credential: { - id: string; - userId: string; - provider: string; - secretId: string; - createdAt: Date; - updatedAt: Date; - }; - isDefault: boolean; - voiceId: string; - speechModel: string | null; - }, ->(preference: T) { - return { - ...preference.credential, - isDefault: preference.isDefault, - voiceId: preference.voiceId, - speechModel: preference.speechModel ?? "", - }; -} - -export async function findDefaultVoiceCredential( - prisma: PrismaClient, - scope: VoiceCredentialScope, -) { - const preference = await prisma.spaceVoicePreference.findFirst({ - where: { spaceId: scope.spaceId, userId: scope.userId, isDefault: true }, - include: { credential: true }, - orderBy: [{ updatedAt: "desc" }, { id: "desc" }], - }); - return preference ? withVoicePreference(preference) : null; -} - -export function findNewestUserVoiceCredential( - prisma: PrismaClient, - userId: string, - provider: string, -) { - return prisma.userVoiceCredential.findFirst({ - where: { userId, provider }, - orderBy: newestVoiceCredentialOrder, - }); -} - -export async function findVoiceCredential( - prisma: PrismaClient, - scope: VoiceCredentialScope, - provider: string, -) { - const preference = await prisma.spaceVoicePreference.findFirst({ - where: { - spaceId: scope.spaceId, - userId: scope.userId, - credential: { provider }, - }, - include: { credential: true }, - orderBy: [{ isDefault: "desc" }, { updatedAt: "desc" }, { id: "desc" }], - }); - if (preference) return withVoicePreference(preference); - const credential = await findNewestUserVoiceCredential(prisma, scope.userId, provider); - return credential ? { ...credential, isDefault: false, voiceId: "", speechModel: "" } : null; -} diff --git a/packages/testkit/src/authorization.test.ts b/packages/testkit/src/authorization.test.ts index 75943b25..7871d5ae 100644 --- a/packages/testkit/src/authorization.test.ts +++ b/packages/testkit/src/authorization.test.ts @@ -180,14 +180,6 @@ describeWithDatabase("API authorization and resource isolation", () => { ["export/bot", { botId: "missing-bot" }], ["notifications/registerPush", { token: "ExponentPushToken[not-real]" }], ["search/query", { q: "anything" }], - ["voice/catalog"], - ["voice/status"], - ["voice/credentials"], - ["voice/connect", { provider: "elevenlabs", apiKey: "not-a-real-key" }], - ["voice/disconnect", { provider: "elevenlabs" }], - ["voice/setVoice", { voiceId: "missing-voice" }], - ["voice/voices", {}], - ["voice/prepare", { text: "Nope" }], ]); const results = await Promise.all( @@ -355,7 +347,6 @@ describeWithDatabase("API authorization and resource isolation", () => { ], ["artifacts/get", { botId: ownerBot.id, artifactId: ownerArtifact.id }], ["export/bot", { botId: ownerBot.id }], - ["voice/prepare", { text: "stolen speech", botId: ownerBot.id }], ]; await Promise.all( botIdCalls.map(([procedure, input]) => expectDenied(app, intruder, procedure, input)), @@ -684,70 +675,22 @@ describeWithDatabase("API authorization and resource isolation", () => { label: "Copy provider", modelId: "copy/model", }); - const voice = await rpc<{ id: string; voiceId: string }>(app, cookie, "voice/connect", { - provider: "scripted", - apiKey: "fake-copy-voice-key", - }); const created = await rpc(app, cookie, "spaces/create", { name: "Copied defaults" }); - const [modelPreference, voicePreference] = await Promise.all([ - handles.prisma.spaceModelPreference.findUnique({ - where: { - spaceId_userId_credentialId: { - spaceId: created.id, - userId: actor.userId, - credentialId: model.id, - }, - }, - }), - handles.prisma.spaceVoicePreference.findUnique({ - where: { - spaceId_userId_credentialId: { - spaceId: created.id, - userId: actor.userId, - credentialId: voice.id, - }, + const modelPreference = await handles.prisma.spaceModelPreference.findUnique({ + where: { + spaceId_userId_credentialId: { + spaceId: created.id, + userId: actor.userId, + credentialId: model.id, }, - }), - ]); + }, + }); expect(modelPreference).toMatchObject({ modelId: "copy/model", isDefault: true }); - expect(voicePreference).toMatchObject({ voiceId: voice.voiceId, isDefault: true }); - await rpc( - app, - cookie, - "voice/setVoice", - { provider: "scripted", voiceId: "space-specific-voice" }, - created.id, - ); - await expect( - handles.prisma.spaceVoicePreference.findUniqueOrThrow({ - where: { - spaceId_userId_credentialId: { - spaceId: actor.spaceId, - userId: actor.userId, - credentialId: voice.id, - }, - }, - }), - ).resolves.toMatchObject({ voiceId: voice.voiceId, isDefault: true }); - await expect( - handles.prisma.spaceVoicePreference.findUniqueOrThrow({ - where: { - spaceId_userId_credentialId: { - spaceId: created.id, - userId: actor.userId, - credentialId: voice.id, - }, - }, - }), - ).resolves.toMatchObject({ voiceId: "space-specific-voice", isDefault: true }); await expect( handles.prisma.userModelCredential.count({ where: { userId: actor.userId } }), ).resolves.toBe(1); - await expect( - handles.prisma.userVoiceCredential.count({ where: { userId: actor.userId } }), - ).resolves.toBe(1); }); it("shares model credentials while keeping defaults private to each space", async () => { diff --git a/packages/testkit/src/cli/harness.ts b/packages/testkit/src/cli/harness.ts index b34868fb..8b72c49b 100644 --- a/packages/testkit/src/cli/harness.ts +++ b/packages/testkit/src/cli/harness.ts @@ -73,7 +73,6 @@ async function main() { "packages/testkit/src/journeys.test.ts", "packages/testkit/src/authorization.test.ts", "packages/testkit/src/attachments.test.ts", - "packages/testkit/src/voice.test.ts", "packages/testkit/src/search.test.ts", "packages/testkit/src/executor-lifecycle.test.ts", "packages/testkit/src/connections.test.ts", diff --git a/packages/testkit/src/voice.test.ts b/packages/testkit/src/voice.test.ts deleted file mode 100644 index 7973b151..00000000 --- a/packages/testkit/src/voice.test.ts +++ /dev/null @@ -1,222 +0,0 @@ -import { mkdtempSync } from "node:fs"; -import { tmpdir } from "node:os"; -import path from "node:path"; -import { SCRIPTED_MPEG, SCRIPTED_TRANSCRIPT, SCRIPTED_VOICE_ID } from "@milo/adapters"; -import type { PrismaClient } from "@milo/db"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import type { BotIntroHarness } from "./discard-bot-intro.js"; -import { discardBotIntroFromCreate } from "./discard-bot-intro.js"; -import { sessionCookieHeader } from "./index.js"; - -type App = { request: (input: string, init?: RequestInit) => Promise }; - -process.env.WAKEUP_DRIVER = "memory"; -process.env.SANDBOX_PROVIDER = "fake"; -process.env.AGENT_RUNTIME = "scripted"; - -const hasDb = process.env.VERIFY_DATABASE === "1" && Boolean(process.env.DATABASE_URL); -const describeVoice = hasDb ? describe : describe.skip; -let botIntroHarness: BotIntroHarness | undefined; - -describeVoice("voice credentials and speech HTTP", () => { - let app: App; - let prisma: PrismaClient; - let stop: () => Promise; - const stamp = Date.now(); - const dataDir = mkdtempSync(path.join(tmpdir(), "rakazo-voice-")); - - beforeAll(async () => { - const { createApp } = await import("../../../apps/api/src/app.ts"); - const handles = await createApp({ - databaseUrl: process.env.DATABASE_URL!, - dataDir, - sandboxProvider: "fake", - agentRuntime: "scripted", - }); - app = handles.app; - prisma = handles.prisma; - stop = handles.stop; - botIntroHarness = handles; - }); - - afterAll(async () => { - await stop?.(); - }); - - it("connects a scripted key, speaks, and transcribes without leaking the secret", async () => { - const cookie = await signup(app, `voice-${stamp}@rakazo.test`, "Voice User"); - const other = await signup(app, `voice-other-${stamp}@rakazo.test`, "Other Voice"); - - const before = await rpc<{ ready: boolean; utterances: string[] }>( - app, - cookie, - "voice/prepare", - { text: "Hello there." }, - ); - expect(before).toEqual({ ready: false, utterances: [] }); - - const catalog = await rpc>(app, cookie, "voice/catalog"); - expect(catalog.map((entry) => entry.id)).toContain("scripted"); - - const connected = await rpc<{ hasKey: boolean; provider: string; voiceId: string }>( - app, - cookie, - "voice/connect", - { provider: "scripted", apiKey: "fake-scripted-voice-key" }, - ); - expect(connected.hasKey).toBe(true); - expect(connected.provider).toBe("scripted"); - expect(connected.voiceId).toBe(SCRIPTED_VOICE_ID); - expect(JSON.stringify(connected)).not.toContain("fake-scripted-voice-key"); - - const credentials = await rpc>( - app, - cookie, - "voice/credentials", - ); - expect(credentials).toEqual([ - expect.objectContaining({ hasKey: true, voiceId: SCRIPTED_VOICE_ID }), - ]); - expect(JSON.stringify(credentials)).not.toContain("fake-scripted-voice-key"); - - const prepared = await rpc<{ ready: boolean; utterances: string[] }>( - app, - cookie, - "voice/prepare", - { text: "Hello there. How are you?" }, - ); - expect(prepared.ready).toBe(true); - expect(prepared.utterances.length).toBeGreaterThan(0); - - const spoken = await app.request("/api/voice/speak", { - method: "POST", - headers: { - "content-type": "application/json", - cookie, - origin: "http://127.0.0.1:5173", - }, - body: JSON.stringify({ text: "Hello there." }), - }); - expect(spoken.status).toBe(200); - expect(spoken.headers.get("content-type")).toContain("audio/mpeg"); - expect(Buffer.from(await spoken.arrayBuffer())).toEqual(Buffer.from(SCRIPTED_MPEG)); - - const transcribed = await app.request("/api/voice/transcribe", { - method: "POST", - headers: { - "content-type": "application/json", - cookie, - origin: "http://127.0.0.1:5173", - }, - body: JSON.stringify({ - audioBase64: Buffer.from("noise").toString("base64"), - mimeType: "audio/webm", - }), - }); - expect(transcribed.status).toBe(200); - expect(await transcribed.json()).toEqual({ text: SCRIPTED_TRANSCRIPT }); - - const bot = await rpc<{ id: string }>(app, cookie, "bots/create", { - name: "Speaker", - title: "", - description: "", - instructions: "", - notifyOnFinish: true, - }); - const stolen = await raw(app, other, "voice/prepare", { - text: "stolen", - botId: bot.id, - }); - expect(stolen.status).toBeGreaterThanOrEqual(400); - - const unauth = await app.request("/api/voice/speak", { - method: "POST", - headers: { "content-type": "application/json", origin: "http://127.0.0.1:5173" }, - body: JSON.stringify({ text: "hello" }), - }); - expect(unauth.status).toBe(401); - }); - - it("disconnects the actor credential and leaves another user's key in place", async () => { - const cookie = await signup(app, `voice-disconnect-${stamp}@rakazo.test`, "Voice Disconnect"); - const other = await signup( - app, - `voice-disconnect-other-${stamp}@rakazo.test`, - "Other Voice Disconnect", - ); - const me = await rpc<{ userId: string }>(app, cookie, "me"); - - await rpc(app, cookie, "voice/connect", { - provider: "scripted", - apiKey: "fake-scripted-voice-key", - }); - const stored = await prisma.userVoiceCredential.findFirstOrThrow({ - where: { userId: me.userId, provider: "scripted" }, - }); - - await expect(rpc(app, other, "voice/disconnect", { provider: "scripted" })).resolves.toEqual({ - ok: true, - }); - await expect( - prisma.userVoiceCredential.findUnique({ where: { id: stored.id } }), - ).resolves.toMatchObject({ id: stored.id }); - await expect( - prisma.secret.findUnique({ where: { id: stored.secretId } }), - ).resolves.toMatchObject({ id: stored.secretId }); - - await expect(rpc(app, cookie, "voice/disconnect", { provider: "scripted" })).resolves.toEqual({ - ok: true, - }); - await expect( - rpc>(app, cookie, "voice/credentials"), - ).resolves.toEqual([]); - await expect( - prisma.userVoiceCredential.findUnique({ where: { id: stored.id } }), - ).resolves.toBeNull(); - await expect( - prisma.spaceVoicePreference.count({ where: { credentialId: stored.id } }), - ).resolves.toBe(0); - await expect(prisma.secret.findUnique({ where: { id: stored.secretId } })).resolves.toBeNull(); - - const prepared = await rpc<{ ready: boolean }>(app, cookie, "voice/prepare", { - text: "Hello there.", - }); - expect(prepared.ready).toBe(false); - - await expect(rpc(app, cookie, "voice/disconnect", { provider: "scripted" })).resolves.toEqual({ - ok: true, - }); - }); -}); - -async function signup(app: App, email: string, name: string) { - const response = await app.request("/api/auth/sign-up/email", { - method: "POST", - headers: { "content-type": "application/json", origin: "http://127.0.0.1:5173" }, - body: JSON.stringify({ email, password: "test-password-123", name }), - }); - expect(response.status).toBeLessThan(400); - return sessionCookieHeader(response); -} - -async function rpc(app: App, cookie: string, proc: string, body: unknown = {}): Promise { - const res = await raw(app, cookie, proc, body); - const text = await res.text(); - const parsed = JSON.parse(text) as { json?: T; error?: { message?: string } }; - if (res.status >= 400 || parsed.error) { - throw new Error(`${proc} ${res.status}: ${parsed.error?.message ?? text}`); - } - return discardBotIntroFromCreate(botIntroHarness, cookie, proc, parsed.json as T); -} - -async function raw(app: App, cookie: string, proc: string, body: unknown) { - return app.request(`/rpc/${proc}`, { - method: "POST", - headers: { - "content-type": "application/json", - cookie, - origin: "http://127.0.0.1:5173", - }, - body: JSON.stringify({ json: body }), - }); -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c11551c8..a5c240bf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -140,9 +140,6 @@ importers: expo-application: specifier: 57.0.3 version: 57.0.3(expo@57.0.30) - expo-audio: - specifier: 57.0.5 - version: 57.0.5(expo-asset@57.0.20(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3))(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3) expo-clipboard: specifier: 57.0.2 version: 57.0.2(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3) @@ -185,12 +182,6 @@ importers: expo-sharing: specifier: 57.0.23 version: 57.0.23(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3) - expo-speech: - specifier: 57.0.3 - version: 57.0.3(expo@57.0.30) - expo-speech-recognition: - specifier: 57.1.0 - version: 57.1.0(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3) expo-splash-screen: specifier: 57.0.10 version: 57.0.10(expo@57.0.30)(typescript@6.0.3) @@ -5027,14 +5018,6 @@ packages: react: 19.2.3 react-native: '*' - expo-audio@57.0.5: - resolution: {integrity: sha512-39fX5JC5zDvELB4/eDJPj2XAYRN0W9+K2DfDWm5N3aC5WZ7HRrhupWtT6hbH09NlfYpsRSqYOwEZnocFM42ynQ==} - peerDependencies: - expo: '*' - expo-asset: '*' - react: 19.2.3 - react-native: '*' - expo-clipboard@57.0.2: resolution: {integrity: sha512-VB4Au8X/RbvJKUtJk+87vdtveWSNEa5RzY3ooeO6VNF7Rd49RbQXZOu3/TfEW9p7mU8TCfyTvjyCiAUwSoSJ4w==} peerDependencies: @@ -5192,18 +5175,6 @@ packages: react: 19.2.3 react-native: '*' - expo-speech-recognition@57.1.0: - resolution: {integrity: sha512-eUiODNPb3CNeQB8Rzro79Dsf+dWzFNdyDRxzorfh2SNwXeCQkC5yh8goPNmCO+d1JyaYmV89F4jcGu52p3uW6w==} - peerDependencies: - expo: '*' - react: 19.2.3 - react-native: '*' - - expo-speech@57.0.3: - resolution: {integrity: sha512-rcO8izKziksrV4X3qQ5g+prFNTZmLYDEGEVnTvuvpOZDwjzP9nsdoaFymhY+qj9AJfMcpvR7Wshm+zpislyJBg==} - peerDependencies: - expo: '*' - expo-splash-screen@57.0.10: resolution: {integrity: sha512-W7++tMiyVMviWPTvaTXKpcOwwu5SbriwA2n0ewEhC+ic1LFaUNTUXiIXr95MVMSHaLRgtIG9dGyCTCb+NkekkA==} peerDependencies: @@ -13155,13 +13126,6 @@ snapshots: - supports-color - typescript - expo-audio@57.0.5(expo-asset@57.0.20(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3))(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3): - dependencies: - expo: 57.0.30(@babel/core@7.29.7)(@expo/dom-webview@57.0.1)(@expo/metro-runtime@57.0.17)(expo-router@57.0.28)(react-dom@19.2.3(react@19.2.3))(react-native-web@0.21.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-native-webview@13.16.1(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native-worklets@0.10.1(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3) - expo-asset: 57.0.20(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3) - react: 19.2.3 - react-native: 0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3) - expo-clipboard@57.0.2(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3): dependencies: expo: 57.0.30(@babel/core@7.29.7)(@expo/dom-webview@57.0.1)(@expo/metro-runtime@57.0.17)(expo-router@57.0.28)(react-dom@19.2.3(react@19.2.3))(react-native-web@0.21.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-native-webview@13.16.1(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native-worklets@0.10.1(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3) @@ -13346,16 +13310,6 @@ snapshots: - supports-color - typescript - expo-speech-recognition@57.1.0(expo@57.0.30)(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3): - dependencies: - expo: 57.0.30(@babel/core@7.29.7)(@expo/dom-webview@57.0.1)(@expo/metro-runtime@57.0.17)(expo-router@57.0.28)(react-dom@19.2.3(react@19.2.3))(react-native-web@0.21.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-native-webview@13.16.1(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native-worklets@0.10.1(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3) - react: 19.2.3 - react-native: 0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3) - - expo-speech@57.0.3(expo@57.0.30): - dependencies: - expo: 57.0.30(@babel/core@7.29.7)(@expo/dom-webview@57.0.1)(@expo/metro-runtime@57.0.17)(expo-router@57.0.28)(react-dom@19.2.3(react@19.2.3))(react-native-web@0.21.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3))(react-native-webview@13.16.1(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native-worklets@0.10.1(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3))(react-native@0.86.3(@babel/core@7.29.7)(@react-native/metro-config@0.86.3(@babel/core@7.29.7))(@types/react@19.2.18)(react@19.2.3))(react@19.2.3)(typescript@6.0.3) - expo-splash-screen@57.0.10(expo@57.0.30)(typescript@6.0.3): dependencies: '@expo/config-plugins': 57.0.10(typescript@6.0.3) From 741fbfa293cbb847f5f0a80bfc69943ce2d2a9a0 Mon Sep 17 00:00:00 2001 From: shubhook Date: Wed, 21 Oct 2026 01:04:23 +0530 Subject: [PATCH 2/2] Drop the mobile call card left behind when rebasing voice removal onto main. Co-authored-by: Cursor --- apps/mobile/app/_layout.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx index ef93c03a..07e2d081 100644 --- a/apps/mobile/app/_layout.tsx +++ b/apps/mobile/app/_layout.tsx @@ -7,7 +7,6 @@ import { View } from "react-native"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import { KeyboardProvider } from "react-native-keyboard-controller"; import { AvatarStyleProvider } from "../components/avatar-style"; -import { CallCard } from "../components/CallCard"; import { ComputerUpdateProgress } from "../components/computer-update-progress"; import { currentApiBase, loadApiBase, loadSessionToken, selectedSpaceId } from "../lib/api"; import { loadAppearancePreference, mobileTokens } from "../lib/appearance"; @@ -159,7 +158,6 @@ export default function Layout() { - ) : (