From fadf0ca9f4d73fdaeba1fdbd579a8a39ba07e6c8 Mon Sep 17 00:00:00 2001 From: LegGasai Date: Fri, 6 Nov 2026 17:27:58 +0800 Subject: [PATCH] feat(voice-input): recognize speech with DeepSeek cloud ASR after sign-in Add the experimental speech-to-text-deepseek provider, which sends complete recordings to the DeepSeek One-Shot endpoint with the signed-in account token. speech-to-text gains automatic provider selection, a shared language preference and classified failure codes; the voice UI offers sign-in through the new accountSignIn Client service, and the account service releases tokens to https://harness.deepseek.com. Refs #8059 --- ...eepseek-cloud-speech-recognition.i18n.yaml | 19 ++ ...11-04-deepseek-cloud-speech-recognition.md | 25 ++ ...04-deepseek-cloud-speech-recognition.zh.md | 25 ++ .../voice-input-cloud/recording.expected.md | 5 + .../voice-input-cloud/sign-in.expected.md | 6 + .../tests/expected/voice-setup.expected.md | 9 +- .../expected/voice-source-auto.expected.md | 2 +- .../expected/voice-source-manual.expected.md | 2 +- .../voice-input-cloud/cordis.patch.yml | 18 ++ apps/web/tests/voice-download.e2e.ts | 7 +- apps/web/tests/voice-input-cloud.e2e.ts | 172 +++++++++++ apps/web/tests/voice-input.e2e.ts | 3 +- apps/web/tests/voice-setup.e2e.ts | 12 +- apps/web/tsconfig.json | 1 + docs/config-catalog.md | 43 ++- docs/config-catalog.zh.md | 43 ++- docs/module-graph.md | 4 + docs/module-graph.zh.md | 4 + docs/subsystems/credentials.md | 2 +- docs/subsystems/credentials.zh.md | 2 +- docs/subsystems/voice-input.i18n.yaml | 4 +- docs/subsystems/voice-input.md | 12 +- docs/subsystems/voice-input.zh.md | 12 +- .../ui-settings-account/README.i18n.yaml | 4 +- packages/client/ui-settings-account/README.md | 2 + .../client/ui-settings-account/README.zh.md | 2 + .../ui-settings-account/src/client/index.ts | 16 + .../tests/access-revocation.client.spec.ts | 26 +- .../tests/apply.client.spec.ts | 14 + .../tests/initialization.client.spec.ts | 1 + .../README.i18n.yaml | 4 +- .../deepseek-account-platform/README.md | 2 + .../deepseek-account-platform/README.zh.md | 2 + .../deepseek-account-platform/src/index.ts | 40 ++- .../tests/account.spec.ts | 38 ++- .../deepseek-account/README.i18n.yaml | 8 +- .../credentials/deepseek-account/README.md | 4 +- .../credentials/deepseek-account/README.zh.md | 4 +- .../credentials/deepseek-account/src/index.ts | 2 +- .../api-speech-to-text/README.i18n.yaml | 4 +- .../experimental/api-speech-to-text/README.md | 2 + .../api-speech-to-text/README.zh.md | 2 + .../api-speech-to-text/src/index.ts | 12 +- .../api-speech-to-text/src/types.ts | 8 +- .../tests/controller.spec.ts | 22 +- .../client-ui-voice-input/README.i18n.yaml | 4 +- .../client-ui-voice-input/README.md | 2 + .../client-ui-voice-input/README.zh.md | 2 + .../client-ui-voice-input/package.json | 3 +- .../src/client/PreparationCard.tsx | 63 +++- .../src/client/VoiceInput.module.css | 2 + .../src/client/VoiceInput.tsx | 64 ++-- .../src/client/VoiceSetupDialog.tsx | 34 ++- .../src/client/VoiceSetupPrompt.tsx | 24 +- .../src/client/guidance.ts | 81 +++++ .../src/client/locales.ts | 216 +++++++++++++ .../client-ui-voice-input/src/client/mount.ts | 15 +- .../tests/cloud.client.spec.tsx | 285 ++++++++++++++++++ .../tests/mount.client.spec.ts | 25 +- .../tests/preparation.client.spec.tsx | 12 +- .../tests/readiness.client.spec.ts | 2 +- .../tests/setup-prompt.client.spec.tsx | 5 +- .../tests/voice-input.client.spec.tsx | 5 +- .../client-ui-voice-input/tsconfig.json | 3 + .../speech-to-text-deepseek/README.i18n.yaml | 37 +++ .../speech-to-text-deepseek/README.md | 82 +++++ .../speech-to-text-deepseek/README.zh.md | 82 +++++ .../speech-to-text-deepseek/locale/de.json | 6 + .../speech-to-text-deepseek/locale/en.json | 6 + .../speech-to-text-deepseek/locale/es.json | 6 + .../speech-to-text-deepseek/locale/fr.json | 6 + .../speech-to-text-deepseek/locale/ja.json | 6 + .../speech-to-text-deepseek/locale/pt.json | 6 + .../speech-to-text-deepseek/locale/ru.json | 6 + .../speech-to-text-deepseek/locale/zh.json | 6 + .../speech-to-text-deepseek/package.json | 52 ++++ .../speech-to-text-deepseek/src/audio.ts | 71 +++++ .../src/availability.ts | 67 ++++ .../speech-to-text-deepseek/src/config.ts | 71 +++++ .../speech-to-text-deepseek/src/index.ts | 98 ++++++ .../speech-to-text-deepseek/src/request.ts | 97 ++++++ .../tests/availability.spec.ts | 33 ++ .../tests/payload.spec.ts | 57 ++++ .../tests/provider.spec.ts | 229 ++++++++++++++ .../tests/request.spec.ts | 78 +++++ .../tests/service-double.ts | 86 ++++++ .../speech-to-text-deepseek/tsconfig.json | 30 ++ .../speech-to-text-deepseek/tsdown.config.ts | 3 + .../speech-to-text/README.i18n.yaml | 8 +- .../experimental/speech-to-text/README.md | 6 +- .../experimental/speech-to-text/README.zh.md | 6 +- .../speech-to-text/src/failure.ts | 16 + .../experimental/speech-to-text/src/index.ts | 77 +++-- .../experimental/speech-to-text/src/types.ts | 29 +- .../speech-to-text/tests/automatic.spec.ts | 123 ++++++++ .../tests/configuration.spec.ts | 6 +- .../speech-to-text/tests/service.spec.ts | 22 +- .../voice-input-bundle/README.i18n.yaml | 8 +- .../experimental/voice-input-bundle/README.md | 4 +- .../voice-input-bundle/README.zh.md | 4 +- .../voice-input-bundle/cordis.patch.yml | 5 +- .../voice-input-bundle/locale/de.json | 2 +- .../voice-input-bundle/locale/en.json | 2 +- .../voice-input-bundle/locale/es.json | 2 +- .../voice-input-bundle/locale/fr.json | 2 +- .../voice-input-bundle/locale/ja.json | 2 +- .../voice-input-bundle/locale/pt.json | 2 +- .../voice-input-bundle/locale/ru.json | 2 +- .../voice-input-bundle/locale/zh.json | 2 +- .../voice-input-bundle/package.json | 3 +- .../extensions/tool-cordis/src/api-catalog.ts | 30 +- .../references/packages.md | 1 + .../web/web-search-deepseek/README.i18n.yaml | 4 +- packages/web/web-search-deepseek/README.md | 2 +- packages/web/web-search-deepseek/README.zh.md | 2 +- pnpm-lock.yaml | 31 ++ scripts/experimental-package-policy.ts | 1 + scripts/gen-cordis-catalog.ts | 1 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.base.json | 1 + tsconfig.host.json | 2 + 121 files changed, 2915 insertions(+), 213 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.md create mode 100644 .agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.zh.md create mode 100644 apps/web/tests/expected/voice-input-cloud/recording.expected.md create mode 100644 apps/web/tests/expected/voice-input-cloud/sign-in.expected.md create mode 100644 apps/web/tests/fixtures/voice-input-cloud/cordis.patch.yml create mode 100644 apps/web/tests/voice-input-cloud.e2e.ts create mode 100644 packages/experimental/client-ui-voice-input/src/client/guidance.ts create mode 100644 packages/experimental/client-ui-voice-input/tests/cloud.client.spec.tsx create mode 100644 packages/experimental/speech-to-text-deepseek/README.i18n.yaml create mode 100644 packages/experimental/speech-to-text-deepseek/README.md create mode 100644 packages/experimental/speech-to-text-deepseek/README.zh.md create mode 100644 packages/experimental/speech-to-text-deepseek/locale/de.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/en.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/es.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/fr.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/ja.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/pt.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/ru.json create mode 100644 packages/experimental/speech-to-text-deepseek/locale/zh.json create mode 100644 packages/experimental/speech-to-text-deepseek/package.json create mode 100644 packages/experimental/speech-to-text-deepseek/src/audio.ts create mode 100644 packages/experimental/speech-to-text-deepseek/src/availability.ts create mode 100644 packages/experimental/speech-to-text-deepseek/src/config.ts create mode 100644 packages/experimental/speech-to-text-deepseek/src/index.ts create mode 100644 packages/experimental/speech-to-text-deepseek/src/request.ts create mode 100644 packages/experimental/speech-to-text-deepseek/tests/availability.spec.ts create mode 100644 packages/experimental/speech-to-text-deepseek/tests/payload.spec.ts create mode 100644 packages/experimental/speech-to-text-deepseek/tests/provider.spec.ts create mode 100644 packages/experimental/speech-to-text-deepseek/tests/request.spec.ts create mode 100644 packages/experimental/speech-to-text-deepseek/tests/service-double.ts create mode 100644 packages/experimental/speech-to-text-deepseek/tsconfig.json create mode 100644 packages/experimental/speech-to-text-deepseek/tsdown.config.ts create mode 100644 packages/experimental/speech-to-text/src/failure.ts create mode 100644 packages/experimental/speech-to-text/tests/automatic.spec.ts diff --git a/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.i18n.yaml b/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.i18n.yaml new file mode 100644 index 0000000000..4d34ab77f7 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-04-deepseek-cloud-speech-recognition.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.md +/agent-note-deepseek-cloud-speech-recognition-with-automatic-selection: + en: 8207b0d1f3d81458 + zh: 431b2eddb379d59b +/agent-note-deepseek-cloud-speech-recognition-with-automatic-selection/problem: + en: 65a3a75d5e55b24f + zh: 1ff61a652c2336e5 +/agent-note-deepseek-cloud-speech-recognition-with-automatic-selection/decision: + en: b966ee0bde43b730 + zh: c1e7fba00cea0c3b +/agent-note-deepseek-cloud-speech-recognition-with-automatic-selection/alternatives-considered: + en: 9452985af8f12400 + zh: 9e23d622f47f25c5 +/agent-note-deepseek-cloud-speech-recognition-with-automatic-selection/consequences: + en: e24554ebd7f99c40 + zh: 8d82de73b3ba5c84 diff --git a/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.md b/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.md new file mode 100644 index 0000000000..f786d06546 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.md @@ -0,0 +1,25 @@ +# Agent Note: DeepSeek cloud speech recognition with automatic selection + +Status: implemented + +English | [中文](2026-11-04-deepseek-cloud-speech-recognition.zh.md) + +## Problem + +Experimental voice input recognized speech only on the Host, so first use required downloading and preparing local models. Signed-in DeepSeek users should dictate without that setup, while signed-out users keep the local option. The [voice input decision](../architecture/2026-09-16-experimental-voice-input.md) forbids silently changing where recordings are processed and any fallback that uploads speech after a local failure. + +## Decision + +A separate provider package, `speech-to-text-deepseek`, registers `deepseek-asr` with `location: 'cloud'` and sends complete recordings to the One-Shot endpoint as raw PCM. It does not use the streaming WebSocket endpoint. It authenticates like the account model route, sending the token the account service releases for the endpoint, and refuses recordings without a stored DeepSeek account. The account service releases tokens to `https://harness.deepseek.com`, the default endpoint origin, but never loopback-issued grants. + +`speech-to-text` gains the `auto` preference and `autoOrder`. Selection happens before recording: the first registered provider that is not `unavailable` wins, and the Client sends that exact provider id with the recording. A failed recognition never re-routes audio, and signing out during a recording fails that recording rather than switching providers. One saved language serves every provider: a provider that does not list it receives `auto`, so the menu offers every language some provider recognizes and notes when the provider in use detects instead. The cloud provider sends the language as `preferred_language` and the UI language as `x-client-locale`, as the voice settings RFC specifies. + +Signed-in users get cloud recognition by default without an upload prompt; the user agreement and privacy policy disclose processing, and the interface names the location in the tooltip, transcription status and bundle details. The microphone stays visible whenever the plugin is enabled. Signing in uses a new optional Client service, `accountSignIn`, so the voice UI reuses the account dialog and browser flow instead of duplicating them. After sign-in the dialog closes and the user starts recording; recording never starts without a click because the sign-in tab takes focus and blur cancels capture. + +## Alternatives considered + +A first-use upload notice was rejected by product because the user agreement covers it. Falling back to cloud recognition after a local failure would violate the existing no-fallback guarantee. Calling `account.startSignIn` from the voice UI would duplicate the sign-in dialog, tab ownership and failure states. Limiting the menu to the languages of the provider in use was rejected: the saved language would appear reset whenever automatic selection switched providers. + +## Consequences + +The shipped bundle enables the cloud row against the production endpoint. Raw PCM is zero-padded to 32 bytes because the service rejects other lengths, adding at most 1 ms of silence. A rejected account token signs the account out. Verification covers automatic routing and language rules, account authentication and token rejection, retries with a stable `audio_id`, and a real-composition browser sign-in and dictation against a loopback service. diff --git a/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.zh.md b/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.zh.md new file mode 100644 index 0000000000..6a83adf5cc --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-04-deepseek-cloud-speech-recognition.zh.md @@ -0,0 +1,25 @@ +# Agent Note:带自动选择的 DeepSeek 云端语音识别 + +Status: implemented + +[English](2026-11-04-deepseek-cloud-speech-recognition.md) | 中文 + +## 问题 + +实验性语音输入只在 Host 上识别,首次使用必须下载并准备本地模型。已登录 DeepSeek 的用户应能免去这一步直接听写,未登录用户仍可选择本地识别。[语音输入决策](../architecture/2026-09-16-experimental-voice-input.zh.md)禁止悄悄改变录音的处理位置,也禁止本地失败后回退上传语音。 + +## 决策 + +独立的 Provider 包 `speech-to-text-deepseek` 以 `location: 'cloud'` 注册 `deepseek-asr`,把完整录音以裸 PCM 发送到 One-Shot 接口,不使用流式 WebSocket 接口。它与账号模型路由使用相同的鉴权,发送账号服务为该 endpoint 发放的令牌;没有已保存的 DeepSeek 账号时拒绝录音。账号服务向默认 endpoint 的 origin `https://harness.deepseek.com` 发放令牌,但从不发放本机回环签发的授权。 + +`speech-to-text` 新增 `auto` 偏好和 `autoOrder`。选择在录音之前进行:第一个已注册且不是 `unavailable` 的 Provider 胜出,Client 随录音发送这个确切的 Provider id。识别失败绝不改投其他 Provider;录音期间退出登录时,该次录音失败,而不是换用其他 Provider。一份保存的语言适用于所有 Provider:未列出该语言的 Provider 收到 `auto`,因此菜单列出任一 Provider 支持的全部语言,并在当前 Provider 改为自动识别时给出提示。云端 Provider 按语音配置 RFC 的要求,把语言作为 `preferred_language`、把界面语言作为 `x-client-locale` 发送。 + +已登录用户默认使用云端识别,不弹上传告知;处理方式由用户协议和隐私协议说明,界面在悬停提示、转写状态和 Bundle 详情中标明识别位置。只要插件已启用,麦克风就一直显示。登录使用新的可选 Client 服务 `accountSignIn`,语音 UI 复用账号的登录弹窗和浏览器流程,而不是重写一套。登录后弹窗关闭,由用户点击开始录音;登录标签页会夺走焦点,而失焦会取消录音,所以录音从不在没有点击的情况下自动开始。 + +## 考虑过的方案 + +产品否决了首次上传告知,因为用户协议已经覆盖。本地失败后回退到云端识别会破坏现有的无回退保证。在语音 UI 中直接调用 `account.startSignIn` 会重复登录弹窗、标签页所有权和失败状态。菜单只列当前 Provider 支持的语言被否决:自动选择切换 Provider 时,保存的语言看起来会被重置。 + +## 影响 + +发布的 Bundle 启用云端这一行,指向生产接口。服务拒绝其他长度的裸 PCM,所以补零到 32 字节,最多增加 1 毫秒静音。账号令牌被拒绝时账号退出登录。验证覆盖自动路由与语言规则、账号鉴权与令牌被拒、使用固定 `audio_id` 的重试,以及在真实组合中通过浏览器登录并对本机服务听写。 diff --git a/apps/web/tests/expected/voice-input-cloud/recording.expected.md b/apps/web/tests/expected/voice-input-cloud/recording.expected.md new file mode 100644 index 0000000000..906df62058 --- /dev/null +++ b/apps/web/tests/expected/voice-input-cloud/recording.expected.md @@ -0,0 +1,5 @@ +- textbox "Describe what you want to build, / commands, @ files or sessions" +- button "Cancel" +- img "Recording…" +- button "Stop and transcribe" +- button "Send message" [disabled] diff --git a/apps/web/tests/expected/voice-input-cloud/sign-in.expected.md b/apps/web/tests/expected/voice-input-cloud/sign-in.expected.md new file mode 100644 index 0000000000..bdcb0efdf1 --- /dev/null +++ b/apps/web/tests/expected/voice-input-cloud/sign-in.expected.md @@ -0,0 +1,6 @@ +- dialog "Cloud recognition requires a DeepSeek account": + - heading "Cloud recognition requires a DeepSeek account" [level=2] + - button "Cancel" + - paragraph: DeepSeek cloud recognition is selected. Sign in to use it without downloading models. + - button "Later" + - button "Sign in to DeepSeek" diff --git a/apps/web/tests/expected/voice-setup.expected.md b/apps/web/tests/expected/voice-setup.expected.md index 1cfcd160e0..1438069981 100644 --- a/apps/web/tests/expected/voice-setup.expected.md +++ b/apps/web/tests/expected/voice-setup.expected.md @@ -1,6 +1,7 @@ -- dialog "Set up voice input before recording": - - heading "Set up voice input before recording" [level=2] +- dialog "Prepare speech recognition": + - heading "Prepare speech recognition" [level=2] - button "Cancel" - - paragraph: Voice input is enabled. First use requires downloading and preparing local recognition models. Open the plugin details to review disk space, memory and time estimates before starting setup. + - paragraph: Sign in to DeepSeek to use cloud recognition without downloading models. You can also download a local model so recordings stay on the machine running DSH. - button "Later" - - button "Go to setup" + - button "Download local model" + - button "Sign in to DeepSeek" diff --git a/apps/web/tests/expected/voice-source-auto.expected.md b/apps/web/tests/expected/voice-source-auto.expected.md index a64c41e080..5007a79c07 100644 --- a/apps/web/tests/expected/voice-source-auto.expected.md +++ b/apps/web/tests/expected/voice-source-auto.expected.md @@ -1,4 +1,4 @@ -- strong: SenseVoiceSmall (INT8) +- strong: SenseVoiceSmall (INT8) local recognition - paragraph: Local models will be downloaded to the machine running DSH. No Python or compiler is required. - term: Disk space - definition: Allow about 1 GB for models, runtime, and download caches diff --git a/apps/web/tests/expected/voice-source-manual.expected.md b/apps/web/tests/expected/voice-source-manual.expected.md index 1867a5bb80..c7406c3adc 100644 --- a/apps/web/tests/expected/voice-source-manual.expected.md +++ b/apps/web/tests/expected/voice-source-manual.expected.md @@ -1,4 +1,4 @@ -- strong: SenseVoiceSmall (INT8) +- strong: SenseVoiceSmall (INT8) local recognition - paragraph: Local models will be downloaded to the machine running DSH. No Python or compiler is required. - term: Disk space - definition: Allow about 1 GB for models, runtime, and download caches diff --git a/apps/web/tests/fixtures/voice-input-cloud/cordis.patch.yml b/apps/web/tests/fixtures/voice-input-cloud/cordis.patch.yml new file mode 100644 index 0000000000..0413f146d6 --- /dev/null +++ b/apps/web/tests/fixtures/voice-input-cloud/cordis.patch.yml @@ -0,0 +1,18 @@ +# The cloud dictation scenario points the shipped account provider and the cloud recognizer at one loopback +# double. The scenario substitutes {{origin}} after the listener binds, so no port is ever committed here. +- id: deepseek-account + config: + platformOrigin: "{{origin}}" + inferenceOrigin: "{{origin}}" + allowLoopbackHttp: true +- id: ui-settings-account + config: + step: done + completion: completed +# Automatic selection then has only the cloud recognizer to choose. +- id: speech-to-text-sensevoice + disabled: true +- id: speech-to-text-deepseek + config: + endpoint: "{{origin}}/api/v0/asr/transcribe" + allowLoopbackHttp: true diff --git a/apps/web/tests/voice-download.e2e.ts b/apps/web/tests/voice-download.e2e.ts index a541bef2fb..2470165299 100644 --- a/apps/web/tests/voice-download.e2e.ts +++ b/apps/web/tests/voice-download.e2e.ts @@ -10,6 +10,9 @@ import { expect, it, onTestFinished } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' import { newEnglishPage } from './support.ts' +/** Model download only: the shipped cloud recognizer would change automatic selection and its setup guidance. */ +const LOCAL_ONLY = '- id: speech-to-text-deepseek\n disabled: true\n' + const bundle = fileURLToPath(new URL('../../../packages/experimental/voice-input-bundle', import.meta.url)) const expected = fileURLToPath(new URL('./expected/voice-download.expected.md', import.meta.url)) // The input-device picker on the same page shows its own alert when headless Chromium offers no microphone. @@ -37,7 +40,7 @@ it('shows the failed asset, actual download source and recovery advice, then ret const address = server.address() if (!address || typeof address === 'string') throw new Error('Expected a loopback listener') const origin = `http://127.0.0.1:${address.port}`, overlay = join(root, 'voice.patch.yml') - await writeFile(overlay, `- id: speech-to-text-sensevoice\n config:\n dataRoot: ${JSON.stringify(join(root, 'models'))}\n modelOrigin: ${origin}\n`) + await writeFile(overlay, `- id: speech-to-text-sensevoice\n config:\n dataRoot: ${JSON.stringify(join(root, 'models'))}\n modelOrigin: ${origin}\n${LOCAL_ONLY}`) const scaffold = await launchWebScaffold({ profile: { packages: [{ dir: bundle, enabled: true }] }, extraOverlayPath: overlay }) resources.scaffold = scaffold const browser = await chromium.launch() @@ -98,7 +101,7 @@ it.each([{ winner: 0, manual: false }, { winner: 1, manual: false }, { winner: 0 const overlay = join(root, 'voice.patch.yml') await writeFile(overlay, `- id: speech-to-text-sensevoice\n config: ${JSON.stringify({ dataRoot: join(root, 'models'), modelOrigins: origins, modelProbeTimeoutMs: 10_000, - })}\n`) + })}\n${LOCAL_ONLY}`) const scaffold = await launchWebScaffold({ profile: { packages: [{ dir: bundle, enabled: true }] }, extraOverlayPath: overlay }) resources.scaffold = scaffold const browser = await chromium.launch(); resources.browser = browser diff --git a/apps/web/tests/voice-input-cloud.e2e.ts b/apps/web/tests/voice-input-cloud.e2e.ts new file mode 100644 index 0000000000..15703f90f5 --- /dev/null +++ b/apps/web/tests/voice-input-cloud.e2e.ts @@ -0,0 +1,172 @@ +// Real-composition acceptance for cloud dictation. The scaffold boots the shipped Web Loader tree with the voice +// bundle; one loopback double plays the DeepSeek Platform for sign-in and the One-Shot recognition endpoint, so the +// real account provider, speech service, cloud recognizer, Remote and browser UI run end to end. +import { createServer, type Server } from 'node:http' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest' +import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, saveFailureShot } from './support.ts' + +const OVERLAY_TEMPLATE = fileURLToPath(new URL('./fixtures/voice-input-cloud/cordis.patch.yml', import.meta.url)) +const BUNDLE = fileURLToPath(new URL('../../../packages/experimental/voice-input-bundle', import.meta.url)) +const SIGN_IN_EXPECTED = fileURLToPath(new URL('./expected/voice-input-cloud/sign-in.expected.md', import.meta.url)) +const RECORDING_EXPECTED = fileURLToPath(new URL('./expected/voice-input-cloud/recording.expected.md', import.meta.url)) +const MODE = webSnapshotMode() +const TOKEN = 'dsh_web_cloud_dictation_test' +const CODE = 'cloud-dictation-code' +const TEXT = 'Summarize the latest pull request' + +/** One recognition request as the double received it. */ +interface RecognitionRequest { + readonly token: string | undefined + readonly format: string | undefined + readonly audioId: string | undefined + readonly language: string | undefined + readonly locale: string | undefined + readonly pcmBytes: number +} + +/** Loopback Platform and recognition double; `rejectNext` makes the next recognition reject the account token. */ +async function mockServices() { + const recognitions: RecognitionRequest[] = [] + const control = { rejectNext: false } + let state: string | undefined + let redirectUri: string | undefined + const server: Server = createServer((req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1') + const chunks: Buffer[] = [] + req.on('data', (chunk: Buffer) => { chunks.push(chunk) }) + req.on('end', () => { + void (async () => { + const body = Buffer.concat(chunks) + const reply = (payload: unknown, code = 0): void => { + res.writeHead(200, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ code, msg: '', data: code === 0 ? { biz_code: 0, biz_msg: '', biz_data: payload } : null })) + } + if (url.pathname === '/dsh/authorize') { + const callback = new URL(redirectUri ?? '/') + callback.searchParams.set('code', CODE) + callback.searchParams.set('state', state ?? '') + res.writeHead(302, { location: callback.href }).end() + return + } + if (url.pathname === '/dsh/authorized') { res.writeHead(200, { 'content-type': 'text/html' }).end('Authorized'); return } + if (req.method === 'POST' && url.pathname === '/auth-api/v0/dsh/auth_init') { + const payload = JSON.parse(body.toString('utf8')) as Record + state = String(payload.state) + redirectUri = String(payload.redirect_uri) + reply({ authorize_url: `${origin}/dsh/authorize?authorize_id=cloud`, authorize_id: 'cloud', expires_in: 300 }) + return + } + if (req.method === 'POST' && url.pathname === '/auth-api/v0/dsh/auth_exchange') { + reply({ token: TOKEN, authorized_url: `${origin}/dsh/authorized` }) + return + } + if (req.method === 'POST' && url.pathname === '/api/v0/asr/transcribe') { + const form = await new Response(body, { headers: { 'content-type': req.headers['content-type'] ?? '' } }).formData() + const file = form.get('file'), format = form.get('format'), audioId = form.get('audio_id'), language = form.get('preferred_language') + const token = req.headers['x-dsh-auth-token'], locale = req.headers['x-client-locale'] + recognitions.push({ token: typeof token === 'string' ? token : undefined, format: typeof format === 'string' ? format : undefined, + audioId: typeof audioId === 'string' ? audioId : undefined, language: typeof language === 'string' ? language : undefined, + locale: typeof locale === 'string' ? locale : undefined, pcmBytes: file instanceof File ? file.size : -1 }) + if (control.rejectNext) { control.rejectNext = false; reply(null, 40003); return } + reply({ text: TEXT, audio_id: audioId }) + return + } + if (req.headers['x-dsh-auth-token'] !== TOKEN) { res.writeHead(401).end(); return } + if (url.pathname === '/auth-api/v0/users/current') { reply({ id: 'cloud-user', email: '', id_profile: { name: 'Cloud User' } }); return } + if (url.pathname === '/api/v0/users/get_user_summary') { reply({ normal_wallets: [{ currency: 'CNY', balance: '1.00' }], bonus_wallets: [] }); return } + if (url.pathname === '/api/v0/users/get_unnotified_bonuses') { reply([]); return } + res.writeHead(404).end() + })() + }) + }) + await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('cloud dictation: missing mock listener') + const origin = `http://127.0.0.1:${String(address.port)}` + return { + origin, recognitions, control, + close: () => new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }), + } +} + +describe.skipIf(MODE === 'record')('web e2e: cloud dictation after DeepSeek sign-in', () => { + let root: string | undefined + let scaffold: WebScaffold + let browser: Browser + let services: Awaited> + beforeAll(async () => { + services = await mockServices() + root = await mkdtemp(join(tmpdir(), 'dsh-web-voice-cloud-')) + const overlay = join(root, 'voice-cloud.overlay.yml') + await writeFile(overlay, (await readFile(OVERLAY_TEMPLATE, 'utf8')).replaceAll('{{origin}}', services.origin)) + scaffold = await launchWebScaffold({ profile: { packages: [{ dir: BUNDLE, enabled: true }] }, extraOverlayPath: overlay }) + browser = await chromium.launch({ args: ['--use-fake-ui-for-media-stream', '--use-fake-device-for-media-stream'] }) + }) + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await services?.close() + if (root !== undefined) await rm(root, { recursive: true, force: true }) + }) + + it('asks for sign-in, dictates through the account token, and asks again after the service rejects it', async () => { + const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, locale: 'en-US' }) + onTestFinished(() => context.close()) + const page = await context.newPage() + const tripwire = watchConsole(page) + onTestFailed(() => saveFailureShot(page, 'web-e2e-voice-input-cloud')) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const input = page.locator('[data-composer-input]') + + await page.getByRole('button', { name: 'Open voice input setup', exact: true }).click() + const prompt = page.getByRole('dialog', { name: 'Cloud recognition requires a DeepSeek account', exact: true }) + await prompt.waitFor() + await compareOrRefreshGolden(SIGN_IN_EXPECTED, await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), MODE) + const tab = context.waitForEvent('page') + await prompt.getByRole('button', { name: 'Sign in to DeepSeek', exact: true }).click() + const authorization = await tab + await authorization.waitForURL(url => url.pathname === '/dsh/authorized', { timeout: 30_000 }) + await page.bringToFront() + expect(await prompt.count()).toBe(0) + + const mic = page.getByRole('button', { name: 'Start recording', exact: true }) + await mic.waitFor({ timeout: 30_000 }) + await mic.hover() + await page.getByRole('tooltip', { name: 'Dictate · cloud recognition', exact: true }).waitFor() + await mic.click() + const stop = page.getByRole('button', { name: 'Stop and transcribe', exact: true }) + await stop.waitFor() + await compareOrRefreshGolden(RECORDING_EXPECTED, await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd), MODE) + // Controlled fake microphone audio occupies this recording interval; it is not a readiness wait. + await page.waitForTimeout(300) + await stop.click() + await expect.poll(() => input.innerText(), { timeout: 30_000 }).toBe(TEXT) + expect(services.recognitions).toHaveLength(1) + const [first] = services.recognitions + // The default automatic language sends no preference; the English UI is sent as the service's locale. + expect(first).toMatchObject({ token: TOKEN, format: 'pcm', language: undefined, locale: 'en_US' }) + expect(first!.audioId).toMatch(/^[0-9a-f-]{36}$/) + expect(first!.pcmBytes % 32).toBe(0) + expect(first!.pcmBytes).toBeGreaterThan(0) + + services.control.rejectNext = true + await mic.click() + await stop.waitFor() + await page.waitForTimeout(300) + await stop.click() + await page.getByText('Your DeepSeek sign-in has expired. Sign in again.', { exact: true }).waitFor({ timeout: 30_000 }) + await page.getByRole('button', { name: 'Sign in to DeepSeek', exact: true }).waitFor() + expect(services.recognitions).toHaveLength(2) + expect(await input.innerText()).toBe(TEXT) + await page.getByRole('button', { name: 'Cancel', exact: true }).click() + await page.getByRole('button', { name: 'Open voice input setup', exact: true }).waitFor({ timeout: 30_000 }) + expect(tripwire.pageErrors).toEqual([]) + }, 120_000) +}) diff --git a/apps/web/tests/voice-input.e2e.ts b/apps/web/tests/voice-input.e2e.ts index 133bcb416a..66dbe8daa7 100644 --- a/apps/web/tests/voice-input.e2e.ts +++ b/apps/web/tests/voice-input.e2e.ts @@ -28,7 +28,8 @@ it.skipIf(webSnapshotMode() === 'record')('guides voice setup, records from stan } }) const overlay = join(scratch, 'voice.patch.yml') - await writeFile(overlay, '- id: speech-to-text-sensevoice\n disabled: true\n') + // Local recording only: the shipped cloud recognizer would change automatic selection and its setup guidance. + await writeFile(overlay, '- id: speech-to-text-sensevoice\n disabled: true\n- id: speech-to-text-deepseek\n disabled: true\n') const prompt = fixtureUserPrompts(await readFile(fixture, 'utf8'))[0]! const prefix = 'Use the bash tool to ' const scaffold = await launchWebScaffold({ profile: { packages: [{ dir: bundle, enabled: true }] }, diff --git a/apps/web/tests/voice-setup.e2e.ts b/apps/web/tests/voice-setup.e2e.ts index b592e9eb48..bf1c3c6f8e 100644 --- a/apps/web/tests/voice-setup.e2e.ts +++ b/apps/web/tests/voice-setup.e2e.ts @@ -1,4 +1,4 @@ -/** Empty local caches guide explicit enablement to plugin setup without starting installation. */ +/** Signed out with empty local caches, enabling voice input offers DeepSeek sign-in or local setup without starting installation. */ import { fileURLToPath } from 'node:url' import { chromium, type Browser } from 'playwright' import { expect, it, onTestFinished } from 'vitest' @@ -8,7 +8,7 @@ import { newEnglishPage } from './support.ts' const bundle = fileURLToPath(new URL('../../../packages/experimental/voice-input-bundle', import.meta.url)) const expected = fileURLToPath(new URL('./expected/voice-setup.expected.md', import.meta.url)) -it('guides a newly enabled voice plugin to installation and lets the user postpone it', async () => { +it('offers sign-in or local setup when a signed-out user enables the voice plugin and lets the user postpone it', async () => { const resources: { scaffold?: WebScaffold; browser?: Browser } = {} onTestFinished(async () => { try { await resources.browser?.close() } finally { await resources.scaffold?.close() } @@ -23,7 +23,7 @@ it('guides a newly enabled voice plugin to installation and lets the user postpo const toggle = page.getByRole('switch', { name: 'Enable Voice input', exact: true }) await toggle.waitFor() expect(await toggle.getAttribute('aria-checked')).toBe('false') - const dialog = page.getByRole('dialog', { name: 'Set up voice input before recording', exact: true }) + const dialog = page.getByRole('dialog', { name: 'Prepare speech recognition', exact: true }) expect(await dialog.count()).toBe(0) await toggle.click() await dialog.waitFor() @@ -35,7 +35,7 @@ it('guides a newly enabled voice plugin to installation and lets the user postpo expect(await card.getByRole('status').textContent()).toBe('') await toggle.click() await page.getByRole('switch', { name: 'Enable Voice input', exact: true, checked: false }).click() - await dialog.getByRole('button', { name: 'Go to setup', exact: true }).click() + await dialog.getByRole('button', { name: 'Download local model', exact: true }).click() await page.getByRole('button', { name: 'Download and prepare', exact: true }).waitFor() expect(await dialog.count()).toBe(0) expect(await page.getByText('Local models will be downloaded to the machine running DSH. No Python or compiler is required.', { exact: true }).count()).toBe(1) @@ -44,9 +44,9 @@ it('guides a newly enabled voice plugin to installation and lets the user postpo expect(await source.inputValue()).toBe('') expect(await source.getByRole('option').allTextContents()).toEqual(['Automatic (recommended)', 'Hugging Face', 'HF-Mirror (China mirror)']) await compareOrRefreshGolden(fileURLToPath(new URL('./expected/voice-source-auto.expected.md', import.meta.url)), - await captureStableAria(page, '[data-speech-provider]', scaffold.workspaceCwd), webSnapshotMode()) + await captureStableAria(page, '[data-speech-provider="sensevoice-local"]', scaffold.workspaceCwd), webSnapshotMode()) await source.selectOption('https://hf-mirror.com') await compareOrRefreshGolden(fileURLToPath(new URL('./expected/voice-source-manual.expected.md', import.meta.url)), - await captureStableAria(page, '[data-speech-provider]', scaffold.workspaceCwd), webSnapshotMode()) + await captureStableAria(page, '[data-speech-provider="sensevoice-local"]', scaffold.workspaceCwd), webSnapshotMode()) expect(tripwire.pageErrors).toEqual([]) }) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index ec47d94afe..aa8737fad6 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -56,6 +56,7 @@ "tests/connection-recovery.e2e.ts", "tests/server-restart.e2e.ts", "tests/voice-input.e2e.ts", + "tests/voice-input-cloud.e2e.ts", "tests/cot-translation.e2e.ts", "tests/cot-translation-paid.e2e.ts", "tests/forge-panel.e2e.ts", diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 541f35bf98..728aa9bfa1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -859,7 +859,7 @@ export interface Config { ## `@deepseek-ai/dsh-deepseek-account-platform` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts) +- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:41`](../packages/credentials/deepseek-account-platform/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ @@ -872,6 +872,8 @@ export interface Config { embeddedPageDist?: string /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ inferenceOrigin?: string + /** Further exact HTTP(S) origins of DeepSeek services, such as speech recognition, allowed to receive account tokens. */ + serviceOrigins?: string[] /** Allow HTTP only on loopback for the development Mock. */ allowLoopbackHttp?: boolean /** Map authorization and completion pages to platformOrigin for private development proxies. */ @@ -900,7 +902,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-api-speech-to-text` - `inject`: `speechToText` · `typert` -- `source`: [`packages/experimental/api-speech-to-text/src/index.ts:20`](../packages/experimental/api-speech-to-text/src/index.ts) +- `source`: [`packages/experimental/api-speech-to-text/src/index.ts:23`](../packages/experimental/api-speech-to-text/src/index.ts) ```ts config-catalog /** Limits applied before decoding or calling a provider. */ @@ -1340,13 +1342,15 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-speech-to-text` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/speech-to-text/src/index.ts:20`](../packages/experimental/speech-to-text/src/index.ts) +- `source`: [`packages/experimental/speech-to-text/src/index.ts:27`](../packages/experimental/speech-to-text/src/index.ts) ```ts config-catalog /** Live selection read before a transcription starts; `configure()` writes it through the profile. */ export interface Config { - /** Registered provider selected when the caller omits an id. */ + /** Registered provider selected when the caller omits an id, or `auto` to follow `autoOrder`. */ defaultProvider: Volatile + /** Provider ids considered by automatic selection, in preference order; required while `defaultProvider` is `auto`. */ + autoOrder: string[] /** Provider language hint selected when the caller omits one. */ language: Volatile } @@ -3437,6 +3441,37 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-speech-to-text-deepseek` + +- `inject`: `speechToText` +- `source`: [`packages/experimental/speech-to-text-deepseek/src/config.ts:7`](../packages/experimental/speech-to-text-deepseek/src/config.ts) + +```ts config-catalog +/** Endpoint and service limits; requests authenticate with the DeepSeek account token released for the endpoint. */ +export interface Config { + /** Unique registration id; `speech-to-text` selects this exact id. */ + providerId: string + /** Complete One-Shot transcription URL. */ + endpoint: string + /** Permit plain HTTP to a loopback endpoint, for local service doubles. */ + allowLoopbackHttp: boolean + /** Deadline for one request attempt, including its response body. */ + timeoutMs: number + /** Maximum multipart request bytes the service accepts. */ + maxRequestBytes: number + /** Maximum recording duration the service accepts. */ + maxDurationSeconds: number + /** Maximum response body bytes read from the service. */ + maxResponseBytes: number + /** Language codes the service recognizes, sent as `preferred_language`; `auto` sends none and must be listed. */ + languages: string[] +} +``` + + diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index ddb66d4024..d0c985d242 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -861,7 +861,7 @@ export interface Config { ## `@deepseek-ai/dsh-deepseek-account-platform` - `inject`: `credentials` · `authorization` -- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:23`](../packages/credentials/deepseek-account-platform/src/index.ts) +- `source`: [`packages/credentials/deepseek-account-platform/src/index.ts:41`](../packages/credentials/deepseek-account-platform/src/index.ts) ```ts config-catalog /** Deployment-specific platform and request deadlines. */ @@ -874,6 +874,8 @@ export interface Config { embeddedPageDist?: string /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ inferenceOrigin?: string + /** Further exact HTTP(S) origins of DeepSeek services, such as speech recognition, allowed to receive account tokens. */ + serviceOrigins?: string[] /** Allow HTTP only on loopback for the development Mock. */ allowLoopbackHttp?: boolean /** Map authorization and completion pages to platformOrigin for private development proxies. */ @@ -902,7 +904,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-api-speech-to-text` - `inject`: `speechToText` · `typert` -- `source`: [`packages/experimental/api-speech-to-text/src/index.ts:20`](../packages/experimental/api-speech-to-text/src/index.ts) +- `source`: [`packages/experimental/api-speech-to-text/src/index.ts:23`](../packages/experimental/api-speech-to-text/src/index.ts) ```ts config-catalog /** Limits applied before decoding or calling a provider. */ @@ -1342,13 +1344,15 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-speech-to-text` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/experimental/speech-to-text/src/index.ts:20`](../packages/experimental/speech-to-text/src/index.ts) +- `source`: [`packages/experimental/speech-to-text/src/index.ts:27`](../packages/experimental/speech-to-text/src/index.ts) ```ts config-catalog /** Live selection read before a transcription starts; `configure()` writes it through the profile. */ export interface Config { - /** Registered provider selected when the caller omits an id. */ + /** Registered provider selected when the caller omits an id, or `auto` to follow `autoOrder`. */ defaultProvider: Volatile + /** Provider ids considered by automatic selection, in preference order; required while `defaultProvider` is `auto`. */ + autoOrder: string[] /** Provider language hint selected when the caller omits one. */ language: Volatile } @@ -3439,6 +3443,37 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-speech-to-text-deepseek` + +- `inject`: `speechToText` +- `source`: [`packages/experimental/speech-to-text-deepseek/src/config.ts:7`](../packages/experimental/speech-to-text-deepseek/src/config.ts) + +```ts config-catalog +/** Endpoint and service limits; requests authenticate with the DeepSeek account token released for the endpoint. */ +export interface Config { + /** Unique registration id; `speech-to-text` selects this exact id. */ + providerId: string + /** Complete One-Shot transcription URL. */ + endpoint: string + /** Permit plain HTTP to a loopback endpoint, for local service doubles. */ + allowLoopbackHttp: boolean + /** Deadline for one request attempt, including its response body. */ + timeoutMs: number + /** Maximum multipart request bytes the service accepts. */ + maxRequestBytes: number + /** Maximum recording duration the service accepts. */ + maxDurationSeconds: number + /** Maximum response body bytes read from the service. */ + maxResponseBytes: number + /** Language codes the service recognizes, sent as `preferred_language`; `auto` sends none and must be listed. */ + languages: string[] +} +``` + + diff --git a/docs/module-graph.md b/docs/module-graph.md index f58da15929..176ac5f286 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -311,6 +311,7 @@ flowchart TD pkg_plugin_recommendations["plugin-recommendations"] pkg_session_title_all_prompts_llm["session-title-all-prompts-llm"] pkg_skill_badge["skill-badge"] + pkg_speech_to_text_deepseek["speech-to-text-deepseek"] pkg_tool_ralph["tool-ralph"] pkg_tool_session_query["tool-session-query"] pkg_tool_terminal["tool-terminal"] @@ -791,6 +792,8 @@ flowchart TD pkg_experimental_worktree --> pkg_sandbox_policy pkg_experimental_worktree --> pkg_subprocess pkg_experimental_worktree --> pkg_working_directory + pkg_speech_to_text_deepseek --> pkg_deepseek_account + pkg_speech_to_text_deepseek --> pkg_experimental_speech_to_text pkg_command_feedback --> pkg_anonymous_user_id pkg_command_feedback --> pkg_commands pkg_command_feedback --> pkg_session @@ -1768,6 +1771,7 @@ flowchart TD | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory) | +| [`speech-to-text-deepseek`](../packages/experimental/speech-to-text-deepseek) | `experimental` | [`deepseek-account`](../packages/credentials/deepseek-account), [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 372f734770..2e4f7413e1 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -313,6 +313,7 @@ flowchart TD pkg_plugin_recommendations["plugin-recommendations"] pkg_session_title_all_prompts_llm["session-title-all-prompts-llm"] pkg_skill_badge["skill-badge"] + pkg_speech_to_text_deepseek["speech-to-text-deepseek"] pkg_tool_ralph["tool-ralph"] pkg_tool_session_query["tool-session-query"] pkg_tool_terminal["tool-terminal"] @@ -793,6 +794,8 @@ flowchart TD pkg_experimental_worktree --> pkg_sandbox_policy pkg_experimental_worktree --> pkg_subprocess pkg_experimental_worktree --> pkg_working_directory + pkg_speech_to_text_deepseek --> pkg_deepseek_account + pkg_speech_to_text_deepseek --> pkg_experimental_speech_to_text pkg_command_feedback --> pkg_anonymous_user_id pkg_command_feedback --> pkg_commands pkg_command_feedback --> pkg_session @@ -1770,6 +1773,7 @@ flowchart TD | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) | `credentials` | [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`host-webserver`](../packages/host/webserver) | | [`experimental-ptc-runtime-python`](../packages/experimental/ptc-runtime-python) | `experimental` | [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory) | +| [`speech-to-text-deepseek`](../packages/experimental/speech-to-text-deepseek) | `experimental` | [`deepseek-account`](../packages/credentials/deepseek-account), [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | | [`command-feedback`](../packages/feedback/command-feedback) | `feedback` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`commands`](../packages/interaction/commands), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) | | [`permission-presets`](../packages/interaction/permission-presets) | `interaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) | | [`jobs-local`](../packages/jobs/jobs-local) | `jobs` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`scope`](../packages/core/scope), [`timeout`](../packages/util/timeout) | diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 2a084fb29f..bcb6a205f2 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -338,7 +338,7 @@ abstract signOut(client: AccountClientMetadata): Promise abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. + * Resolve a credential only for an origin the provider allows, such as its inference and service origins. * @param url - actual request destination or API base URL. * @returns stored token, or undefined for other origins or a signed-out account. */ diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 1e9221699a..8b66881431 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -338,7 +338,7 @@ abstract signOut(client: AccountClientMetadata): Promise abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. + * Resolve a credential only for an origin the provider allows, such as its inference and service origins. * @param url - actual request destination or API base URL. * @returns stored token, or undefined for other origins or a signed-out account. */ diff --git a/docs/subsystems/voice-input.i18n.yaml b/docs/subsystems/voice-input.i18n.yaml index 5d8400aa8e..3360ab1087 100644 --- a/docs/subsystems/voice-input.i18n.yaml +++ b/docs/subsystems/voice-input.i18n.yaml @@ -6,8 +6,8 @@ en: b21f58d0dcb90287 zh: be60807d02623a87 /voice-input/provider-selection: - en: 3a5ec4718b839349 - zh: a8448bd6064d4c81 + en: 5693cf0e60ba2c08 + zh: 2a366af304dcdc74 /voice-input/browser-and-host-ownership: en: 404d67d8276522db zh: f653397888d2e616 diff --git a/docs/subsystems/voice-input.md b/docs/subsystems/voice-input.md index 1d85e8226a..6b597ca1fb 100644 --- a/docs/subsystems/voice-input.md +++ b/docs/subsystems/voice-input.md @@ -8,6 +8,8 @@ Experimental speech recognition has three roles: the [Service Definition](../../ `SpeechProviderId` brands the registration identity. `SpeechProviderInfo` carries a display name, accepted `languages` hints and `host-local` or `cloud` processing location. `SpeechRequest` contains WAV bytes and optional provider/language selection; `resolve()` produces `SpeechSpec` with one captured provider instance. A missing provider or unsupported language fails; replacement or withdrawal invalidates resolved work. Audio never falls back to a different provider. +`defaultProvider: auto` selects, before recording, the first registered `autoOrder` provider whose state is not `unavailable`. The bundle orders the [DeepSeek cloud provider](../../packages/experimental/speech-to-text-deepseek/README.md) before SenseVoice, so a signed-in DeepSeek account uses cloud recognition. The cloud provider stays `unavailable` with `sign-in-required` until an account is stored, authenticates like the account model route, and sends the saved language and the UI language to the service. A provider that does not list the saved language receives `auto`. Expected failures carry a `SpeechFailureCode` through the Remote for localized recovery. + `SpeechProvider.transcribe()` accepts one complete `SpeechInput` and an `AbortSignal`. `Transcript` returns plain `text`, `audioSeconds` and `inferenceSeconds`. Providers honor cancellation and settle their work before deregistration completes. The local provider serializes calls, bounds its queue and manages its worker lifetime independently of Sessions. ## Browser and Host ownership @@ -124,8 +126,9 @@ async *follow(caller: AbortSignal): AsyncIterable snapshot(): SpeechSnapshot /** - * Persist changed selection fields into this plugin's profile entry; the resulting language must be accepted by the selected provider. - * @param patch - explicit provider or language changes. + * Persist changed selection fields into this plugin's profile entry. The language must be listed by at least one + * registered provider; a provider that does not list it receives `auto` when it transcribes. + * @param patch - explicit provider, `auto`, or language changes. * @returns after the profile write and the live update it applies. */ async configure(patch: SpeechSelectionPatch): Promise @@ -145,8 +148,9 @@ prepare(id: SpeechProviderId, options?: SpeechPreparationOptions): void async cancelPreparation(id: SpeechProviderId): Promise /** - * Apply composition defaults and capture the selected provider. Missing providers and unsupported languages fail explicitly. - * @param request - complete recording and optional selection. + * Apply the saved selection and capture the provider. Missing providers and hints no registered provider lists fail + * explicitly; the captured provider receives the hint when it lists it and `auto` otherwise. + * @param request - complete recording, optional selection and the client's UI language. * @returns provider-pinned input for transcribe(). */ resolve(request: SpeechRequest): SpeechSpec diff --git a/docs/subsystems/voice-input.zh.md b/docs/subsystems/voice-input.zh.md index 78a70ab9c2..b272d5f111 100644 --- a/docs/subsystems/voice-input.zh.md +++ b/docs/subsystems/voice-input.zh.md @@ -8,6 +8,8 @@ `SpeechProviderId` 为注册标识添加类型品牌。`SpeechProviderInfo` 携带显示名称、支持的 `languages` 语言提示及 `host-local` 或 `cloud` 处理位置。`SpeechRequest` 包含 WAV 字节和可选的 Provider、语言选择;`resolve()` 生成捕获一个 Provider 实例的 `SpeechSpec`。缺失的 Provider 或不支持的语言会报错;替换或撤销会使已解析的任务失效。音频不会回退到其他 Provider。 +`defaultProvider: auto` 在录音前选择 `autoOrder` 中第一个已注册且状态不是 `unavailable` 的 Provider。Bundle 把 [DeepSeek 云端 Provider](../../packages/experimental/speech-to-text-deepseek/README.zh.md) 排在 SenseVoice 之前,因此已登录 DeepSeek 账号时使用云端识别。云端 Provider 在保存账号之前处于带 `sign-in-required` 的 `unavailable`,鉴权方式与账号模型路由相同,并把保存的语言和界面语言发送给服务。未列出已保存语言的 Provider 收到 `auto`。可预期的失败通过 Remote 携带 `SpeechFailureCode`,供界面本地化恢复提示。 + `SpeechProvider.transcribe()` 接收完整的 `SpeechInput` 与 `AbortSignal`。`Transcript` 返回纯文本 `text`、`audioSeconds` 和 `inferenceSeconds`。Provider 响应取消,并在注销完成前结束其任务。本地 Provider 串行执行调用、限制队列,并独立于 Session 管理工作进程生命周期。 ## 浏览器与 Host 所有权 @@ -124,8 +126,9 @@ async *follow(caller: AbortSignal): AsyncIterable snapshot(): SpeechSnapshot /** - * Persist changed selection fields into this plugin's profile entry; the resulting language must be accepted by the selected provider. - * @param patch - explicit provider or language changes. + * Persist changed selection fields into this plugin's profile entry. The language must be listed by at least one + * registered provider; a provider that does not list it receives `auto` when it transcribes. + * @param patch - explicit provider, `auto`, or language changes. * @returns after the profile write and the live update it applies. */ async configure(patch: SpeechSelectionPatch): Promise @@ -145,8 +148,9 @@ prepare(id: SpeechProviderId, options?: SpeechPreparationOptions): void async cancelPreparation(id: SpeechProviderId): Promise /** - * Apply composition defaults and capture the selected provider. Missing providers and unsupported languages fail explicitly. - * @param request - complete recording and optional selection. + * Apply the saved selection and capture the provider. Missing providers and hints no registered provider lists fail + * explicitly; the captured provider receives the hint when it lists it and `auto` otherwise. + * @param request - complete recording, optional selection and the client's UI language. * @returns provider-pinned input for transcribe(). */ resolve(request: SpeechRequest): SpeechSpec diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index ebcb4c7149..81358aa038 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -15,8 +15,8 @@ en: c26f81e8adf0128b zh: e11ab371f51f66bc /deepseek-ai-dsh-client-ui-settings-account/use-this-package: - en: 2e63a8b01d800894 - zh: 42db1f28e2ddb2a3 + en: ec5e1aa5d0e3ae00 + zh: 0bb340658d11656f /deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding: en: 7ae4e68f9491b068 zh: f7478269bf8d28b3 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index f16fe754b3..5824aac284 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -30,6 +30,8 @@ A new account-model sign-in-required event displays “Model unavailable. Please Desktop and plain Web clients both mount the sidebar account launcher, Account settings, the sign-in step of model onboarding, and the account-state subscription. Desktop main opens the authorization page in the system browser. A plain Web client, identified by the absent Desktop preload bridge, sends `login_source` web with its own origin as the callback origin, preopens a tab during the sign-in click, navigates it to the authorization URL with the same `theme` parameter once its attempt receives one, and closes it on failure, expiry, or cancellation; a blocked popup leaves the copy-link route. Embedded Platform pages, Desktop onboarding, and the native device reader stay Desktop-only, so Web Platform links open new tabs. +While the Peer may watch the account, the plugin provides the Client service `accountSignIn`, whose `open()` shows the sign-in dialog and starts a browser attempt; callers invoke it from a click so a plain Web client can preopen the authorization tab. Revoking account access withdraws the service. + The sidebar and Account settings display circular profile images with diameters of 24px and 32px respectively. Both observe one browser image load and show the account icon while no URL is available, loading is pending, or loading failed. A rendered image failure updates the shared result, so both surfaces return to the icon and remain eligible for retry; reports from a superseded picture attempt are ignored. Each Settings entry, or return from a Settings or quota-notice top-up page, retries a failed image once even when its URL is unchanged; pending and successful loads are reused, and success updates both surfaces. A changed picture URL starts a new load; account-state replacement, sign-out, and plugin unload discard the previous picture and its callbacks. The collapsed sidebar centers the avatar in a 36 × 36 px button. Before sign-in the sidebar launcher shows a compact More row instead, leading with the ellipsis glyph and aligning its content and inset hover fill with navigation rows. Expanded buttons use border-box sizing: the signed-in row is 44px high including its 6px padding, and the signed-out More row is 32px high. The signed-in launcher retains its 24px avatar and 8px label gap and owns a 2px inline margin on its root; this inset does not move the Settings shell's adjacent status indicator horizontally. The section registers through settings.section and uses the account Remote namespace. The stream survives carrier reconnects through the shared Remote supervisor. The page renders feature-owned English and Chinese copy and keeps API keys separate from account state. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index 6599e08a22..2ccbf3c141 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -30,6 +30,8 @@ kind: "package-reference" Desktop 与普通 Web 客户端都挂载侧边栏账号菜单、账号设置、模型引导中的登录步骤,并订阅账号状态。Desktop 主进程在系统浏览器中打开授权页面。普通 Web 客户端(以缺少 Desktop preload 桥接识别)以 `login_source` web 发起登录,并以自身 origin 作为回调 origin;它在点击登录时预先打开一个标签页,本次尝试获得授权 URL 后带上相同的 `theme` 参数导航该标签页,并在失败、过期或取消时关闭它;弹窗被拦截时仍可使用复制链接。内嵌 Platform 页面、Desktop 引导和原生设备信息读取器仅在 Desktop 中提供,因此 Web 中的 Platform 链接在新标签页打开。 +当前 Peer 可以观察账号时,插件提供 Client 服务 `accountSignIn`,其 `open()` 显示登录弹窗并发起一次浏览器登录;调用方应在点击处理中调用,以便普通 Web 客户端预先打开授权标签页。撤销账号访问权限时该服务随之撤回。 + 侧边栏和账号设置以正圆图片显示账号头像,直径分别为 24px 和 32px。两处共享一次浏览器图片加载,URL 缺失、加载中或加载失败时使用账号图标兜底。渲染图片失败时更新共享结果,两处一起恢复为图标,并保留重试机会;已被替换的图片加载尝试上报的失败会被忽略。每次进入设置,或从设置及余额不足提示打开的充值页面返回时,都会重试一次失败的图片,即使 URL 未变化;加载中和已成功的图片会复用,成功后两处一起展示。头像 URL 变化时开始新加载;账号状态替换、退出登录和插件卸载会丢弃旧头像及其回调。折叠侧边栏将头像居中放置在 36 × 36 px 的按钮内。登录前侧边栏入口改为紧凑的「更多」行,以三点图标开头,内容和内缩的悬停底色与导航行对齐。展开态按钮采用 border-box 尺寸:已登录行含 6px 内边距共高 44px,未登录的「更多」行高 32px。已登录入口保留 24px 头像及 8px 标签间距,并由自身根节点承担左右各 2px 外边距;该内缩不会水平移动设置外壳中相邻的状态指示器。 该页面通过 settings.section 注册,并使用 account Remote 命名空间。共享 Remote 管理器负责连接恢复后的流重连。页面使用功能自有的中英文文案,将 API Key 与账号状态分开。 diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index 45f13a1b97..e60be33484 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -41,6 +41,16 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { 'settings.account': AccountKey } } +declare module '@deepseek-ai/cordis' { + interface Context { + /** Cross-plugin entry to the account sign-in dialog; present while this Peer may watch the account. */ + accountSignIn: { + /** Show the sign-in dialog and start a browser attempt; call it from the user's click so the tab can preopen. */ + open(): void + } + } +} + /** Services required by account settings. */ export const inject = ['slots', 'locale', 'remote', 'remote.account', 'remote.session', 'theme', 'configForms', 'remoteAccess'] /** Register account UI in Desktop and plain Web clients. @param ctx - client plugin context. */ @@ -333,6 +343,12 @@ export function apply(ctx: Context): void { ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.launcher', () => ctx.slots.register({ name: 'settings.launcher', locale: 'settings.account', inject: () => operations, }, AccountMenu))) + ctx.remoteAccess.whenAccess('account/watch', () => { + const withdraw = ctx.reflect.provide('accountSignIn', { open: () => { void operations.start().catch((_shownInDialog: unknown) => { + // start() already published loginFailed, which the sign-in dialog renders for this attempt. + }) } }) + return () => { void withdraw() } + }) ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.section', () => { let unregister: (() => void) | undefined const update = () => { diff --git a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts index c969148d1b..1388173ede 100644 --- a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts +++ b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts @@ -62,6 +62,12 @@ it('withdraws every account surface and the account stream on revocation, and re return () => { registered.set(entry.name, registered.get(entry.name)! - 1) } }, }, + reflect: { + provide: (name: string) => { + registered.set(name, (registered.get(name) ?? 0) + 1) + return () => { registered.set(name, registered.get(name)! - 1) } + }, + }, remoteAccess: { whenAccess: (action: string, install: () => AccessEffect) => { guards.push({ action, install, installed: undefined }) @@ -88,22 +94,22 @@ it('withdraws every account surface and the account stream on revocation, and re }, } const surfaces = (): Record => Object.fromEntries( - ['settings.launcher', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section'].map(name => [name, registered.get(name)]), + ['settings.launcher', 'shell.quota-notice', 'settings.models.sign-in', 'settings.section', 'accountSignIn'].map(name => [name, registered.get(name)]), ) try { apply(ctx as never) expect(new Set(guards.map(guard => guard.action))).toEqual(new Set(['account/watch'])) grant(guards) await streams[0]!.accepted - expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) + expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1, accountSignIn: 1 }) revoke(guards) expect(streams[0]!.signal.aborted).toBe(true) - expect(surfaces()).toEqual({ 'settings.launcher': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0 }) + expect(surfaces()).toEqual({ 'settings.launcher': 0, 'shell.quota-notice': 0, 'settings.models.sign-in': 0, 'settings.section': 0, accountSignIn: 0 }) grant(guards) await streams[1]!.accepted - expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1 }) + expect(surfaces()).toEqual({ 'settings.launcher': 1, 'shell.quota-notice': 1, 'settings.models.sign-in': 1, 'settings.section': 1, accountSignIn: 1 }) } finally { revoke(guards) for (const dispose of lifetime.reverse()) dispose() @@ -138,6 +144,12 @@ it('drops reads a revoked grant started, and the next grant shows no account sec return () => { registered.set(entry.name, registered.get(entry.name)! - 1) } }, }, + reflect: { + provide: (name: string) => { + registered.set(name, (registered.get(name) ?? 0) + 1) + return () => { registered.set(name, registered.get(name)! - 1) } + }, + }, remoteAccess: { whenAccess: (action: string, install: () => AccessEffect) => { guards.push({ action, install, installed: undefined }) @@ -228,6 +240,12 @@ function revocationHarness(scripts: StreamScript[]) { return () => { registered.set(entry.name, registered.get(entry.name)! - 1) } }, }, + reflect: { + provide: (name: string) => { + registered.set(name, (registered.get(name) ?? 0) + 1) + return () => { registered.set(name, registered.get(name)! - 1) } + }, + }, remoteAccess: { whenAccess: (action: string, install: () => AccessEffect) => { guards.push({ action, install, installed: undefined }) diff --git a/packages/client/ui-settings-account/tests/apply.client.spec.ts b/packages/client/ui-settings-account/tests/apply.client.spec.ts index 300641d109..1d3aed2ca2 100644 --- a/packages/client/ui-settings-account/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-account/tests/apply.client.spec.ts @@ -85,6 +85,20 @@ withoutAccountAccess('opens no account stream and registers no account surface w expect(quotaNoticeEntry(c)).toBeUndefined() expect(c.ctx.slots.entries('settings.models.sign-in')).toHaveLength(0) expect(c.ctx.slots.entries('settings.section').some(entry => entry.options.id === 'account')).toBe(false) + expect(c.ctx.get('accountSignIn')).toBeUndefined() +}, 60_000) + +it('lets other plugins open sign-in from a click and withdraws the entry on unload', async ({ start, mock }) => { + const open = vi.spyOn(window, 'open').mockReturnValue(null) + const c = await start() + mock.remote.account.startSignIn.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.ctx.get('accountSignIn')!.open() + // The tab preopens synchronously inside the caller's click, before the Host responds. + expect(open).toHaveBeenCalledOnce() + expect(operations(c).hooks.account.getSnapshot()).toMatchObject({ loginVisible: true }) + await vi.waitFor(() => { expect(operations(c).hooks.account.getSnapshot()).toMatchObject({ loginFailed: true }) }) + await c.unload(SELF) + expect(c.ctx.get('accountSignIn')).toBeUndefined() }, 60_000) it('claims account balance notices from the frame-wide quota chain and declines generic quota', async ({ start }) => { diff --git a/packages/client/ui-settings-account/tests/initialization.client.spec.ts b/packages/client/ui-settings-account/tests/initialization.client.spec.ts index a17217f0d2..993ebe61b6 100644 --- a/packages/client/ui-settings-account/tests/initialization.client.spec.ts +++ b/packages/client/ui-settings-account/tests/initialization.client.spec.ts @@ -44,6 +44,7 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize return () => {} }, }, + reflect: { provide: () => () => {} }, remoteAccess: { whenAccess: (_action: string, install: () => (() => void) | Iterable<() => void> | undefined) => { const effect = install() diff --git a/packages/credentials/deepseek-account-platform/README.i18n.yaml b/packages/credentials/deepseek-account-platform/README.i18n.yaml index 9e6ffe9905..8cfb8473d6 100644 --- a/packages/credentials/deepseek-account-platform/README.i18n.yaml +++ b/packages/credentials/deepseek-account-platform/README.i18n.yaml @@ -15,8 +15,8 @@ en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account-platform/use-this-package: - en: 56bee240f50c293a - zh: 6c4c5de6088c9d79 + en: a502409a77cb0cca + zh: 0950a4ac2989a5ad /deepseek-ai-dsh-deepseek-account-platform/understand-the-implementation: en: 76d2da2dab100ac3 zh: 2c9404f27915daab diff --git a/packages/credentials/deepseek-account-platform/README.md b/packages/credentials/deepseek-account-platform/README.md index 104b597c9a..cffd00a02f 100644 --- a/packages/credentials/deepseek-account-platform/README.md +++ b/packages/credentials/deepseek-account-platform/README.md @@ -65,6 +65,8 @@ Host diagnostics use `console.error` with the `[deepseek-account]` prefix on sta inferenceOrigin defaults to `https://api.deepseek.com`. A private deployment patch may replace it with one exact HTTP(S) origin, including its port, for inference and file authentication through x-dsh-auth-token. Paths, URL credentials, queries and fragments are invalid configuration. Alternate origins require a grant issued by the configured platformOrigin; mock tokens remain excluded. Loopback grants cannot authenticate the official production API. Deployment addresses belong in private patches, not shipped configuration. +`serviceOrigins` lists further exact origins of DeepSeek services that receive the account token, and defaults to `https://harness.deepseek.com` for speech recognition. Each entry follows the `inferenceOrigin` validation. The official origins `https://api.deepseek.com` and `https://harness.deepseek.com` never receive a loopback-issued grant; any other origin requires a grant issued by the configured platformOrigin. Set `serviceOrigins: []` to release tokens only to `inferenceOrigin`. + At provider initialization, a valid stored grant whose issuer differs from platformOrigin is deleted locally before consumers read account state. Startup continues signed out without a remote logout request; API keys and device identity remain stored. Storage failures remain explicit, and account HTTP or response-validation failures do not delete a matching grant. diff --git a/packages/credentials/deepseek-account-platform/README.zh.md b/packages/credentials/deepseek-account-platform/README.zh.md index 7e9b181868..082e5a26c9 100644 --- a/packages/credentials/deepseek-account-platform/README.zh.md +++ b/packages/credentials/deepseek-account-platform/README.zh.md @@ -65,6 +65,8 @@ Host 诊断仅在请求、响应校验或登录失败时,通过 `console.error inferenceOrigin 默认为 `https://api.deepseek.com`。私有部署 patch 可将其替换为一个精确的 HTTP(S) 来源(含端口),让推理及文件请求通过 x-dsh-auth-token 认证。配置不得包含路径、URL 凭证、查询或片段。其他来源要求授权由配置的 platformOrigin 签发;仍拒绝 Mock token。本机授权不能认证官方生产 API。部署地址保存在私有 patch 中,不随默认配置发布。 +`serviceOrigins` 列出另外可以接收账号 token 的 DeepSeek 服务的精确来源,默认是用于语音识别的 `https://harness.deepseek.com`。每一项都按 `inferenceOrigin` 的规则校验。官方来源 `https://api.deepseek.com` 和 `https://harness.deepseek.com` 永远不会收到本机签发的授权;其他来源要求授权由配置的 platformOrigin 签发。设为 `serviceOrigins: []` 时只向 `inferenceOrigin` 发放 token。 + 提供者初始化时,若有效的已存授权 issuer 与 platformOrigin 不同,会在使用方读取账号状态前删除该本地授权,以未登录态继续启动,不发送远端退登请求;API Key 和设备标识保留。存储错误仍明确报错,账号 HTTP 或响应校验失败不会删除来源匹配的授权。 diff --git a/packages/credentials/deepseek-account-platform/src/index.ts b/packages/credentials/deepseek-account-platform/src/index.ts index 0319a553c3..ef38622639 100644 --- a/packages/credentials/deepseek-account-platform/src/index.ts +++ b/packages/credentials/deepseek-account-platform/src/index.ts @@ -17,6 +17,24 @@ import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformO const KEY = credentialKey('deepseek-account-platform', 'default') const DEVICE = credentialKey('deepseek-account-platform', 'device') const grant = z.object({ version: z.literal(1), token: z.string().min(1), issuer: z.url() }) +/** Production DeepSeek origins; they never receive a grant issued by a loopback development platform. */ +const OFFICIAL_TOKEN_ORIGINS: ReadonlySet = new Set(['https://api.deepseek.com', 'https://harness.deepseek.com']) +const LOOPBACK_HOSTS: ReadonlySet = new Set(['localhost', '127.0.0.1', '[::1]']) + +/** + * Validate one exact token destination. + * @param value - configured origin. + * @param field - configuration field named in the error. + * @returns the normalized origin. + */ +function tokenOrigin(value: string, field: string): string { + const origin = new URL(value) + if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password + || origin.pathname !== '/' || origin.search || origin.hash) { + throw new Error(`account: ${field} must be an HTTP(S) origin without credentials, path, query or fragment`) + } + return origin.origin +} const device = z.object({ id: z.uuid() }) /** Deployment-specific platform and request deadlines. */ @@ -29,6 +47,8 @@ export interface Config { embeddedPageDist?: string /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ inferenceOrigin?: string + /** Further exact HTTP(S) origins of DeepSeek services, such as speech recognition, allowed to receive account tokens. */ + serviceOrigins?: string[] /** Allow HTTP only on loopback for the development Mock. */ allowLoopbackHttp?: boolean /** Map authorization and completion pages to platformOrigin for private development proxies. */ @@ -54,6 +74,7 @@ export const Config = Schema.object({ desktopPlatform: Schema.union([Schema.const('darwin'), Schema.const('win32'), Schema.const(null)]).default(null), embeddedPageDist: Schema.string().default(''), inferenceOrigin: Schema.string().default('https://api.deepseek.com'), + serviceOrigins: Schema.array(Schema.string()).default(['https://harness.deepseek.com']), allowLoopbackHttp: Schema.boolean().default(false), rewriteBrowserOrigin: Schema.boolean().default(false), requestHeaders: Schema.dict(Schema.string().role('secret')).default({}), @@ -86,7 +107,8 @@ export class PlatformAccount extends DeepSeekAccount { static Config = Config private readonly origin: string private readonly embeddedPageDist: string - private readonly inferenceOrigin: string + /** Exact origins that receive account tokens: the inference origin followed by the service origins. */ + private readonly tokenOrigins: ReadonlySet private readonly rewriteBrowserOrigin: boolean private readonly platform: 'darwin' | 'win32' | null private readonly requestHeaders: Record @@ -115,12 +137,8 @@ export class PlatformAccount extends DeepSeekAccount { const resolved = Config(config) this.embeddedPageDist = resolved.embeddedPageDist this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp) - const inference = new URL(resolved.inferenceOrigin) - if (!['http:', 'https:'].includes(inference.protocol) || inference.username || inference.password - || inference.pathname !== '/' || inference.search || inference.hash) { - throw new Error('account: inferenceOrigin must be an HTTP(S) origin without credentials, path, query or fragment') - } - this.inferenceOrigin = inference.origin + this.tokenOrigins = new Set([tokenOrigin(resolved.inferenceOrigin, 'inferenceOrigin'), + ...resolved.serviceOrigins.map(origin => tokenOrigin(origin, 'serviceOrigins'))]) this.rewriteBrowserOrigin = resolved.rewriteBrowserOrigin this.platform = resolved.desktopPlatform this.requestHeaders = platformHeaders(resolved.requestHeaders) @@ -384,17 +402,17 @@ export class PlatformAccount extends DeepSeekAccount { override async resolveToken(url: string): Promise { if (this.closed || this.removing !== undefined) return undefined const destination = new URL(url) - if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined + if (!this.tokenOrigins.has(destination.origin) || destination.username || destination.password) return undefined const record = await this.ctx.credentials.readRecord(KEY) if (record === undefined) return undefined if (record.kind !== 'grant') throw new PlatformAuthError('storage') const result = grant.safeParse(record.payload) if (!result.success) throw new PlatformAuthError('storage') - // Development grants cannot authenticate production model or file requests. + // Development grants cannot authenticate production requests; other origins accept only this platform's grants. const issuer = new URL(result.data.issuer) if (result.data.token.startsWith('dsh_mock_')) return undefined - if (this.inferenceOrigin === 'https://api.deepseek.com') { - if (['localhost', '127.0.0.1', '[::1]'].includes(issuer.hostname)) return undefined + if (OFFICIAL_TOKEN_ORIGINS.has(destination.origin)) { + if (LOOPBACK_HOSTS.has(issuer.hostname)) return undefined } else if (issuer.origin !== this.origin) return undefined return result.data.token } diff --git a/packages/credentials/deepseek-account-platform/tests/account.spec.ts b/packages/credentials/deepseek-account-platform/tests/account.spec.ts index 590fb0b7be..61a01ea4ec 100644 --- a/packages/credentials/deepseek-account-platform/tests/account.spec.ts +++ b/packages/credentials/deepseek-account-platform/tests/account.spec.ts @@ -35,6 +35,7 @@ async function fixture( embeddedPageDist = '', desktopPlatform: 'darwin' | 'win32' | null = null, balanceTimeoutMs = 30_000, + serviceOrigins?: string[], ) { const home = await mkdtemp(join(tmpdir(), 'dsh-account-')) cleanups.push(() => rm(home, { recursive: true, force: true })) @@ -160,7 +161,7 @@ async function fixture( const provider = ctx.plugin(PlatformAccount, { platformOrigin: origin, inferenceOrigin, embeddedPageDist, desktopPlatform, allowLoopbackHttp: true, requestHeaders, accountRequestHeaders, - rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs, + rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs, ...serviceOrigins === undefined ? {} : { serviceOrigins }, }) await provider cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() }) @@ -306,6 +307,39 @@ it('allows real account credentials only on the exact official HTTPS origin', as } }) +it('also releases a production grant to the exact official speech service origin', async () => { + const f = await fixture() + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'test-account-token' }, + })) + expect(await f.account.resolveToken('https://harness.deepseek.com/api/v0/asr/transcribe')).toBe('test-account-token') + for (const url of ['http://harness.deepseek.com/api', 'https://harness.deepseek.com.evil.test', 'https://harness.deepseek.com:8443', + 'https://user@harness.deepseek.com', 'https://chat.deepseek.com/api']) { + expect(await f.account.resolveToken(url)).toBeUndefined() + } +}) + +it('sends service origins only grants allowed for them and supports removing the default', async () => { + const f = await fixture(undefined, {}, false, {}, 'https://api.deepseek.com', undefined, '', null, 30_000, + ['https://harness.deepseek.com', 'https://speech.private.example']) + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: f.origin, token: 'loopback-token' }, + })) + expect(await f.account.resolveToken('https://harness.deepseek.com/api')).toBeUndefined() + expect(await f.account.resolveToken('https://api.deepseek.com/v1')).toBeUndefined() + expect(await f.account.resolveToken('https://speech.private.example/asr')).toBe('loopback-token') + await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'production-token' }, + })) + expect(await f.account.resolveToken('https://speech.private.example/asr')).toBeUndefined() + const none = await fixture(undefined, {}, false, {}, 'https://api.deepseek.com', undefined, '', null, 30_000, []) + await none.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'production-token' }, + })) + expect(await none.account.resolveToken('https://harness.deepseek.com/api')).toBeUndefined() + expect(await none.account.resolveToken('https://api.deepseek.com/v1')).toBe('production-token') +}) + it('restricts platform destinations to the configured origin and route', () => { expect(() => platformOrigin('http://localhost:8081', false)).toThrow() expect(platformOrigin('http://localhost:8081', true)).toBe('http://localhost:8081') @@ -1154,6 +1188,8 @@ it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as con it.each(['ftp://api.example', 'https://user:password@api.example', 'https://api.example/path', 'https://api.example/?query=1', 'https://api.example/#fragment'])('rejects invalid inference origin %s', async (inferenceOrigin) => { expect(() => new PlatformAccount(new Context(), { inferenceOrigin })).toThrow('account: inferenceOrigin') + expect(() => new PlatformAccount(new Context(), { serviceOrigins: ['https://harness.deepseek.com', inferenceOrigin] })) + .toThrow('account: serviceOrigins') }) it('rejects authorization begun without a local account attempt', async () => { diff --git a/packages/credentials/deepseek-account/README.i18n.yaml b/packages/credentials/deepseek-account/README.i18n.yaml index 7ac8b46fac..503cc26bd1 100644 --- a/packages/credentials/deepseek-account/README.i18n.yaml +++ b/packages/credentials/deepseek-account/README.i18n.yaml @@ -3,14 +3,14 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/credentials/deepseek-account/README.md /: - en: 30a2d1a634d60f4a - zh: 9fbf972d342f8ba2 + en: 86719c0f727b11c1 + zh: 55ccd4a8467cecfc /deepseek-ai-dsh-deepseek-account: en: 4333ad7e5c2d257f zh: 1f1acbb68131d328 /deepseek-ai-dsh-deepseek-account/summary: - en: 26e77d24d904dd48 - zh: abc2d141826091f9 + en: 3258c8314650221a + zh: 642234db90b47134 /deepseek-ai-dsh-deepseek-account/table-of-contents: en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 diff --git a/packages/credentials/deepseek-account/README.md b/packages/credentials/deepseek-account/README.md index 16cdf91af5..509803cca1 100644 --- a/packages/credentials/deepseek-account/README.md +++ b/packages/credentials/deepseek-account/README.md @@ -1,5 +1,5 @@ --- -description: "Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host model consumers resolve account credentials only for the provider-configured inference origin." +description: "Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host consumers resolve account credentials only for the origins the provider allows: its inference origin and its service origins." kind: "package-reference" --- @@ -19,7 +19,7 @@ getUnnotifiedBonuses returns the granted bonuses Platform has not yet recorded a ## Summary -Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host model consumers resolve account credentials only for the provider-configured inference origin. +Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host consumers resolve account credentials only for the origins the provider allows: its inference origin and its service origins. `SignInErrorCode` distinguishes `no-response` (fetch returned no Response) from HTTP and response-validation failures so clients can offer network troubleshooting. diff --git a/packages/credentials/deepseek-account/README.zh.md b/packages/credentials/deepseek-account/README.zh.md index 2ef0d01d89..5e16c60624 100644 --- a/packages/credentials/deepseek-account/README.zh.md +++ b/packages/credentials/deepseek-account/README.zh.md @@ -1,5 +1,5 @@ --- -description: "账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 模型使用方仅能为提供者配置的推理来源解析账号凭证。" +description: "账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 使用方仅能为提供者允许的来源解析账号凭证:推理来源和服务来源。" kind: "package-reference" --- @@ -19,7 +19,7 @@ getUnnotifiedBonuses 返回平台尚未记录为已展示的赠金及其所属 ## 概述 -账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 模型使用方仅能为提供者配置的推理来源解析账号凭证。 +账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 使用方仅能为提供者允许的来源解析账号凭证:推理来源和服务来源。 `SignInErrorCode` 将 `no-response`(fetch 未返回 Response)与 HTTP 和响应校验失败区分开,使客户端可以提示检查网络。 diff --git a/packages/credentials/deepseek-account/src/index.ts b/packages/credentials/deepseek-account/src/index.ts index 20b0a8b81d..a8e8368995 100644 --- a/packages/credentials/deepseek-account/src/index.ts +++ b/packages/credentials/deepseek-account/src/index.ts @@ -93,7 +93,7 @@ export abstract class DeepSeekAccount extends Service { */ abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable /** - * Resolve a credential only for the inference origin allowed by the provider. + * Resolve a credential only for an origin the provider allows, such as its inference and service origins. * @param url - actual request destination or API base URL. * @returns stored token, or undefined for other origins or a signed-out account. */ diff --git a/packages/experimental/api-speech-to-text/README.i18n.yaml b/packages/experimental/api-speech-to-text/README.i18n.yaml index 1db635bcd9..5cd1974971 100644 --- a/packages/experimental/api-speech-to-text/README.i18n.yaml +++ b/packages/experimental/api-speech-to-text/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 364c80ee00a374ff /deepseek-ai-dsh-experimental-api-speech-to-text/use-this-package: - en: 23efd2789fe70cd9 - zh: 3edd559ee5975742 + en: e259a2bbb6b1086e + zh: e91346ace8f6a239 /deepseek-ai-dsh-experimental-api-speech-to-text/understand-the-implementation: en: cffe2ab0b7cd0b8b zh: 5fd4f71cb083de80 diff --git a/packages/experimental/api-speech-to-text/README.md b/packages/experimental/api-speech-to-text/README.md index 226df827ad..67cc923b3e 100644 --- a/packages/experimental/api-speech-to-text/README.md +++ b/packages/experimental/api-speech-to-text/README.md @@ -27,6 +27,8 @@ The `speech` Remote connects browser recordings to `ctx.speechToText`. It expose Compose with the speech Service Definition and Typert. `maxAudioBytes` and `maxDurationSeconds` limit accepted recordings. The browser UI mounts this package’s generated `/remote` contribution when enabled. +A provider failure becomes `speech/transcription-failed`; when the provider throws `SpeechTranscriptionError`, the details carry its `SpeechFailureCode` as `code`, and `reason` keeps the Host diagnostic. An optional `locale` carries the Client's UI language; a value that is not a language tag fails as `gateway/bad-request` before recognition. + `prepare(providerId, { downloadSource })` forwards one advertised source to the provider; omission keeps its configured policy. The catalog carries `downloadSources` for the picker. The provider rejects unavailable choices and changes to an active task’s source. ----- diff --git a/packages/experimental/api-speech-to-text/README.zh.md b/packages/experimental/api-speech-to-text/README.zh.md index 27927b922f..fdb709aeb6 100644 --- a/packages/experimental/api-speech-to-text/README.zh.md +++ b/packages/experimental/api-speech-to-text/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" 与语音服务定义和 Typert 组合。`maxAudioBytes` 与 `maxDurationSeconds` 限制接收的录音。浏览器 UI 启用时挂载本包生成的 `/remote` 贡献。 +Provider 失败时返回 `speech/transcription-failed`;Provider 抛出 `SpeechTranscriptionError` 时,详情的 `code` 携带其 `SpeechFailureCode`,`reason` 保留 Host 诊断信息。可选的 `locale` 携带 Client 的界面语言;不是语言标签的值在识别前以 `gateway/bad-request` 失败。 + `prepare(providerId, { downloadSource })` 将公布的一个下载源转发给提供方,省略时保留其配置策略。目录通过 `downloadSources` 提供选择器选项。提供方拒绝不可用的源,以及对进行中任务的源变更。 ----- diff --git a/packages/experimental/api-speech-to-text/src/index.ts b/packages/experimental/api-speech-to-text/src/index.ts index 4d19d7c5af..3cae3a7697 100644 --- a/packages/experimental/api-speech-to-text/src/index.ts +++ b/packages/experimental/api-speech-to-text/src/index.ts @@ -2,13 +2,16 @@ import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' -import type {} from '@deepseek-ai/dsh-experimental-speech-to-text' +import { SpeechTranscriptionError } from '@deepseek-ai/dsh-experimental-speech-to-text' import type { SpeechPreparationOptions, SpeechProviderId, SpeechSelectionPatch, Transcript } from '@deepseek-ai/dsh-experimental-speech-to-text/types' import type { SpeechCatalog, TranscriptionRequest } from './types.ts' import { validateWave } from '@deepseek-ai/dsh-experimental-speech-to-text/wave' export type * from './types.ts' +/** Language tag accepted from the Client; anything else could not be forwarded safely as a request header. */ +const LOCALE_TAG = /^[A-Za-z]{2,3}(?:[-_][A-Za-z0-9]{1,8}){0,3}$/ + declare module '@deepseek-ai/cordis' { interface Context { /** Experimental speech Remote controller. */ @@ -88,6 +91,9 @@ export default class SpeechController extends TypertRemoteService { @Remote async transcribe(request: TranscriptionRequest, signal: AbortSignal): Promise { signal.throwIfAborted() + if (request.locale !== undefined && !LOCALE_TAG.test(request.locale)) { + throw new RemoteError('gateway/bad-request', 'The client locale is not a language tag', {}) + } const encoded = request.audioBase64 if (encoded.length > Math.ceil(this.config.maxAudioBytes / 3) * 4) { throw new RemoteError('speech/invalid-audio', 'Audio is invalid or exceeds the configured byte limit', { reason: 'encoding-or-size' }) @@ -100,12 +106,14 @@ export default class SpeechController extends TypertRemoteService { const spec = this.ctx.speechToText.resolve({ audio, ...request.providerId === undefined ? {} : { providerId: request.providerId }, ...request.language === undefined ? {} : { language: request.language }, + ...request.locale === undefined ? {} : { locale: request.locale }, }) return await this.ctx.speechToText.transcribe(spec, signal) } catch (error) { signal.throwIfAborted() const reason = error instanceof Error ? error.message : String(error) - throw new RemoteError('speech/transcription-failed', reason, { reason }) + throw new RemoteError('speech/transcription-failed', reason, + error instanceof SpeechTranscriptionError ? { reason, code: error.code } : { reason }) } } } diff --git a/packages/experimental/api-speech-to-text/src/types.ts b/packages/experimental/api-speech-to-text/src/types.ts index d7436e7a62..a0311bdc8a 100644 --- a/packages/experimental/api-speech-to-text/src/types.ts +++ b/packages/experimental/api-speech-to-text/src/types.ts @@ -1,13 +1,13 @@ /** JSON-safe inputs and results of the experimental speech Remote namespace. */ -import type { SpeechProviderId, SpeechSnapshot } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import type { SpeechFailureCode, SpeechProviderId, SpeechSnapshot } from '@deepseek-ai/dsh-experimental-speech-to-text/types' import type {} from '@deepseek-ai/dsh-typert-protocol' declare module '@deepseek-ai/dsh-typert-protocol' { interface RemoteErrorDetailsMap { /** Audio encoding or intake limits prevented transcription. */ 'speech/invalid-audio': { readonly reason: string } - /** The selected provider rejected transcription. */ - 'speech/transcription-failed': { readonly reason: string } + /** The selected provider rejected transcription; `code` is present when the provider classified the failure. */ + 'speech/transcription-failed': { readonly reason: string; readonly code?: SpeechFailureCode } } } @@ -16,6 +16,8 @@ export interface TranscriptionRequest { readonly audioBase64: string readonly providerId?: SpeechProviderId readonly language?: string + /** Active UI language as a BCP 47 tag such as `zh` or `pt-BR`; cloud providers forward it to the service. */ + readonly locale?: string } /** Current provider choices and audio intake limits. */ diff --git a/packages/experimental/api-speech-to-text/tests/controller.spec.ts b/packages/experimental/api-speech-to-text/tests/controller.spec.ts index caa2145ea2..f7a93cf2eb 100644 --- a/packages/experimental/api-speech-to-text/tests/controller.spec.ts +++ b/packages/experimental/api-speech-to-text/tests/controller.spec.ts @@ -1,8 +1,8 @@ /** Authenticated speech domain methods validate audio before selecting a recognizer. */ import { Context } from '@deepseek-ai/cordis' import { afterEach, expect, it, vi } from 'vitest' -import SpeechToText from '@deepseek-ai/dsh-experimental-speech-to-text' -import type { SpeechProviderId } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import SpeechToText, { SpeechTranscriptionError } from '@deepseek-ai/dsh-experimental-speech-to-text' +import type { SpeechInput, SpeechProviderId } from '@deepseek-ai/dsh-experimental-speech-to-text/types' import SpeechController from '../src/index.ts' const roots: Context[] = [] @@ -11,7 +11,7 @@ const id = 'sensevoice-local' as SpeechProviderId function fixture(maxAudioBytes = 32044, maxDurationSeconds = 1) { const ctx = new Context(); roots.push(ctx) const speech = new SpeechToText(ctx, SpeechToText.Config({ defaultProvider: id, language: 'auto' })) - const recognize = vi.fn(async () => ({ text: '你好', audioSeconds: 1, inferenceSeconds: 0.1 })) + const recognize = vi.fn(async (_input: SpeechInput, _signal: AbortSignal) => ({ text: '你好', audioSeconds: 1, inferenceSeconds: 0.1 })) speech.register({ info: { id, name: 'test', location: 'host-local', languages: ['auto', 'zh', 'en', 'ja'] }, transcribe: recognize }) return { api: new SpeechController(ctx, { maxAudioBytes, maxDurationSeconds }), recognize } } @@ -65,6 +65,18 @@ it('rejects oversized, noncanonical, malformed and overlong audio without infere expect(recognize).not.toHaveBeenCalled() }) +it('forwards a well-formed client locale and rejects malformed tags before recognition', async () => { + const { api, recognize } = fixture() + await api.transcribe({ audioBase64: recording(), locale: 'pt-BR' }, new AbortController().signal) + const [input] = recognize.mock.lastCall! + expect([input.language, input.locale]).toEqual(['auto', 'pt-BR']) + for (const locale of ['zh\r\nx-injected: 1', '', 'chinese-simplified-script-x-y']) { + await expect(api.transcribe({ audioBase64: recording(), locale }, new AbortController().signal)) + .rejects.toMatchObject({ code: 'gateway/bad-request' }) + } + expect(recognize).toHaveBeenCalledOnce() +}) + it('preserves cancellation and reports recognizer failures', async () => { const { api, recognize } = fixture() await expect(api.configure({ language: 'zh' })).rejects.toThrow('settings service') @@ -73,4 +85,8 @@ it('preserves cancellation and reports recognizer failures', async () => { await expect(api.transcribe({ audioBase64: recording() }, new AbortController().signal)).rejects.toMatchObject({ code: 'speech/transcription-failed', message: 'offline' }) recognize.mockRejectedValueOnce('failed') await expect(api.transcribe({ audioBase64: recording() }, new AbortController().signal)).rejects.toMatchObject({ message: 'failed' }) + recognize.mockRejectedValueOnce(new SpeechTranscriptionError('rate-limited', 'HTTP 429')) + await expect(api.transcribe({ audioBase64: recording() }, new AbortController().signal)).rejects.toMatchObject({ + code: 'speech/transcription-failed', message: 'HTTP 429', details: { reason: 'HTTP 429', code: 'rate-limited' }, + }) }) diff --git a/packages/experimental/client-ui-voice-input/README.i18n.yaml b/packages/experimental/client-ui-voice-input/README.i18n.yaml index 6aa37a6ef0..b5a214fd94 100644 --- a/packages/experimental/client-ui-voice-input/README.i18n.yaml +++ b/packages/experimental/client-ui-voice-input/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 364c80ee00a374ff /deepseek-ai-dsh-experimental-client-ui-voice-input/use-this-package: - en: b7a99b656839e8a0 - zh: 5c6e2635eb20fc11 + en: 48572dd712956323 + zh: c667080b2e9a36bd /deepseek-ai-dsh-experimental-client-ui-voice-input/understand-the-implementation: en: 8fe96eeef9afe7d7 zh: 11936f647ded39eb diff --git a/packages/experimental/client-ui-voice-input/README.md b/packages/experimental/client-ui-voice-input/README.md index 2aa4fdd707..ecca044990 100644 --- a/packages/experimental/client-ui-voice-input/README.md +++ b/packages/experimental/client-ui-voice-input/README.md @@ -27,6 +27,8 @@ This optional browser plugin adds an outline microphone icon between the model s Enable the [voice input bundle](../voice-input-bundle/README.md) from Plugins. After cache inspection, missing models trigger a setup prompt with Go to setup and Later actions. Go to setup opens bundle details; Download and prepare starts installation there. Intact cached models need no prompt or repeated installation. Before recognition is ready, guidance appears only on click, with no microphone tooltip. Clicking the microphone opens the same guidance dialog; its action opens the voice bundle details without recording or downloading. Cache inspection, preparation in progress, failures and disconnected services instead offer navigation to status, progress or error details. The dialog moves focus to its navigation action and keeps Tab traversal inside it; Later or Escape restores the previous focus without changing or submitting the draft. Before preparation, local providers can show their estimated disk, memory and setup-time requirements. The preparation summary starts collapsed; expand it to inspect completed, current and pending steps. Once ready, click the microphone, allow access and click Stop to transcribe. Cancel or Escape discards capture. Recognition feedback stays inside the toolbar. Provider and language preferences are saved from bundle details through the Settings service. Browser microphone access requires HTTPS or loopback and operating-system permission. +With a signed-in DeepSeek account, automatic selection uses cloud recognition without a prompt; the microphone tooltip and the transcription status name cloud recognition. When automatic selection falls back to an unprepared local model and signing in would enable cloud recognition, the prompt makes Sign in to DeepSeek the primary action beside Download local model and Later. A signed-out user who chose cloud recognition explicitly is asked to sign in or use local recognition. Sign-in actions call the optional `accountSignIn` service and appear only while it is present; otherwise the dialog points to the Account page in Settings. Classified failures show localized messages in the toolbar, with Sign in to DeepSeek after an expired account and Use local recognition after a cloud outage or an exhausted daily allowance. Bundle details offer Automatic and name the provider in use. An explicit choice shows only that provider's card; Automatic lists cloud providers before local ones. The language menu lists every language some provider recognizes; when the provider in use does not list the saved language, a note says it detects the language automatically. Each transcription sends the active UI language as `locale`. + Use the native **Input device** selector in bundle details to follow the system default or select a browser microphone. System default shows the current device name when available. While bundle details are active, the selected input's live level remains visible at the right of the field; selecting another input restarts the preview for that device. Hiding or leaving the page, or disabling the plugin, releases the preview, including late permission grants. The browser remembers the device for subsequent recordings independently of Host recognition settings. Device insertion and removal refresh the options without interrupting an available selected input. A disconnected selection retains its name and position as a disabled option with an Unavailable label. Reconnecting while the page is active restores its preview; choosing another input removes the unavailable option. Interrupted recordings require an explicit restart. Permission denial keeps other choices accessible; an explicitly selected device never silently falls back to another input. Before downloading or retrying, **Model download source** offers Automatic and the origins advertised by the Host. SenseVoice normally offers Hugging Face and HF-Mirror; a fixed private deployment exposes only its configured origin. Manual selection uses only that source, while Automatic preserves the provider’s comparison and fallback policy. The choice is retained for retries in the current card, without changing deployment configuration or recognition preferences. Source controls are unavailable during preparation and hidden when resources are ready. diff --git a/packages/experimental/client-ui-voice-input/README.zh.md b/packages/experimental/client-ui-voice-input/README.zh.md index 3dadc0d92d..2a11a1669a 100644 --- a/packages/experimental/client-ui-voice-input/README.zh.md +++ b/packages/experimental/client-ui-voice-input/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" 在插件管理页启用[语音输入 Bundle](../voice-input-bundle/README.zh.md)。缓存检查后,缺少模型时弹出安装引导,可选择“前往安装”或“稍后”。“前往安装”打开 Bundle 详情,再点击“下载并准备”才开始安装。缓存完整时不弹引导,也无需重复安装。识别未就绪时不显示麦克风悬停提示,点击后才打开同一个引导弹窗;点击引导按钮进入语音 Bundle 详情,不会录音或下载。缓存检查、正在准备、准备失败或服务断连时,弹窗改为引导查看状态、进度或错误详情。弹窗将焦点移到导航按钮,并将 Tab 切换约束在弹窗内;选择“稍后”或按 Escape 关闭时恢复此前焦点,不改变或提交草稿。准备前,本地 Provider 可展示磁盘、内存与安装时间的估算。准备摘要默认折叠;展开后可查看已完成、当前和未开始的步骤。就绪后点击麦克风,允许访问,再点击停止以转写。取消或 Escape 丢弃录音。识别反馈留在工具栏内部。Provider 和语言偏好在 Bundle 详情中通过 Settings 服务保存。浏览器麦克风访问需要 HTTPS 或环回地址,以及操作系统权限。 +已登录 DeepSeek 账号时,自动选择直接使用云端识别,不弹引导;麦克风悬停提示和转写状态会标明云端识别。自动选择回退到尚未下载的本地模型、而登录即可使用云端识别时,引导弹窗以“登录 DeepSeek”为主按钮,并提供“下载本地模型”和“稍后”。手动选择云端识别但未登录时,弹窗提示登录或改用本地识别。登录按钮调用可选的 `accountSignIn` 服务,只在该服务存在时显示;否则弹窗提示在设置的账号页登录。可分类的失败在工具栏内显示本地化提示:账号失效时提供“登录 DeepSeek”,云端不可用或当日额度用完时提供“改用本地识别”。Bundle 详情提供“自动”选项并显示当前使用的服务。手动选择某个服务时只显示该服务的卡片;选择“自动”时,云端服务的卡片排在本地服务之前。识别语言菜单列出任一服务支持的全部语言;当前服务不支持已保存的语言时,提示将自动识别语言。每次转写都把当前界面语言作为 `locale` 发送。 + 在 Bundle 详情中使用原生**输入设备**选择器,跟随系统默认设备或选择浏览器可用的麦克风。系统默认在名称可用时显示当前设备名。Bundle 详情处于活动状态时,已选输入的实时电平持续显示在字段右侧;切换设备会为该设备重新启动预览。隐藏或离开页面、禁用插件时会释放预览,包括随后才批准的麦克风授权。浏览器会记住设备选择并用于后续录音,与 Host 的识别设置分别保存。插入和拔出设备会刷新选项,不打断仍然可用的已选输入。已选设备断开后会作为禁用选项保留名称和位置,并显示“不可用”。页面处于活动状态时,重新连接会恢复预览;改选其他输入后移除不可用选项。录音中断后需要手动重新开始。权限被拒绝时仍可选择其他设备;明确指定的设备不会静默回退到其他输入。 下载或重试前,**模型下载源**提供自动选择及 Host 公布的源。SenseVoice 默认提供 Hugging Face 和 HF-Mirror;固定私有部署仅显示配置的源。手动选择只使用指定源,自动选择沿用提供方的比较与回退策略。当前卡片中的重试会保留选择,不修改部署配置或识别偏好。准备期间不能改源,资源就绪后隐藏源选择器。 diff --git a/packages/experimental/client-ui-voice-input/package.json b/packages/experimental/client-ui-voice-input/package.json index 20b4649e56..700ee08b2d 100644 --- a/packages/experimental/client-ui-voice-input/package.json +++ b/packages/experimental/client-ui-voice-input/package.json @@ -57,7 +57,8 @@ "@testing-library/react": "^16.3.3", "@deepseek-ai/dsh-api-gateway": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", - "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*" + "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", + "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*" }, "dsh": { "client": { diff --git a/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx b/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx index f279d2bc99..c3c1a95a21 100644 --- a/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx +++ b/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx @@ -4,18 +4,24 @@ import { Button, DisclosureRow, IconChevronDownOutlineRegular, StateDot, type St import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { SpeechPreparationState, SpeechProviderId, SpeechProviderView, SpeechSelectionPatch } from '@deepseek-ai/dsh-experimental-speech-to-text/types' import type { VoiceInputInjected } from './VoiceInput.tsx' +import { offeredLanguages, providerLabel, selectedProvider } from './guidance.ts' import { MicrophonePicker } from './MicrophonePicker.tsx' import { NS } from './locales.ts' import css from './VoiceInput.module.css' /** One recognizer's resource readiness and explicit preparation controls. */ export type PreparationCardProps = Pick, 'prepare' | 'cancelPreparation'> - & PropsLocale & { readonly provider: SpeechProviderView; readonly connected: boolean } + & PropsLocale & { + readonly provider: SpeechProviderView + readonly connected: boolean + /** Open account sign-in; absent while the account UI offers no entry. */ + readonly signIn?: (() => void) | undefined + } function preparationTone(state: SpeechPreparationState): StateDotState { if (state.phase === 'ready' || state.phase === 'standby') return 'done' if (state.phase === 'failed') return 'error' - if (state.phase === 'unprepared' || state.phase === 'cancelled') return 'idle' + if (state.phase === 'unprepared' || state.phase === 'cancelled' || state.phase === 'unavailable') return 'idle' return 'ongoing' } @@ -42,7 +48,7 @@ function PreparationFailure({ state, t }: { state: Extract - {provider.name} + {providerLabel(provider, t)} {state.phase === 'unprepared' && provider.location === 'host-local' && provider.setupEstimate &&

{t('setup.local')}

@@ -119,6 +126,8 @@ export function PreparationCard({ provider, connected, prepare, cancelPreparatio {t(selectedSource === '' ? 'sourceAutoHelp' : 'sourceManualHelp')}
}
+ {state.phase === 'unavailable' && signIn !== undefined + && } {canPrepare && } {preparing && state.phase !== 'waking' && - { setSetupOpen(false) }} - onOpenDetails={navigable ? () => { setSetupOpen(false); openSettings() } : undefined} t={t} /> + onOpenDetails={navigable ? () => { setSetupOpen(false); openSettings() } : undefined} + onSignIn={signInPresent ? requestSignIn : undefined} onUseLocal={local === undefined ? undefined : () => { useLocal(local) }} t={t} /> return
} + {phase === 'feedback' && action !== undefined && } {phase === 'feedback' && (pending ? - {onOpenDetails !== undefined && + : } + {details && } + {signIn && } }> -

{t(needsInstallation ? 'setupPrompt.body' : 'setupPrompt.unavailableBody')}

+

{t(BODY[kind])}

+ {offersSignIn && !signIn &&

{t('signInFromSettings')}

} } diff --git a/packages/experimental/client-ui-voice-input/src/client/VoiceSetupPrompt.tsx b/packages/experimental/client-ui-voice-input/src/client/VoiceSetupPrompt.tsx index afce24f6ce..54fb7335d5 100644 --- a/packages/experimental/client-ui-voice-input/src/client/VoiceSetupPrompt.tsx +++ b/packages/experimental/client-ui-voice-input/src/client/VoiceSetupPrompt.tsx @@ -1,27 +1,31 @@ -/** Activation guidance after the Host inspects local recognition resources. */ +/** Activation guidance after the Host inspects recognition readiness. */ import { useEffect } from 'react' import { VoiceSetupDialog } from './VoiceSetupDialog.tsx' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' import type { VoiceInputInjected } from './VoiceInput.tsx' +import { voiceGuidance } from './guidance.ts' import type { NS } from './locales.ts' /** Registration shares for the bundle's activation guidance. */ export type VoiceSetupPromptProps = PropsRuntime<'plugins.bundle.activation'> & PropsLocale - & Pick, 'useSpeechReadiness'> + & Pick, 'useSpeechReadiness' | 'useAccountSignIn' | 'signIn'> /** - * Offer navigation to installation without starting a download. - * @param props - activation navigation and the shared Host readiness observer. - * @returns the shared modal only when the selected local provider needs preparation. + * Offer sign-in or navigation to installation without starting a download. + * @param props - activation navigation, the shared Host readiness observer and the optional sign-in entry. + * @returns the shared modal only when the selected provider needs sign-in or local preparation. */ -export function VoiceSetupPrompt({ useSpeechReadiness, onDismiss, onOpenDetails, t }: VoiceSetupPromptProps) { +export function VoiceSetupPrompt({ useSpeechReadiness, useAccountSignIn, signIn, onDismiss, onOpenDetails, t }: VoiceSetupPromptProps) { const readiness = useSpeechReadiness(value => value) + const signInPresent = useAccountSignIn(present => present) const provider = readiness.catalog?.providers.find(item => item.id === readiness.catalog?.selection.providerId) const phase = readiness.connected ? provider?.preparation.phase : undefined - const needsSetup = phase === 'unprepared' && provider?.location === 'host-local' + const guidance = voiceGuidance(readiness.catalog, readiness.connected) + const prompt = guidance === 'unavailable' ? null : guidance useEffect(() => { - if (phase !== undefined && phase !== 'checking' && !needsSetup) onDismiss() - }, [phase, needsSetup, onDismiss]) - return + if (phase !== undefined && phase !== 'checking' && prompt === null) onDismiss() + }, [phase, prompt, onDismiss]) + return { onDismiss(); signIn() } : undefined} t={t} /> } diff --git a/packages/experimental/client-ui-voice-input/src/client/guidance.ts b/packages/experimental/client-ui-voice-input/src/client/guidance.ts new file mode 100644 index 0000000000..eaa61ff4b8 --- /dev/null +++ b/packages/experimental/client-ui-voice-input/src/client/guidance.ts @@ -0,0 +1,81 @@ +/** Recording guidance derived from one complete Host readiness snapshot; pure, shared by every voice surface. */ +import type { SpeechCatalog } from '@deepseek-ai/dsh-experimental-api-speech-to-text/types' +import type { SpeechProviderView } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' + +/** + * What a click on the microphone shows instead of recording. + * `install`: download the selected local model; `install-or-sign-in`: automatic selection fell back to an unprepared local + * model while signing in would enable cloud recognition; `sign-in`: the selected cloud provider needs a DeepSeek account; + * `unavailable`: readiness is unknown, progressing or failed. + */ +export type VoiceGuidance = 'install' | 'install-or-sign-in' | 'sign-in' | 'unavailable' + +/** + * Find the provider the saved selection resolves to. + * @param catalog - latest Host catalog. + * @returns the provider a recording started now would use. + */ +export function selectedProvider(catalog: SpeechCatalog | null): SpeechProviderView | undefined { + return catalog?.providers.find(provider => provider.id === catalog.selection.providerId) +} + +/** + * Find the provider that “use local recognition” selects. + * @param catalog - latest Host catalog. + * @returns the first Host-local provider. + */ +export function localProvider(catalog: SpeechCatalog | null): SpeechProviderView | undefined { + return catalog?.providers.find(provider => provider.location === 'host-local') +} + +/** + * Decide whether the microphone records on click. + * @param provider - one provider view. + * @returns whether a recording can start without preparation. + */ +export function canRecord(provider: SpeechProviderView | undefined): boolean { + const phase = provider?.preparation.phase + return phase === 'ready' || phase === 'standby' || phase === 'waking' +} + +/** `sign-in-required` is the only reason a provider is `unavailable`. */ +const needsSignIn = (provider: SpeechProviderView): boolean => provider.preparation.phase === 'unavailable' + +/** + * Choose the guidance a microphone click shows instead of recording. + * @param catalog - latest Host catalog. + * @param connected - whether the readiness stream is live. + * @returns guidance for a microphone click, or null when recording can start. + */ +export function voiceGuidance(catalog: SpeechCatalog | null, connected: boolean): VoiceGuidance | null { + const provider = selectedProvider(catalog) + if (!connected || catalog === null || provider === undefined) return 'unavailable' + if (canRecord(provider)) return null + if (provider.location === 'cloud' && needsSignIn(provider)) return 'sign-in' + if (provider.location !== 'host-local' || provider.preparation.phase !== 'unprepared') return 'unavailable' + const signInWouldHelp = catalog.selection.mode === 'auto' && catalog.providers.some(row => row.location === 'cloud' && needsSignIn(row)) + return signInWouldHelp ? 'install-or-sign-in' : 'install' +} + +/** + * Name a provider together with where it processes audio. + * @param provider - one provider view. + * @param t - voice-input translator. + * @returns the localized option label. + */ +export function providerLabel(provider: SpeechProviderView, t: PropsLocale['t']): string { + return t(provider.location === 'cloud' ? 'providerCloud' : 'providerLocal', { name: provider.name }) +} + +/** + * List every language some provider recognizes, so the preference survives switching providers. + * @param catalog - latest Host catalog. + * @param order - preferred menu order; codes outside it follow in provider order. + * @returns distinct language codes in menu order. + */ +export function offeredLanguages(catalog: SpeechCatalog | null, order: readonly string[]): string[] { + const listed = new Set(catalog?.providers.flatMap(provider => provider.languages)) + return [...order.filter(code => listed.has(code)), ...[...listed].filter(code => !order.includes(code))] +} diff --git a/packages/experimental/client-ui-voice-input/src/client/locales.ts b/packages/experimental/client-ui-voice-input/src/client/locales.ts index 8460775175..d5e2add532 100644 --- a/packages/experimental/client-ui-voice-input/src/client/locales.ts +++ b/packages/experimental/client-ui-voice-input/src/client/locales.ts @@ -102,6 +102,33 @@ export const zh = { unavailable: '当前浏览器不支持录音,请使用支持麦克风的浏览器。', permission: '麦克风权限未开启,请在浏览器和系统设置中允许访问。', tooLarge: '录音超过服务限制,请缩短录音后重试。', + 'dictateCloud': '听写 · 云端识别', + 'transcribingCloud': '云端识别中…', + 'providerAuto': '自动(推荐)', + 'providerCloud': '{name} 云端识别', + 'providerLocal': '{name} 本地识别', + 'selection.current': '当前使用:{name}', + 'selection.signedIn': '已登录 DeepSeek', + 'selection.signedOut': '未登录 DeepSeek', + 'selection.autoHelp': '自动:已登录 DeepSeek 时使用云端识别,否则使用本地识别', + 'languageFallback.host-local': '本地识别不支持{language},将自动识别', + 'languageFallback.cloud': '云端识别不支持{language},将自动识别', + 'unavailable.sign-in-required': '登录 DeepSeek 账号后即可使用,无需下载模型', + 'signIn': '登录 DeepSeek', + 'signInFromSettings': '请在设置的账号页登录 DeepSeek', + 'useLocal': '改用本地识别', + 'signInPrompt.title': '云端识别需要登录 DeepSeek 账号', + 'signInPrompt.body': '当前使用 DeepSeek 云端识别,登录后即可使用,无需下载模型', + 'choicePrompt.title': '准备语音识别', + 'choicePrompt.body': '登录 DeepSeek 账号即可使用云端识别,无需下载模型。也可以下载本地模型,录音只在运行 DSH 的机器上识别。', + 'choicePrompt.download': '下载本地模型', + 'failure.sign-in-required': 'DeepSeek 登录已失效,请重新登录', + 'failure.rate-limited': '请求过于频繁,请稍后再试', + 'failure.quota-exceeded': '今日云端识别时长已用完,可改用本地识别', + 'failure.service-unavailable': '云端识别暂不可用', + 'failure.invalid-audio': '录音格式不受支持或超过服务时长限制', + 'failure.timeout': '识别超时,请重试', + 'failure.service-error': '识别失败,请重试', } as const /** Keys accepted by the voice input translator. */ @@ -206,6 +233,33 @@ export const en: Record = { unavailable: 'This browser cannot record audio. Use a browser with microphone support.', permission: 'Microphone access is disabled. Allow it in browser and system settings.', tooLarge: 'The recording exceeds the service limit. Try a shorter recording.', + 'dictateCloud': 'Dictate · cloud recognition', + 'transcribingCloud': 'Recognizing in the cloud…', + 'providerAuto': 'Automatic (recommended)', + 'providerCloud': '{name} cloud recognition', + 'providerLocal': '{name} local recognition', + 'selection.current': 'Currently using: {name}', + 'selection.signedIn': 'signed in to DeepSeek', + 'selection.signedOut': 'not signed in to DeepSeek', + 'selection.autoHelp': 'Automatic uses cloud recognition while you are signed in to DeepSeek, and local recognition otherwise.', + 'languageFallback.host-local': 'Local recognition does not support {language}; the language will be detected automatically.', + 'languageFallback.cloud': 'Cloud recognition does not support {language}; the language will be detected automatically.', + 'unavailable.sign-in-required': 'Sign in to DeepSeek to use it. No model download is needed.', + 'signIn': 'Sign in to DeepSeek', + 'signInFromSettings': 'Sign in to DeepSeek from the Account page in Settings.', + 'useLocal': 'Use local recognition', + 'signInPrompt.title': 'Cloud recognition requires a DeepSeek account', + 'signInPrompt.body': 'DeepSeek cloud recognition is selected. Sign in to use it without downloading models.', + 'choicePrompt.title': 'Prepare speech recognition', + 'choicePrompt.body': 'Sign in to DeepSeek to use cloud recognition without downloading models. You can also download a local model so recordings stay on the machine running DSH.', + 'choicePrompt.download': 'Download local model', + 'failure.sign-in-required': 'Your DeepSeek sign-in has expired. Sign in again.', + 'failure.rate-limited': 'Too many requests. Try again later.', + 'failure.quota-exceeded': 'Today\'s cloud recognition time is used up. Use local recognition or try again tomorrow.', + 'failure.service-unavailable': 'Cloud recognition is temporarily unavailable.', + 'failure.invalid-audio': 'The recording format is unsupported or exceeds the service duration limit.', + 'failure.timeout': 'Recognition timed out. Try again.', + 'failure.service-error': 'Recognition failed. Try again.', } declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -326,6 +380,33 @@ export const ja = { 'unavailable': 'このブラウザは音声を録音できません。マイクに対応したブラウザを使用してください。', 'permission': 'マイクへのアクセスが無効になっています。ブラウザとシステムの設定で許可してください。', 'tooLarge': '録音がサービスの上限を超えています。短い録音をお試しください。', + 'dictateCloud': 'ディクテーション · クラウド認識', + 'transcribingCloud': 'クラウドで認識中…', + 'providerAuto': '自動(推奨)', + 'providerCloud': '{name} クラウド認識', + 'providerLocal': '{name} ローカル認識', + 'selection.current': '現在の認識:{name}', + 'selection.signedIn': 'DeepSeek にログイン済み', + 'selection.signedOut': 'DeepSeek に未ログイン', + 'selection.autoHelp': '自動:DeepSeek にログインしている間はクラウド認識、それ以外はローカル認識を使います。', + 'languageFallback.host-local': 'ローカル認識は{language}に対応していないため、言語を自動で検出します。', + 'languageFallback.cloud': 'クラウド認識は{language}に対応していないため、言語を自動で検出します。', + 'unavailable.sign-in-required': 'DeepSeek にログインすると利用できます。モデルのダウンロードは不要です。', + 'signIn': 'DeepSeek にログイン', + 'signInFromSettings': '設定のアカウントページから DeepSeek にログインしてください。', + 'useLocal': 'ローカル認識を使う', + 'signInPrompt.title': 'クラウド認識には DeepSeek アカウントが必要です', + 'signInPrompt.body': 'DeepSeek クラウド認識が選択されています。ログインすると、モデルをダウンロードせずに利用できます。', + 'choicePrompt.title': '音声認識を準備', + 'choicePrompt.body': 'DeepSeek にログインすると、モデルをダウンロードせずにクラウド認識を使えます。ローカルモデルをダウンロードして、DSH を実行しているマシン上だけで認識することもできます。', + 'choicePrompt.download': 'ローカルモデルをダウンロード', + 'failure.sign-in-required': 'DeepSeek のログインが期限切れです。もう一度ログインしてください。', + 'failure.rate-limited': 'リクエストが多すぎます。しばらくしてから再試行してください。', + 'failure.quota-exceeded': '本日のクラウド認識時間を使い切りました。ローカル認識を使うか、明日もう一度お試しください。', + 'failure.service-unavailable': 'クラウド認識は一時的に利用できません。', + 'failure.invalid-audio': '録音形式に対応していないか、サービスの時間制限を超えています。', + 'failure.timeout': '認識がタイムアウトしました。再試行してください。', + 'failure.service-error': '認識に失敗しました。再試行してください。', } satisfies Record /** Spanish dictionary, checked against the English keys. */ @@ -427,6 +508,33 @@ export const es = { unavailable: 'Este navegador no puede grabar audio. Utilice un navegador compatible con micrófono.', permission: 'El acceso al micrófono está deshabilitado. Permitirlo en la configuración del navegador y del sistema.', tooLarge: 'La grabación excede el límite del servicio. Pruebe con una grabación más corta.', + 'dictateCloud': 'Dictar · reconocimiento en la nube', + 'transcribingCloud': 'Reconociendo en la nube…', + 'providerAuto': 'Automático (recomendado)', + 'providerCloud': 'Reconocimiento en la nube de {name}', + 'providerLocal': 'Reconocimiento local con {name}', + 'selection.current': 'En uso: {name}', + 'selection.signedIn': 'sesión iniciada en DeepSeek', + 'selection.signedOut': 'sin sesión en DeepSeek', + 'selection.autoHelp': 'Automático usa el reconocimiento en la nube mientras tienes sesión iniciada en DeepSeek y el local en caso contrario.', + 'languageFallback.host-local': 'El reconocimiento local no admite {language}; el idioma se detectará automáticamente.', + 'languageFallback.cloud': 'El reconocimiento en la nube no admite {language}; el idioma se detectará automáticamente.', + 'unavailable.sign-in-required': 'Inicia sesión en DeepSeek para usarlo. No hace falta descargar modelos.', + 'signIn': 'Iniciar sesión en DeepSeek', + 'signInFromSettings': 'Inicia sesión en DeepSeek desde la página Cuenta de Ajustes.', + 'useLocal': 'Usar reconocimiento local', + 'signInPrompt.title': 'El reconocimiento en la nube requiere una cuenta de DeepSeek', + 'signInPrompt.body': 'El reconocimiento en la nube de DeepSeek está seleccionado. Inicia sesión para usarlo sin descargar modelos.', + 'choicePrompt.title': 'Preparar el reconocimiento de voz', + 'choicePrompt.body': 'Inicia sesión en DeepSeek para usar el reconocimiento en la nube sin descargar modelos. También puedes descargar un modelo local para que las grabaciones se reconozcan solo en la máquina que ejecuta DSH.', + 'choicePrompt.download': 'Descargar modelo local', + 'failure.sign-in-required': 'Tu sesión de DeepSeek ha caducado. Vuelve a iniciar sesión.', + 'failure.rate-limited': 'Demasiadas solicitudes. Inténtalo más tarde.', + 'failure.quota-exceeded': 'Se agotó el tiempo de reconocimiento en la nube de hoy. Usa el reconocimiento local o inténtalo mañana.', + 'failure.service-unavailable': 'El reconocimiento en la nube no está disponible temporalmente.', + 'failure.invalid-audio': 'El formato de la grabación no es compatible o supera el límite de duración del servicio.', + 'failure.timeout': 'El reconocimiento agotó el tiempo de espera. Inténtalo de nuevo.', + 'failure.service-error': 'El reconocimiento falló. Inténtalo de nuevo.', } satisfies Record /** French dictionary, checked against the English keys. */ @@ -528,6 +636,33 @@ export const fr = { unavailable: 'Ce navigateur ne peut pas enregistrer de son. Utilisez un navigateur prenant en charge le microphone.', permission: "L'accès au microphone est désactivé. Autorisez-le dans les paramètres du navigateur et du système.", tooLarge: "L'enregistrement dépasse la limite du service. Essayez un enregistrement plus court.", + 'dictateCloud': 'Dicter · reconnaissance cloud', + 'transcribingCloud': 'Reconnaissance dans le cloud…', + 'providerAuto': 'Automatique (recommandé)', + 'providerCloud': 'Reconnaissance cloud {name}', + 'providerLocal': 'Reconnaissance locale {name}', + 'selection.current': 'Utilisé actuellement : {name}', + 'selection.signedIn': 'connecté à DeepSeek', + 'selection.signedOut': 'non connecté à DeepSeek', + 'selection.autoHelp': 'Automatique utilise la reconnaissance cloud lorsque vous êtes connecté à DeepSeek, et la reconnaissance locale sinon.', + 'languageFallback.host-local': 'La reconnaissance locale ne prend pas en charge {language} ; la langue sera détectée automatiquement.', + 'languageFallback.cloud': 'La reconnaissance cloud ne prend pas en charge {language} ; la langue sera détectée automatiquement.', + 'unavailable.sign-in-required': 'Connectez-vous à DeepSeek pour l\'utiliser. Aucun téléchargement de modèle n\'est nécessaire.', + 'signIn': 'Se connecter à DeepSeek', + 'signInFromSettings': 'Connectez-vous à DeepSeek depuis la page Compte des paramètres.', + 'useLocal': 'Utiliser la reconnaissance locale', + 'signInPrompt.title': 'La reconnaissance cloud nécessite un compte DeepSeek', + 'signInPrompt.body': 'La reconnaissance cloud DeepSeek est sélectionnée. Connectez-vous pour l\'utiliser sans télécharger de modèle.', + 'choicePrompt.title': 'Préparer la reconnaissance vocale', + 'choicePrompt.body': 'Connectez-vous à DeepSeek pour utiliser la reconnaissance cloud sans télécharger de modèle. Vous pouvez aussi télécharger un modèle local afin que les enregistrements soient reconnus uniquement sur la machine qui exécute DSH.', + 'choicePrompt.download': 'Télécharger le modèle local', + 'failure.sign-in-required': 'Votre connexion DeepSeek a expiré. Reconnectez-vous.', + 'failure.rate-limited': 'Trop de requêtes. Réessayez plus tard.', + 'failure.quota-exceeded': 'Le temps de reconnaissance cloud d\'aujourd\'hui est épuisé. Utilisez la reconnaissance locale ou réessayez demain.', + 'failure.service-unavailable': 'La reconnaissance cloud est temporairement indisponible.', + 'failure.invalid-audio': 'Le format de l\'enregistrement n\'est pas pris en charge ou dépasse la durée maximale du service.', + 'failure.timeout': 'La reconnaissance a expiré. Réessayez.', + 'failure.service-error': 'La reconnaissance a échoué. Réessayez.', } satisfies Record /** German dictionary, checked against the English keys. */ @@ -629,6 +764,33 @@ export const de = { unavailable: 'Dieser Browser kann keine Audiodaten aufzeichnen. Verwenden Sie einen Browser mit Mikrofonunterstützung.', permission: 'Der Mikrofonzugriff ist deaktiviert. Erlauben Sie es in den Browser- und Systemeinstellungen.', tooLarge: 'Die Aufnahme überschreitet das Dienstlimit. Versuchen Sie es mit einer kürzeren Aufnahme.', + 'dictateCloud': 'Diktieren · Cloud-Erkennung', + 'transcribingCloud': 'Erkennung in der Cloud…', + 'providerAuto': 'Automatisch (empfohlen)', + 'providerCloud': '{name}-Cloud-Erkennung', + 'providerLocal': 'Lokale Erkennung mit {name}', + 'selection.current': 'Aktuell verwendet: {name}', + 'selection.signedIn': 'bei DeepSeek angemeldet', + 'selection.signedOut': 'nicht bei DeepSeek angemeldet', + 'selection.autoHelp': 'Automatisch verwendet die Cloud-Erkennung, solange Sie bei DeepSeek angemeldet sind, andernfalls die lokale Erkennung.', + 'languageFallback.host-local': 'Die lokale Erkennung unterstützt {language} nicht; die Sprache wird automatisch erkannt.', + 'languageFallback.cloud': 'Die Cloud-Erkennung unterstützt {language} nicht; die Sprache wird automatisch erkannt.', + 'unavailable.sign-in-required': 'Melden Sie sich bei DeepSeek an, um sie zu verwenden. Es muss kein Modell heruntergeladen werden.', + 'signIn': 'Bei DeepSeek anmelden', + 'signInFromSettings': 'Melden Sie sich in den Einstellungen auf der Kontoseite bei DeepSeek an.', + 'useLocal': 'Lokale Erkennung verwenden', + 'signInPrompt.title': 'Die Cloud-Erkennung erfordert ein DeepSeek-Konto', + 'signInPrompt.body': 'Die DeepSeek-Cloud-Erkennung ist ausgewählt. Melden Sie sich an, um sie ohne Modell-Download zu verwenden.', + 'choicePrompt.title': 'Spracherkennung vorbereiten', + 'choicePrompt.body': 'Melden Sie sich bei DeepSeek an, um die Cloud-Erkennung ohne Modell-Download zu verwenden. Sie können auch ein lokales Modell herunterladen, damit Aufnahmen nur auf dem Rechner erkannt werden, auf dem DSH läuft.', + 'choicePrompt.download': 'Lokales Modell herunterladen', + 'failure.sign-in-required': 'Ihre DeepSeek-Anmeldung ist abgelaufen. Melden Sie sich erneut an.', + 'failure.rate-limited': 'Zu viele Anfragen. Versuchen Sie es später erneut.', + 'failure.quota-exceeded': 'Die heutige Cloud-Erkennungszeit ist aufgebraucht. Verwenden Sie die lokale Erkennung oder versuchen Sie es morgen erneut.', + 'failure.service-unavailable': 'Die Cloud-Erkennung ist vorübergehend nicht verfügbar.', + 'failure.invalid-audio': 'Das Aufnahmeformat wird nicht unterstützt oder überschreitet die Höchstdauer des Dienstes.', + 'failure.timeout': 'Zeitüberschreitung bei der Erkennung. Versuchen Sie es erneut.', + 'failure.service-error': 'Die Erkennung ist fehlgeschlagen. Versuchen Sie es erneut.', } satisfies Record /** Russian dictionary, checked against the English keys. */ @@ -730,6 +892,33 @@ export const ru = { unavailable: 'Этот браузер не может записывать звук. Используйте браузер с поддержкой микрофона.', permission: 'Доступ к микрофону отключен. Разрешите это в настройках браузера и системы.', tooLarge: 'Запись превышает лимит обслуживания. Попробуйте более короткую запись.', + 'dictateCloud': 'Диктовка · облачное распознавание', + 'transcribingCloud': 'Распознавание в облаке…', + 'providerAuto': 'Автоматически (рекомендуется)', + 'providerCloud': 'Облачное распознавание {name}', + 'providerLocal': 'Локальное распознавание {name}', + 'selection.current': 'Сейчас используется: {name}', + 'selection.signedIn': 'выполнен вход в DeepSeek', + 'selection.signedOut': 'вход в DeepSeek не выполнен', + 'selection.autoHelp': 'Автоматический режим использует облачное распознавание, пока выполнен вход в DeepSeek, и локальное в остальных случаях.', + 'languageFallback.host-local': 'Локальное распознавание не поддерживает язык «{language}»; язык будет определён автоматически.', + 'languageFallback.cloud': 'Облачное распознавание не поддерживает язык «{language}»; язык будет определён автоматически.', + 'unavailable.sign-in-required': 'Войдите в DeepSeek, чтобы пользоваться им. Скачивать модели не нужно.', + 'signIn': 'Войти в DeepSeek', + 'signInFromSettings': 'Войдите в DeepSeek на странице «Аккаунт» в настройках.', + 'useLocal': 'Использовать локальное распознавание', + 'signInPrompt.title': 'Для облачного распознавания нужен аккаунт DeepSeek', + 'signInPrompt.body': 'Выбрано облачное распознавание DeepSeek. Войдите, чтобы пользоваться им без загрузки моделей.', + 'choicePrompt.title': 'Подготовка распознавания речи', + 'choicePrompt.body': 'Войдите в DeepSeek, чтобы пользоваться облачным распознаванием без загрузки моделей. Можно также скачать локальную модель, чтобы записи распознавались только на компьютере, где запущен DSH.', + 'choicePrompt.download': 'Скачать локальную модель', + 'failure.sign-in-required': 'Сеанс DeepSeek истёк. Войдите снова.', + 'failure.rate-limited': 'Слишком много запросов. Повторите попытку позже.', + 'failure.quota-exceeded': 'Время облачного распознавания на сегодня исчерпано. Используйте локальное распознавание или повторите попытку завтра.', + 'failure.service-unavailable': 'Облачное распознавание временно недоступно.', + 'failure.invalid-audio': 'Формат записи не поддерживается или превышает ограничение длительности службы.', + 'failure.timeout': 'Время ожидания распознавания истекло. Повторите попытку.', + 'failure.service-error': 'Не удалось распознать речь. Повторите попытку.', } satisfies Record /** Portuguese dictionary, checked against the English keys. */ @@ -831,4 +1020,31 @@ export const pt = { unavailable: 'Este navegador não pode gravar áudio. Use um navegador com suporte para microfone.', permission: 'O acesso ao microfone está desativado. Permita nas configurações do navegador e do sistema.', tooLarge: 'A gravação excede o limite de serviço. Experimente uma gravação mais curta.', + 'dictateCloud': 'Ditar · reconhecimento na nuvem', + 'transcribingCloud': 'A reconhecer na nuvem…', + 'providerAuto': 'Automático (recomendado)', + 'providerCloud': 'Reconhecimento na nuvem da {name}', + 'providerLocal': 'Reconhecimento local com {name}', + 'selection.current': 'Em uso: {name}', + 'selection.signedIn': 'sessão iniciada na DeepSeek', + 'selection.signedOut': 'sem sessão na DeepSeek', + 'selection.autoHelp': 'O modo automático usa o reconhecimento na nuvem enquanto tem sessão iniciada na DeepSeek e o local nos restantes casos.', + 'languageFallback.host-local': 'O reconhecimento local não suporta {language}; o idioma será detetado automaticamente.', + 'languageFallback.cloud': 'O reconhecimento na nuvem não suporta {language}; o idioma será detetado automaticamente.', + 'unavailable.sign-in-required': 'Inicie sessão na DeepSeek para o utilizar. Não é necessário transferir modelos.', + 'signIn': 'Iniciar sessão na DeepSeek', + 'signInFromSettings': 'Inicie sessão na DeepSeek na página Conta das Definições.', + 'useLocal': 'Usar reconhecimento local', + 'signInPrompt.title': 'O reconhecimento na nuvem requer uma conta DeepSeek', + 'signInPrompt.body': 'O reconhecimento na nuvem da DeepSeek está selecionado. Inicie sessão para o utilizar sem transferir modelos.', + 'choicePrompt.title': 'Preparar o reconhecimento de voz', + 'choicePrompt.body': 'Inicie sessão na DeepSeek para usar o reconhecimento na nuvem sem transferir modelos. Também pode transferir um modelo local para que as gravações sejam reconhecidas apenas na máquina que executa o DSH.', + 'choicePrompt.download': 'Transferir modelo local', + 'failure.sign-in-required': 'A sua sessão na DeepSeek expirou. Inicie sessão novamente.', + 'failure.rate-limited': 'Demasiados pedidos. Tente novamente mais tarde.', + 'failure.quota-exceeded': 'O tempo de reconhecimento na nuvem de hoje esgotou-se. Use o reconhecimento local ou tente novamente amanhã.', + 'failure.service-unavailable': 'O reconhecimento na nuvem está temporariamente indisponível.', + 'failure.invalid-audio': 'O formato da gravação não é suportado ou excede o limite de duração do serviço.', + 'failure.timeout': 'O reconhecimento excedeu o tempo limite. Tente novamente.', + 'failure.service-error': 'O reconhecimento falhou. Tente novamente.', } satisfies Record diff --git a/packages/experimental/client-ui-voice-input/src/client/mount.ts b/packages/experimental/client-ui-voice-input/src/client/mount.ts index 7f43ca9cd1..72c0c9840c 100644 --- a/packages/experimental/client-ui-voice-input/src/client/mount.ts +++ b/packages/experimental/client-ui-voice-input/src/client/mount.ts @@ -12,6 +12,7 @@ import { Recording } from './audio.ts' import { createMicrophoneDeviceStore } from './microphone-device.ts' import { en, ja, es, fr, de, ru, pt, NS, zh } from './locales.ts' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-settings-account/client' import { observeReadiness } from './readiness.ts' import { VoicePreparation } from './PreparationCard.tsx' import { VoiceSetupPrompt } from './VoiceSetupPrompt.tsx' @@ -33,16 +34,26 @@ function registerUi(ctx: Context): void { return () => { pluginNavigation.set(false) } }, 'voice-input: plugin navigation presence') }) + // The account UI provides sign-in only while the current Peer may watch the account. + const accountSignIn = createSnapshotStore(false) + ctx.inject(['accountSignIn'], (scope: Context) => { + scope.effect(() => { + accountSignIn.set(true) + return () => { accountSignIn.set(false) } + }, 'voice-input: account sign-in presence') + }) const actions: VoiceInputInjected = { openSettings: () => { ctx.get('pluginNavigation')?.openBundle('@deepseek-ai/dsh-experimental-voice-input-bundle') }, - hooks: { speechReadiness: readiness.state, microphoneDevice: microphone, pluginNavigation }, + signIn: () => { ctx.get('accountSignIn')?.open() }, + hooks: { speechReadiness: readiness.state, microphoneDevice: microphone, pluginNavigation, accountSignIn }, selectMicrophone: (device) => { microphone.set(device) }, createRecording: () => { const recording = new Recording(() => { recordings.delete(recording) }, microphone.getSnapshot().id) recordings.add(recording) return recording }, - transcribe: async (request, signal) => await ctx.remote.speech.transcribe(request, signal), + transcribe: async (request, signal) => + await ctx.remote.speech.transcribe({ ...request, locale: ctx.locale.getSnapshot().active }, signal), configure: async (patch) => { const result = await ctx.remote.speech.configure(patch); if (!result.ok) throw result.error }, prepare: async (providerId, options) => { const result = await ctx.remote.speech.prepare(providerId, options); if (!result.ok) throw result.error diff --git a/packages/experimental/client-ui-voice-input/tests/cloud.client.spec.tsx b/packages/experimental/client-ui-voice-input/tests/cloud.client.spec.tsx new file mode 100644 index 0000000000..eeee11bea8 --- /dev/null +++ b/packages/experimental/client-ui-voice-input/tests/cloud.client.spec.tsx @@ -0,0 +1,285 @@ +// @vitest-environment jsdom +/** Cloud recognition guidance, location cues, classified failures, and the automatic preference. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { bindSnapshotSelector, makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SpeechCatalog, TranscriptionRequest } from '@deepseek-ai/dsh-experimental-api-speech-to-text/types' +import type { SpeechFailureCode, SpeechPreparationState, SpeechProviderId, SpeechProviderView, Transcript } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { VoiceInput, type VoiceInputProps } from '../src/client/VoiceInput.tsx' +import { VoicePreparation } from '../src/client/PreparationCard.tsx' +import { VoiceSetupPrompt, type VoiceSetupPromptProps } from '../src/client/VoiceSetupPrompt.tsx' +import { offeredLanguages, providerLabel, voiceGuidance } from '../src/client/guidance.ts' +import { Recording } from '../src/client/audio.ts' +import type { SpeechReadiness } from '../src/client/readiness.ts' +import { zh } from '../src/client/locales.ts' + +beforeEach(() => { vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1)); vi.stubGlobal('cancelAnimationFrame', vi.fn()) }) +afterEach(() => { cleanup(); vi.unstubAllGlobals() }) + +const t = makeTranslate(zh, commonZh) +const CLOUD = 'deepseek-asr' as SpeechProviderId, LOCAL = 'sensevoice-local' as SpeechProviderId +const signedOut: SpeechPreparationState = { phase: 'unavailable', reason: 'sign-in-required' } + +function catalog(options: { cloud?: SpeechPreparationState; local?: SpeechPreparationState; mode?: 'auto' | 'explicit'; selected?: SpeechProviderId; language?: string }): SpeechCatalog { + const providers: SpeechProviderView[] = [] + if (options.local) providers.push({ id: LOCAL, name: 'SenseVoiceSmall (INT8)', location: 'host-local', languages: ['auto', 'zh', 'en', 'yue', 'ja', 'ko'], preparation: options.local, + setupEstimate: { recommendedDiskBytes: 1e9, expectedMemoryBytes: 1e9, minimumMinutes: 1, maximumMinutes: 10 } }) + if (options.cloud) providers.push({ id: CLOUD, name: 'DeepSeek', location: 'cloud', languages: ['auto', 'zh', 'en', 'ja', 'es', 'fr', 'de', 'ru', 'pt', 'yue', 'ko'], preparation: options.cloud }) + return { providers, maxAudioBytes: 1000, maxDurationSeconds: 120, + selection: { mode: options.mode ?? 'auto', providerId: options.selected ?? CLOUD, language: options.language ?? 'zh' } } +} + +describe('guidance', () => { + it('derives the microphone guidance from the selected provider', () => { + expect(voiceGuidance(null, true)).toBe('unavailable') + expect(voiceGuidance(catalog({ cloud: { phase: 'ready' } }), false)).toBe('unavailable') + expect(voiceGuidance(catalog({ cloud: { phase: 'ready' } }), true)).toBeNull() + expect(voiceGuidance(catalog({ cloud: signedOut, mode: 'explicit' }), true)).toBe('sign-in') + expect(voiceGuidance(catalog({ cloud: { phase: 'failed', message: 'no token' } }), true)).toBe('unavailable') + expect(voiceGuidance(catalog({ cloud: signedOut, local: { phase: 'unprepared' }, selected: LOCAL }), true)).toBe('install-or-sign-in') + expect(voiceGuidance(catalog({ cloud: signedOut, local: { phase: 'unprepared' }, selected: LOCAL, mode: 'explicit' }), true)).toBe('install') + expect(voiceGuidance(catalog({ cloud: { phase: 'ready' }, local: { phase: 'unprepared' }, selected: LOCAL }), true)).toBe('install') + expect(voiceGuidance(catalog({ local: { phase: 'checking', startedAt: 0 }, selected: LOCAL }), true)).toBe('unavailable') + }) + + it('labels providers by processing location and offers every listed language in menu order', () => { + const both = catalog({ cloud: { phase: 'ready' }, local: { phase: 'ready' } }) + expect(both.providers.map(row => providerLabel(row, t))).toEqual(['SenseVoiceSmall (INT8) 本地识别', 'DeepSeek 云端识别']) + expect(offeredLanguages(both, ['auto', 'zh', 'en', 'ja', 'es'])).toEqual(['auto', 'zh', 'en', 'ja', 'es', 'yue', 'ko', 'fr', 'de', 'ru', 'pt']) + expect(offeredLanguages(catalog({ local: { phase: 'ready' }, selected: LOCAL }), ['auto', 'es', 'zh'])).toEqual(['auto', 'zh', 'en', 'yue', 'ja', 'ko']) + expect(offeredLanguages(null, ['auto'])).toEqual([]) + }) +}) + +function composer(initial: SpeechCatalog, options: { signIn?: boolean; navigable?: boolean } = {}) { + const capture = Object.assign(new Recording(() => {}), { start: vi.fn(async () => {}), stop: vi.fn(async () => new Uint8Array(48)), + amplitude: () => 0, dispose: vi.fn(async () => {}) }) + const inputActions = { notify: vi.fn(), insertQuote: () => false, captureInsertion: vi.fn(() => ({ start: 0, end: 0, draftRev: 1 })), + insertText: vi.fn(() => true), setDraft: vi.fn(), persistDraft: vi.fn(), addAttachments: vi.fn(() => true), removeAttachment: vi.fn(), + pruneAttachments: vi.fn(), submit: vi.fn() } + const readiness = createSnapshotStore({ connected: true, error: null, catalog: initial }) + const settle = Promise.withResolvers>() + const transcribe = vi.fn<(request: TranscriptionRequest, signal: AbortSignal) => Promise>>(() => settle.promise) + const props: VoiceInputProps = { sessionId: 'one' as SessionId, inputActions, transcribe, locked: false, onActiveChange: vi.fn(), + openSettings: vi.fn(), prepare: vi.fn(async () => {}), cancelPreparation: vi.fn(async () => {}), configure: vi.fn(async () => {}), + selectMicrophone: vi.fn(), useMicrophoneDevice: bindSnapshotSelector(createSnapshotStore({ id: '', label: '' })), + useSpeechReadiness: bindSnapshotSelector(readiness), createRecording: () => capture, + usePluginNavigation: bindSnapshotSelector(createSnapshotStore(options.navigable ?? true)), + useAccountSignIn: bindSnapshotSelector(createSnapshotStore(options.signIn ?? true)), signIn: vi.fn(), t } + render() + return { props, settle, transcribe, inputActions } +} + +async function record(): Promise { + fireEvent.click(screen.getByRole('button', { name: zh.start })) + await screen.findByRole('button', { name: zh.stop }) +} + +describe('composer', () => { + it('marks cloud recognition in the tooltip and transcription status without a recording badge', async () => { + const b = composer(catalog({ cloud: { phase: 'ready' }, local: { phase: 'unprepared' } })) + fireEvent.pointerEnter(screen.getByRole('button', { name: zh.start }).parentElement!) + expect((await screen.findByRole('tooltip')).textContent).toBe(zh.dictateCloud) + await record() + expect(screen.getByRole('img', { name: zh.recording })).toBeTruthy() + expect(screen.queryByText('云端')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: zh.stop })) + expect(await screen.findByText(zh.transcribingCloud)).toBeTruthy() + const [sent] = b.transcribe.mock.calls[0]! + expect(Object.keys(sent).sort()).toEqual(['audioBase64', 'language', 'providerId']) + expect([sent.providerId, sent.language]).toEqual([CLOUD, 'zh']) + act(() => { b.settle.resolve({ ok: true, value: { text: '你好', audioSeconds: 1, inferenceSeconds: 1 } }) }) + await waitFor(() => { expect(b.inputActions.insertText).toHaveBeenCalledWith('你好', { start: 0, end: 0, draftRev: 1 }) }) + }) + + async function fail(b: ReturnType, code: SpeechFailureCode | undefined): Promise { + await record() + fireEvent.click(screen.getByRole('button', { name: zh.stop })) + await waitFor(() => { expect(b.transcribe).toHaveBeenCalledOnce() }) + act(() => { b.settle.resolve({ ok: false, error: new RemoteError('speech/transcription-failed', 'HTTP 503', + code === undefined ? { reason: 'HTTP 503' } : { reason: 'HTTP 503', code }) }) }) + } + + it('localizes classified failures and offers sign-in after an expired account', async () => { + const b = composer(catalog({ cloud: { phase: 'ready' } })) + await fail(b, 'sign-in-required') + expect(await screen.findByText(zh['failure.sign-in-required'])).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: zh.signIn })) + expect(b.props.signIn).toHaveBeenCalledOnce() + expect(screen.queryByText(zh['failure.sign-in-required'])).toBeNull() + }) + + it('omits sign-in recovery while the account UI offers no entry and keeps unclassified messages', async () => { + const b = composer(catalog({ cloud: { phase: 'ready' } }), { signIn: false }) + await fail(b, 'sign-in-required') + expect(await screen.findByText(zh['failure.sign-in-required'])).toBeTruthy() + expect(screen.queryByRole('button', { name: zh.signIn })).toBeNull() + cleanup() + const plain = composer(catalog({ cloud: { phase: 'ready' } })) + await fail(plain, undefined) + expect(await screen.findByText('语音识别失败:HTTP 503')).toBeTruthy() + }) + + it('switches to local recognition after a cloud outage and opens setup for an unprepared model', async () => { + const b = composer(catalog({ cloud: { phase: 'ready' }, local: { phase: 'unprepared' } })) + await fail(b, 'service-unavailable') + expect(await screen.findByText(zh['failure.service-unavailable'])).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: zh.useLocal })) + await waitFor(() => { expect(b.props.openSettings).toHaveBeenCalledOnce() }) + expect(b.props.configure).toHaveBeenCalledWith({ providerId: LOCAL }) + }) + + it('switches to a prepared local model without leaving the composer', async () => { + const b = composer(catalog({ cloud: signedOut, local: { phase: 'standby' }, mode: 'explicit' })) + fireEvent.click(screen.getByRole('button', { name: zh['setupPrompt.trigger'] })) + fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: zh.useLocal })) + await waitFor(() => { expect(b.props.configure).toHaveBeenCalledWith({ providerId: LOCAL }) }) + expect(b.props.openSettings).not.toHaveBeenCalled() + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('offers local recognition once the daily cloud allowance is used up', async () => { + const b = composer(catalog({ cloud: { phase: 'ready' }, local: { phase: 'standby' } })) + await fail(b, 'quota-exceeded') + expect(await screen.findByText(zh['failure.quota-exceeded'])).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: zh.useLocal })) + await waitFor(() => { expect(b.props.configure).toHaveBeenCalledWith({ providerId: LOCAL }) }) + expect(b.props.openSettings).not.toHaveBeenCalled() + cleanup() + const cloudOnly = composer(catalog({ cloud: { phase: 'ready' } })) + await fail(cloudOnly, 'quota-exceeded') + expect(await screen.findByText(zh['failure.quota-exceeded'])).toBeTruthy() + expect(screen.queryByRole('button', { name: zh.useLocal })).toBeNull() + }) + + it('reports a failed switch to local recognition in the toolbar', async () => { + const b = composer(catalog({ cloud: signedOut, local: { phase: 'ready' }, mode: 'explicit' })) + vi.mocked(b.props.configure).mockRejectedValueOnce(new Error('settings are read-only')) + fireEvent.click(screen.getByRole('button', { name: zh['setupPrompt.trigger'] })) + const dialog = screen.getByRole('dialog', { name: zh['signInPrompt.title'] }) + fireEvent.click(within(dialog).getByRole('button', { name: zh.useLocal })) + expect(await screen.findByText('语音识别失败:settings are read-only')).toBeTruthy() + expect(b.props.openSettings).not.toHaveBeenCalled() + }) + + it('asks a signed-out user of explicit cloud recognition to sign in before recording', () => { + const b = composer(catalog({ cloud: signedOut, local: { phase: 'ready' }, mode: 'explicit' })) + fireEvent.click(screen.getByRole('button', { name: zh['setupPrompt.trigger'] })) + const dialog = screen.getByRole('dialog', { name: zh['signInPrompt.title'] }) + expect(within(dialog).getByText(zh['signInPrompt.body'])).toBeTruthy() + expect(within(dialog).getByRole('button', { name: zh.useLocal })).toBeTruthy() + fireEvent.click(within(dialog).getByRole('button', { name: zh.signIn })) + expect(b.props.signIn).toHaveBeenCalledOnce() + expect(screen.queryByRole('dialog')).toBeNull() + expect(b.transcribe).not.toHaveBeenCalled() + }) + + it('points to Settings when no sign-in entry exists and offers both paths for automatic selection', () => { + composer(catalog({ cloud: signedOut, mode: 'explicit' }), { signIn: false }) + fireEvent.click(screen.getByRole('button', { name: zh['setupPrompt.trigger'] })) + let dialog = screen.getByRole('dialog', { name: zh['signInPrompt.title'] }) + expect(within(dialog).getByText(zh.signInFromSettings)).toBeTruthy() + expect(within(dialog).queryByRole('button', { name: zh.signIn })).toBeNull() + fireEvent.click(within(dialog).getByRole('button', { name: zh['setupPrompt.later'] })) + cleanup() + const b = composer(catalog({ cloud: signedOut, local: { phase: 'unprepared' }, selected: LOCAL })) + fireEvent.click(screen.getByRole('button', { name: zh['setupPrompt.trigger'] })) + dialog = screen.getByRole('dialog', { name: zh['choicePrompt.title'] }) + fireEvent.click(within(dialog).getByRole('button', { name: zh['choicePrompt.download'] })) + expect(b.props.openSettings).toHaveBeenCalledOnce() + }) +}) + +function preferences(initial: SpeechCatalog, signIn = true) { + const store = createSnapshotStore({ connected: true, error: null, catalog: initial }) + const props = { useSpeechReadiness: bindSnapshotSelector(store), configure: vi.fn(async () => {}), t, + useMicrophoneDevice: bindSnapshotSelector(createSnapshotStore({ id: '', label: '' })), selectMicrophone: vi.fn(), + createRecording: () => new Recording(() => {}), prepare: vi.fn(async () => {}), cancelPreparation: vi.fn(async () => {}), + useAccountSignIn: bindSnapshotSelector(createSnapshotStore(signIn)), signIn: vi.fn() } + render() + return { props, store } +} + +describe('preferences', () => { + const cardIds = (): (string | null)[] => [...document.querySelectorAll('[data-speech-provider]')].map(card => card.getAttribute('data-speech-provider')) + it('offers the automatic preference and explains its current choice and account state', async () => { + const b = preferences(catalog({ cloud: signedOut, local: { phase: 'unprepared' }, selected: LOCAL })) + const service = screen.getByLabelText(zh.provider) + expect(service.value).toBe('auto') + expect(within(service).getAllByRole('option').map(option => option.textContent)) + .toEqual([zh.providerAuto, 'SenseVoiceSmall (INT8) 本地识别', 'DeepSeek 云端识别']) + expect(screen.getByText('当前使用:SenseVoiceSmall (INT8) 本地识别')).toBeTruthy() + expect(screen.getByText(zh['selection.signedOut'])).toBeTruthy() + expect(screen.getByText(zh['selection.autoHelp'])).toBeTruthy() + expect(screen.getAllByText(/本地识别$/).length).toBeGreaterThan(0) + // Automatic lists cloud before local regardless of which one is in use. + expect(cardIds()).toEqual([CLOUD, LOCAL]) + expect(screen.getByText(zh['unavailable.sign-in-required'])).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: zh.signIn })) + expect(b.props.signIn).toHaveBeenCalledOnce() + fireEvent.change(service, { target: { value: CLOUD } }) + await waitFor(() => { expect(b.props.configure).toHaveBeenCalledWith({ providerId: CLOUD }) }) + fireEvent.change(service, { target: { value: 'auto' } }) + await waitFor(() => { expect(b.props.configure).toHaveBeenCalledWith({ providerId: 'auto' }) }) + }) + + it('offers every recognized language and explains when the active provider detects instead', async () => { + const b = preferences(catalog({ cloud: { phase: 'ready' }, local: { phase: 'ready' }, language: 'es' })) + const language = screen.getByLabelText(zh.language) + expect(language.disabled).toBe(false) + expect(language.value).toBe('es') + expect(within(language).getAllByRole('option').map(option => option.getAttribute('value'))) + .toEqual(['auto', 'zh', 'en', 'ja', 'es', 'fr', 'de', 'ru', 'pt', 'yue', 'ko']) + expect(within(language).getAllByRole('option').map(option => option.textContent).slice(0, 5)) + .toEqual([zh.auto, zh.zh, zh.en, zh.ja, zh.es]) + expect(screen.queryByText(/将自动识别/)).toBeNull() + expect(screen.getByText(zh['selection.signedIn'])).toBeTruthy() + fireEvent.change(language, { target: { value: 'fr' } }) + await waitFor(() => { expect(b.props.configure).toHaveBeenCalledWith({ language: 'fr' }) }) + expect(cardIds()).toEqual([CLOUD, LOCAL]) + expect(screen.getByText(zh.cloudReady)).toBeTruthy() + act(() => { b.store.set({ connected: true, error: null, catalog: catalog({ cloud: { phase: 'ready' }, local: { phase: 'ready' }, mode: 'explicit', selected: LOCAL, language: 'es' }) }) }) + expect(screen.getByLabelText(zh.language).value).toBe('es') + expect(screen.getByText('本地识别不支持西班牙语,将自动识别')).toBeTruthy() + expect(screen.queryByText(zh['selection.signedIn'])).toBeNull() + expect(cardIds()).toEqual([LOCAL]) + act(() => { b.store.set({ connected: true, error: null, catalog: catalog({ cloud: { phase: 'ready' }, local: { phase: 'ready' }, mode: 'explicit', selected: CLOUD }) }) }) + expect(cardIds()).toEqual([CLOUD]) + }) + + it('hides sign-in without an account entry', () => { + preferences(catalog({ cloud: signedOut, mode: 'explicit' }), false) + expect(screen.queryByRole('button', { name: zh.signIn })).toBeNull() + }) +}) + +describe('activation prompt', () => { + function prompt(initial: SpeechCatalog) { + const onDismiss = vi.fn(), onOpenDetails = vi.fn(), signIn = vi.fn() + const props = { packageName: 'voice-bundle', t, onDismiss, onOpenDetails, signIn, + useSpeechReadiness: bindSnapshotSelector(createSnapshotStore({ connected: true, error: null, catalog: initial })), + useAccountSignIn: bindSnapshotSelector(createSnapshotStore(true)) } as VoiceSetupPromptProps + render() + return { onDismiss, onOpenDetails, signIn } + } + + it('enables a signed-in cloud selection without a prompt', () => { + const b = prompt(catalog({ cloud: { phase: 'ready' }, local: { phase: 'unprepared' } })) + expect(screen.queryByRole('dialog')).toBeNull() + expect(b.onDismiss).toHaveBeenCalled() + }) + + it('makes signing in the primary choice when automatic selection falls back to an unprepared model', () => { + const b = prompt(catalog({ cloud: signedOut, local: { phase: 'unprepared' }, selected: LOCAL })) + const dialog = screen.getByRole('dialog', { name: zh['choicePrompt.title'] }) + const primary = within(dialog).getByRole('button', { name: zh.signIn }) + expect(primary.hasAttribute('data-modal-autofocus')).toBe(true) + fireEvent.click(primary) + expect(b.onDismiss).toHaveBeenCalled() + expect(b.signIn).toHaveBeenCalledOnce() + }) +}) diff --git a/packages/experimental/client-ui-voice-input/tests/mount.client.spec.ts b/packages/experimental/client-ui-voice-input/tests/mount.client.spec.ts index a328473da6..1c7c8bcbeb 100644 --- a/packages/experimental/client-ui-voice-input/tests/mount.client.spec.ts +++ b/packages/experimental/client-ui-voice-input/tests/mount.client.spec.ts @@ -31,6 +31,7 @@ function assertVoiceActions(value: Record): asserts value is Re assert(typeof value.prepare === 'function') assert(typeof value.cancelPreparation === 'function') assert(typeof value.transcribe === 'function') + assert(typeof value.signIn === 'function') assert(typeof value.hooks === 'object' && value.hooks !== null) } @@ -85,6 +86,28 @@ it('starts without the Plugins page navigation and follows its presence', async } }) +it('follows the account sign-in entry and opens it only while present', async () => { + hostApply() + const b = await fixture() + try { + await b.ctx.plugin({ inject: [...inject], apply: ctx => mountVoiceInput(ctx, REMOTE) }) + const actions = b.ctx.slots.entries('conversation.input.activity').find(item => item.component === VoiceInput)!.inject!() + assertVoiceActions(actions) + expect(actions.hooks.accountSignIn.getSnapshot()).toBe(false) + expect(() => { actions.signIn() }).not.toThrow() + const open = vi.fn() + const account = b.ctx.plugin({ apply: (ctx: Context) => { ctx.provide('accountSignIn', { open } as never) } }) + await account + await vi.waitFor(() => { expect(actions.hooks.accountSignIn.getSnapshot()).toBe(true) }) + actions.signIn() + expect(open).toHaveBeenCalledOnce() + await account.dispose() + expect(actions.hooks.accountSignIn.getSnapshot()).toBe(false) + } finally { + await b.ctx.fiber.dispose() + } +}) + it('withdraws its Remote, localized slot and microphone captures on disposal', async () => { hostApply() const b = await fixture() @@ -124,7 +147,7 @@ it('withdraws its Remote, localized slot and microphone captures on disposal', a const request = { providerId: 'local' as SpeechProviderId, audioBase64: '' }, signal = new AbortController().signal await actions.transcribe(request, signal) expect(b.configure).toHaveBeenCalledTimes(2) - expect(b.transcribe).toHaveBeenCalledWith(request, signal) + expect(b.transcribe).toHaveBeenCalledWith({ ...request, locale: b.ctx.locale.getSnapshot().active }, signal) await fiber.dispose() expect(dispose).toHaveBeenCalledOnce() expect(b.ctx.slots.entries('conversation.input.activity')).toHaveLength(0) diff --git a/packages/experimental/client-ui-voice-input/tests/preparation.client.spec.tsx b/packages/experimental/client-ui-voice-input/tests/preparation.client.spec.tsx index 38f13a83ff..39541541e7 100644 --- a/packages/experimental/client-ui-voice-input/tests/preparation.client.spec.tsx +++ b/packages/experimental/client-ui-voice-input/tests/preparation.client.spec.tsx @@ -112,7 +112,7 @@ it('explains download failures on the Host machine and retains an actionable ret }) it('persists settings and reports disconnection in the detail card', async () => { const store = createSnapshotStore({ connected: true, error: null, catalog: { - selection: { providerId: id, language: 'auto' }, maxAudioBytes: 100, maxDurationSeconds: 120, + selection: { mode: 'explicit', providerId: id, language: 'auto' }, maxAudioBytes: 100, maxDurationSeconds: 120, providers: [{ id, name: 'SenseVoiceSmall', location: 'host-local', languages: ['auto', 'zh', 'en', 'ja'], preparation: { phase: 'ready' } }, { id: 'cloud' as SpeechProviderId, name: 'Cloud', location: 'cloud', languages: ['auto', 'en', 'zh', 'ja', 'fr', 'it'], preparation: { phase: 'ready' } }], } }) @@ -120,17 +120,21 @@ it('persists settings and reports disconnection in the detail card', async () => const props = { useSpeechReadiness: bindSnapshotSelector(store), configure, t, useMicrophoneDevice: bindSnapshotSelector(createSnapshotStore({ id: '', label: '' })), selectMicrophone: vi.fn(), createRecording: () => new Recording(() => {}), - prepare: vi.fn(async () => {}), cancelPreparation: vi.fn(async () => {}) } + prepare: vi.fn(async () => {}), cancelPreparation: vi.fn(async () => {}), + useAccountSignIn: bindSnapshotSelector(createSnapshotStore(false)), signIn: vi.fn() } const view = render() fireEvent.change(screen.getByLabelText(zh.provider), { target: { value: 'cloud' } }) await waitFor(() => { expect(configure).toHaveBeenCalledWith({ providerId: 'cloud' }) }) const current = store.getSnapshot() - act(() => { store.set({ ...current, catalog: { ...current.catalog!, selection: { providerId: 'cloud' as SpeechProviderId, language: 'en' } } }) }) + act(() => { store.set({ ...current, catalog: { ...current.catalog!, selection: { mode: 'explicit', providerId: 'cloud' as SpeechProviderId, language: 'en' } } }) }) expect(screen.getByText(zh.cloud)).toBeTruthy() expect(within(screen.getByLabelText(zh.language)).getAllByRole('option').map(item => item.value)) - .toEqual(['auto', 'en', 'zh', 'ja', 'fr', 'it']) + .toEqual(['auto', 'zh', 'en', 'ja', 'fr', 'it']) expect(within(screen.getByLabelText(zh.language)).getByRole('option', { name: zh.fr })).toBeTruthy() expect(within(screen.getByLabelText(zh.language)).getByRole('option', { name: 'it' })).toBeTruthy() + act(() => { store.set({ ...current, catalog: { ...current.catalog!, selection: { mode: 'explicit', providerId: id, language: 'it' } } }) }) + expect(screen.getByText('本地识别不支持it,将自动识别')).toBeTruthy() + act(() => { store.set({ ...current, catalog: { ...current.catalog!, selection: { mode: 'explicit', providerId: 'cloud' as SpeechProviderId, language: 'en' } } }) }) configure.mockRejectedValueOnce(new Error('settings are read-only')) fireEvent.change(screen.getByLabelText(zh.language), { target: { value: 'zh' } }) await screen.findByText('语音识别失败:settings are read-only') diff --git a/packages/experimental/client-ui-voice-input/tests/readiness.client.spec.ts b/packages/experimental/client-ui-voice-input/tests/readiness.client.spec.ts index 8e7787bcc4..152b37c1ae 100644 --- a/packages/experimental/client-ui-voice-input/tests/readiness.client.spec.ts +++ b/packages/experimental/client-ui-voice-input/tests/readiness.client.spec.ts @@ -7,7 +7,7 @@ import type { SpeechCatalog } from '@deepseek-ai/dsh-experimental-api-speech-to- import { expect, it, vi, onTestFinished } from 'vitest' import { observeReadiness } from '../src/client/readiness.ts' -const catalog: SpeechCatalog = { providers: [], selection: { providerId: 'local' as SpeechProviderId, language: 'auto' }, +const catalog: SpeechCatalog = { providers: [], selection: { mode: 'explicit', providerId: 'local' as SpeechProviderId, language: 'auto' }, maxAudioBytes: 100, maxDurationSeconds: 120 } function fixture(failure?: unknown) { diff --git a/packages/experimental/client-ui-voice-input/tests/setup-prompt.client.spec.tsx b/packages/experimental/client-ui-voice-input/tests/setup-prompt.client.spec.tsx index 16fe9f538a..53d684acfa 100644 --- a/packages/experimental/client-ui-voice-input/tests/setup-prompt.client.spec.tsx +++ b/packages/experimental/client-ui-voice-input/tests/setup-prompt.client.spec.tsx @@ -15,11 +15,12 @@ function fixture() { const state = createSnapshotStore({ catalog: null, connected: false, error: null }) const onDismiss = vi.fn(), onOpenDetails = vi.fn(), providerId = 'local' as SpeechProviderId const props = { packageName: 'voice-bundle', t: makeTranslate(zh), onDismiss, onOpenDetails, - useSpeechReadiness: bindSnapshotSelector(state) } as VoiceSetupPromptProps + useSpeechReadiness: bindSnapshotSelector(state), useAccountSignIn: bindSnapshotSelector(createSnapshotStore(false)), + signIn: vi.fn() } as VoiceSetupPromptProps render() return { onDismiss, onOpenDetails, publish(preparation: SpeechPreparationState, location: 'host-local' | 'cloud' = 'host-local') { act(() => { state.set({ connected: true, error: null, catalog: { - selection: { providerId, language: 'auto' }, maxAudioBytes: 1000, maxDurationSeconds: 120, + selection: { mode: 'explicit', providerId, language: 'auto' }, maxAudioBytes: 1000, maxDurationSeconds: 120, providers: [{ id: providerId, name: 'SenseVoice', location, languages: ['auto'], preparation }], } }) }) } } diff --git a/packages/experimental/client-ui-voice-input/tests/voice-input.client.spec.tsx b/packages/experimental/client-ui-voice-input/tests/voice-input.client.spec.tsx index b0e23ff464..0f5e89a544 100644 --- a/packages/experimental/client-ui-voice-input/tests/voice-input.client.spec.tsx +++ b/packages/experimental/client-ui-voice-input/tests/voice-input.client.spec.tsx @@ -27,7 +27,7 @@ function fixture(recording?: Recording, navigable = true) { pruneAttachments: vi.fn(), submit: vi.fn() } const readiness = createSnapshotStore({ connected: true, error: null, catalog: { providers: [{ id, name: 'SenseVoiceSmall', location: 'host-local', languages: ['auto', 'zh', 'en', 'ja'], preparation: { phase: 'ready' } }], - selection: { providerId: id, language: 'auto' }, maxAudioBytes: 100, maxDurationSeconds: 120, + selection: { mode: 'explicit', providerId: id, language: 'auto' }, maxAudioBytes: 100, maxDurationSeconds: 120, } }) const transcribe = vi.fn<(request: unknown, signal: AbortSignal) => Promise>>( async () => ({ ok: true, value: transcript })) @@ -36,6 +36,7 @@ function fixture(recording?: Recording, navigable = true) { selectMicrophone: vi.fn(), useMicrophoneDevice: bindSnapshotSelector(createSnapshotStore({ id: '', label: '' })), useSpeechReadiness: bindSnapshotSelector(readiness), createRecording: () => recording ?? capture, usePluginNavigation: bindSnapshotSelector(createSnapshotStore(navigable)), + useAccountSignIn: bindSnapshotSelector(createSnapshotStore(false)), signIn: vi.fn(), t: makeTranslate(zh, commonZh) } const view = render() return { props, capture, inputActions, readiness, transcribe, view } @@ -95,7 +96,7 @@ it('keeps provider and language fixed and preserves conflicting text for explici const b = fixture(); b.inputActions.insertText.mockReturnValue(false) await start() const state = b.readiness.getSnapshot() - act(() => { b.readiness.set({ ...state, catalog: { ...state.catalog!, selection: { providerId: id, language: 'en' } } }) }) + act(() => { b.readiness.set({ ...state, catalog: { ...state.catalog!, selection: { mode: 'explicit', providerId: id, language: 'en' } } }) }) stop() const insert = await screen.findByRole('button', { name: zh.insert }) expect(b.transcribe).toHaveBeenCalledWith(expect.objectContaining({ language: 'auto' }), expect.any(AbortSignal)) diff --git a/packages/experimental/client-ui-voice-input/tsconfig.json b/packages/experimental/client-ui-voice-input/tsconfig.json index eab610db2d..49d5f40fee 100644 --- a/packages/experimental/client-ui-voice-input/tsconfig.json +++ b/packages/experimental/client-ui-voice-input/tsconfig.json @@ -55,6 +55,9 @@ }, { "path": "../../client/ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../../client/ui-settings-account" } ] } diff --git a/packages/experimental/speech-to-text-deepseek/README.i18n.yaml b/packages/experimental/speech-to-text-deepseek/README.i18n.yaml new file mode 100644 index 0000000000..b5765aa3d0 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/README.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/speech-to-text-deepseek/README.md +/: + en: 49b7e4c8c2d226db + zh: 49252d60bd302488 +/deepseek-ai-dsh-speech-to-text-deepseek: + en: 3f9c968e887d1b0e + zh: 87773b1199035b43 +/deepseek-ai-dsh-speech-to-text-deepseek/summary: + en: cf2c7f54a2cdd558 + zh: 9f73c2b6c86836cf +/deepseek-ai-dsh-speech-to-text-deepseek/table-of-contents: + en: d152484eb41ac6b4 + zh: 364c80ee00a374ff +/deepseek-ai-dsh-speech-to-text-deepseek/use-this-package: + en: e01bfa8cf5320995 + zh: 396e4365646078d5 +/deepseek-ai-dsh-speech-to-text-deepseek/understand-the-implementation: + en: 8a8297b71b9deb5c + zh: 907bb496784534e7 +/deepseek-ai-dsh-speech-to-text-deepseek/further-exploration: + en: 5c64426add9d79d6 + zh: 4e06aa2ead8d2ccd +/deepseek-ai-dsh-speech-to-text-deepseek/model-experience: + en: 889f2ab33ba9864e + zh: df7f7faab0fec85a +/deepseek-ai-dsh-speech-to-text-deepseek/model-experience/kv-cache-effect: + en: b5ec79db2e1d0dbc + zh: e5aff567ae5ee6fc +/deepseek-ai-dsh-speech-to-text-deepseek/known-limitations-and-deferred-work: + en: ea34516252d09c95 + zh: 6090de90c221cc31 +/deepseek-ai-dsh-speech-to-text-deepseek/known-limitations-and-deferred-work/dev-note: + en: 1db80dd0b4dada5f + zh: c05b807e22a0b020 diff --git a/packages/experimental/speech-to-text-deepseek/README.md b/packages/experimental/speech-to-text-deepseek/README.md new file mode 100644 index 0000000000..ff79a761a6 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/README.md @@ -0,0 +1,82 @@ +--- +description: "Recognize complete recordings with the DeepSeek One-Shot cloud service." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-speech-to-text-deepseek + +English | [中文](README.zh.md) + +## Summary + +This provider registers `deepseek-asr` with `speech-to-text` and sends each complete recording to the DeepSeek One-Shot transcription endpoint as raw 16 kHz mono PCM16. It authenticates with the signed-in DeepSeek account and accepts recordings only while an account is stored. Activation does not contact the recognition service. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The [voice input bundle](../voice-input-bundle/README.md) enables this row. `endpoint`, the complete transcription URL, defaults to `https://harness.deepseek.com/api/v0/asr/transcribe`. HTTPS is required; `allowLoopbackHttp: true` permits plain HTTP only to a loopback service double. The endpoint must not contain credentials, a query or a fragment. `timeoutMs` (30,000 ms), `maxRequestBytes` (3,932,160), `maxDurationSeconds` (120) and `maxResponseBytes` (65,536) bound one attempt. + +Each request sends the token that the DeepSeek account service releases for `endpoint` as `x-dsh-auth-token`, like the account model route. The account service releases a token only for the origins it allows, including `https://harness.deepseek.com` by default; a stored account that receives no token for the endpoint reports failed readiness instead of a sign-in request. A rejection (HTTP 401, code 40002 or 40003) invalidates exactly that token, so the account signs out and the failure asks the user to sign in again. + +----- + + +## Understand the implementation + +
+Maintainer details — click to expand + +Readiness follows the account service's `watch()` stream; the latest inspection wins and disposal stops publication. Without an account service or a stored account the provider is `unavailable` with `sign-in-required`, which automatic selection skips. `prepare()` re-inspects; there is nothing to download or cancel. + +A recording is validated as canonical WAV, stripped of its 44-byte header and zero-padded to a multiple of 32 bytes, at most 1 ms of silence, because the service rejects other raw PCM lengths. The multipart body carries `file`, `format=pcm` and a fresh `audio_id`; its complete length is checked before sending. `languages` (default `auto`, `zh`, `en`, `ja`, `es`, `fr`, `de`, `ru`, `pt`, `yue`, `ko`) lists the service's language codes and must include `auto`. A listed hint other than `auto` is sent as `preferred_language`; `auto` sends none. The client's UI language is sent as `x-client-locale` in the service spelling: hyphens become underscores and a bare `zh`, `en` or `pt` gains the region `CN`, `US` or `BR`. The service matches the two values. Requests refuse redirects, so tokens never follow a redirect. + +The service deduplicates by `audio_id`, so the identical body is resubmitted once when no response arrives, on HTTP 5xx, or on `biz_code 3`. Other outcomes are final: `biz_data.code` 6 and 10 return empty text; 1, 2, 4, 7 and 8 map to `service-unavailable`, `rate-limited`, `invalid-audio` and `timeout`; 11 (`daily_limit_reached`, the daily recognition time allowance is used up) maps to `quota-exceeded`; HTTP 429 maps to `rate-limited`; other statuses, codes and malformed envelopes map to `service-error`. Failures throw `SpeechTranscriptionError` and log the endpoint path, status and codes with the `[speech-to-text-deepseek]` prefix, never audio, tokens or response bodies. + +
+ +----- + + +## Further Exploration + +[Voice input subsystem](../../../docs/subsystems/voice-input.md) + +----- + + +## Model Experience + +None, as recordings and transcription remain outside model requests; ordinary user submission owns any later text. + +#### KV Cache effect + +No direct effect; ordinary submission owns the message content. + +## Known Limitations and Deferred Work + + + +- Only One-Shot transcription of a complete recording is supported; the WebSocket streaming endpoint and `fetch_cached` are not used. Recordings must not exceed 120 seconds. + +----- + + +### Dev Note + +
+Maintainer details — click to expand + +Tests run against loopback service doubles: `tests/service-double.ts` for the provider and `apps/web/tests/voice-input-cloud.e2e.ts` for browser sign-in and dictation through the shipped composition. No test calls the production endpoint, because its account token comes only from an interactive browser sign-in. + +
diff --git a/packages/experimental/speech-to-text-deepseek/README.zh.md b/packages/experimental/speech-to-text-deepseek/README.zh.md new file mode 100644 index 0000000000..62c5e2a849 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/README.zh.md @@ -0,0 +1,82 @@ +--- +description: "使用 DeepSeek One-Shot 云端服务识别完整录音。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-speech-to-text-deepseek + +[English](README.md) | 中文 + +## 概述 + +此 Provider 向 `speech-to-text` 注册 `deepseek-asr`,把每段完整录音以 16 kHz 单声道 PCM16 裸数据发送到 DeepSeek One-Shot 转写接口。它使用已登录的 DeepSeek 账号鉴权,只有存在已保存的账号时才接受录音。启用时不访问识别服务。 + +## 目录 + +- [使用此包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +[语音输入 Bundle](../voice-input-bundle/README.zh.md) 启用这一行。`endpoint` 是完整的转写 URL,默认为 `https://harness.deepseek.com/api/v0/asr/transcribe`。必须使用 HTTPS;`allowLoopbackHttp: true` 只允许以明文 HTTP 访问本机回环地址上的服务替身。endpoint 不能包含凭据、query 或 fragment。`timeoutMs`(30,000 毫秒)、`maxRequestBytes`(3,932,160)、`maxDurationSeconds`(120)和 `maxResponseBytes`(65,536)限制单次请求。 + +与账号模型路由相同,每次请求都把 DeepSeek 账号服务为 `endpoint` 发放的令牌作为 `x-dsh-auth-token` 发送。账号服务只为它允许的 origin 发放令牌,默认包含 `https://harness.deepseek.com`;已保存账号却拿不到该 endpoint 的令牌时,就绪状态报告失败,而不是要求登录。服务拒绝令牌(HTTP 401、code 40002 或 40003)时,只作废被拒绝的那个令牌,账号随之退出登录,失败提示用户重新登录。 + +----- + + +## 理解实现 + +
+维护者信息 — 点击展开 + +就绪状态跟随账号服务的 `watch()` 流;以最新一次检查为准,卸载后不再发布。没有账号服务或没有已保存账号时,Provider 处于带 `sign-in-required` 的 `unavailable`,自动选择会跳过它。`prepare()` 只重新检查;没有需要下载或取消的资源。 + +录音先按规范 WAV 校验,去掉 44 字节头,再补零到 32 字节的整数倍(最多 1 毫秒静音),因为服务拒绝其他长度的裸 PCM。multipart 请求体包含 `file`、`format=pcm` 和新生成的 `audio_id`;发送前检查完整长度。`languages`(默认 `auto`、`zh`、`en`、`ja`、`es`、`fr`、`de`、`ru`、`pt`、`yue`、`ko`)列出服务的语言代码,必须包含 `auto`。`auto` 以外的已列出提示作为 `preferred_language` 发送;`auto` 不发送。客户端的界面语言按服务的写法作为 `x-client-locale` 发送:连字符换成下划线,单独的 `zh`、`en`、`pt` 补上地区 `CN`、`US`、`BR`。服务综合这两个值匹配语言。请求拒绝重定向,令牌不会随重定向转发。 + +服务按 `audio_id` 去重,因此在没有收到响应、HTTP 5xx 或 `biz_code 3` 时,原样重新提交一次。其他结果都是最终结果:`biz_data.code` 6 和 10 返回空文本;1、2、4、7、8 分别映射为 `service-unavailable`、`rate-limited`、`invalid-audio` 和 `timeout`;11(`daily_limit_reached`,当日识别时长额度已用完)映射为 `quota-exceeded`;HTTP 429 映射为 `rate-limited`;其他状态码、code 和格式错误的响应映射为 `service-error`。失败时抛出 `SpeechTranscriptionError`,并以 `[speech-to-text-deepseek]` 前缀记录 endpoint 路径、状态码和返回码,从不记录音频、令牌或响应正文。 + +
+ +----- + + +## 进一步探索 + +[语音输入子系统](../../../docs/subsystems/voice-input.zh.md) + +----- + + +## 模型体验 + +无,因为录音与转写不进入模型请求;之后的文字由普通用户提交拥有。 + +#### KV 缓存影响 + +没有直接影响;普通提交拥有消息内容。 + +## 已知限制与后续工作 + + + +- 只支持对完整录音做 One-Shot 转写,不使用 WebSocket 流式接口和 `fetch_cached`。录音不能超过 120 秒。 + +----- + + +### 开发备注 + +
+维护者信息 — 点击展开 + +测试都使用本机回环服务替身:Provider 测试使用 `tests/service-double.ts`,`apps/web/tests/voice-input-cloud.e2e.ts` 在发布的组合中验证浏览器登录与听写。没有测试访问生产接口,因为其账号令牌只能通过交互式浏览器登录获得。 + +
diff --git a/packages/experimental/speech-to-text-deepseek/locale/de.json b/packages/experimental/speech-to-text-deepseek/locale/de.json new file mode 100644 index 0000000000..681e6e2eb9 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek-Cloud-Erkennung", + "description": "Transkribiert Aufnahmen mit dem DeepSeek-Clouddienst, nachdem Sie sich mit einem DeepSeek-Konto angemeldet haben." + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/en.json b/packages/experimental/speech-to-text-deepseek/locale/en.json new file mode 100644 index 0000000000..ae2882bcf3 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek cloud recognition", + "description": "Transcribe recordings with the DeepSeek cloud service after signing in to a DeepSeek account." + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/es.json b/packages/experimental/speech-to-text-deepseek/locale/es.json new file mode 100644 index 0000000000..3e2e06e431 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Reconocimiento en la nube de DeepSeek", + "description": "Transcribe grabaciones con el servicio en la nube de DeepSeek tras iniciar sesión con una cuenta de DeepSeek." + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/fr.json b/packages/experimental/speech-to-text-deepseek/locale/fr.json new file mode 100644 index 0000000000..e4cdd835e3 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Reconnaissance cloud DeepSeek", + "description": "Transcrit les enregistrements avec le service cloud de DeepSeek après connexion à un compte DeepSeek." + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/ja.json b/packages/experimental/speech-to-text-deepseek/locale/ja.json new file mode 100644 index 0000000000..712df87179 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek クラウド認識", + "description": "DeepSeek アカウントにログインすると、DeepSeek のクラウドサービスで録音を文字起こしします。" + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/pt.json b/packages/experimental/speech-to-text-deepseek/locale/pt.json new file mode 100644 index 0000000000..8f0cbfc7a3 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Reconhecimento na nuvem da DeepSeek", + "description": "Transcreve gravações com o serviço em nuvem da DeepSeek após iniciar sessão numa conta DeepSeek." + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/ru.json b/packages/experimental/speech-to-text-deepseek/locale/ru.json new file mode 100644 index 0000000000..04102d0b79 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Облачное распознавание DeepSeek", + "description": "Расшифровывает записи облачным сервисом DeepSeek после входа в аккаунт DeepSeek." + } +} diff --git a/packages/experimental/speech-to-text-deepseek/locale/zh.json b/packages/experimental/speech-to-text-deepseek/locale/zh.json new file mode 100644 index 0000000000..c473831891 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek 云端识别", + "description": "登录 DeepSeek 账号后,使用 DeepSeek 云端服务转写录音。" + } +} diff --git a/packages/experimental/speech-to-text-deepseek/package.json b/packages/experimental/speech-to-text-deepseek/package.json new file mode 100644 index 0000000000..a22080df15 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/package.json @@ -0,0 +1,52 @@ +{ + "name": "@deepseek-ai/dsh-speech-to-text-deepseek", + "description": "DeepSeek One-Shot cloud transcription authenticated by the DeepSeek account", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/speech-to-text-deepseek" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-experimental-speech-to-text": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-experimental-speech-to-text": "workspace:*" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-deepseek-account": { + "optional": true + } + } +} diff --git a/packages/experimental/speech-to-text-deepseek/src/audio.ts b/packages/experimental/speech-to-text-deepseek/src/audio.ts new file mode 100644 index 0000000000..4b40783cba --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/src/audio.ts @@ -0,0 +1,71 @@ +/** Raw PCM payload and multipart body accepted by the One-Shot transcription endpoint. */ +import { randomUUID } from 'node:crypto' +import { SpeechTranscriptionError } from '@deepseek-ai/dsh-experimental-speech-to-text' +import { validateWave } from '@deepseek-ai/dsh-experimental-speech-to-text/wave' + +/** Region-less UI languages and the region the service's `x-client-locale` table lists for them. */ +const DEFAULT_REGIONS: Readonly> = { zh: 'zh_CN', en: 'en_US', pt: 'pt_BR' } + +/** + * Convert a client UI language to the service's `x-client-locale` spelling. + * @param locale - BCP 47 language tag such as `zh`, `zh-Hant` or `pt-BR`. + * @returns underscore-separated locale, with a default region for a bare `zh`, `en` or `pt`. + */ +export function clientLocale(locale: string): string { + const wire = locale.replaceAll('-', '_') + return DEFAULT_REGIONS[wire] ?? wire +} + +/** The service rejects raw PCM whose byte length is not a multiple of this value. */ +const PCM_ALIGNMENT_BYTES = 32 +const WAVE_HEADER_BYTES = 44 + +/** Canonical WAV converted to the service's raw 16 kHz mono PCM16 payload. */ +export interface PcmPayload { + /** Samples zero-padded to the service alignment; padding adds at most 1 ms of silence. */ + readonly pcm: Uint8Array + /** Duration of the original recording. */ + readonly seconds: number +} + +/** + * Strip the WAV header and align the samples. + * @param audio - canonical 16 kHz mono PCM16 WAV recording. + * @param maxDurationSeconds - longest recording the service accepts. + * @returns aligned samples and the recording duration. + */ +export function pcmPayload(audio: Uint8Array, maxDurationSeconds: number): PcmPayload { + let seconds: number + try { seconds = validateWave(audio, maxDurationSeconds) } catch (error) { + // validateWave reports every rejection as an Error whose message names the violated constraint. + throw new SpeechTranscriptionError('invalid-audio', (error as Error).message, { cause: error }) + } + const samples = audio.subarray(WAVE_HEADER_BYTES) + const pcm = new Uint8Array(Math.ceil(samples.byteLength / PCM_ALIGNMENT_BYTES) * PCM_ALIGNMENT_BYTES) + pcm.set(samples) + return { pcm, seconds } +} + +/** One encoded `multipart/form-data` request body. */ +export interface MultipartBody { + readonly body: Uint8Array + readonly contentType: string +} + +/** + * Encode text fields and one binary file; the complete byte length is known before sending. + * @param fields - text field names and values. + * @param file - file field name, file name, and bytes. + * @returns the body and its content type. + */ +export function multipartBody(fields: readonly (readonly [string, string])[], + file: { readonly name: string; readonly filename: string; readonly bytes: Uint8Array }): MultipartBody { + const boundary = `dsh-speech-${randomUUID()}` + const parts: Uint8Array[] = [] + for (const [name, value] of fields) { + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`)) + } + parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${file.name}"; filename="${file.filename}"\r\n` + + 'Content-Type: application/octet-stream\r\n\r\n'), file.bytes, Buffer.from(`\r\n--${boundary}--\r\n`)) + return { body: Buffer.concat(parts), contentType: `multipart/form-data; boundary=${boundary}` } +} diff --git a/packages/experimental/speech-to-text-deepseek/src/availability.ts b/packages/experimental/speech-to-text-deepseek/src/availability.ts new file mode 100644 index 0000000000..a7bf7c17bc --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/src/availability.ts @@ -0,0 +1,67 @@ +/** Recording readiness derived from the DeepSeek account and configured credentials; nothing is downloaded. */ +import type { SpeechPreparation, SpeechPreparationState } from '@deepseek-ai/dsh-experimental-speech-to-text/types' + +/** + * Inspect whether recordings can be sent now. + * @param signedIn - whether the account service reports a stored account. + * @returns the complete state to publish. + */ +export type ReadinessInspection = (signedIn: boolean) => Promise + +/** Host-owned cloud readiness; the latest inspection wins and disposal stops publication. */ +export class CloudReadiness implements SpeechPreparation { + private state: SpeechPreparationState = { phase: 'unavailable', reason: 'sign-in-required' } + private readonly listeners = new Set<() => void>() + private generation = 0 + private closed = false + private present = false + + /** @param inspection - availability check, rerun whenever its inputs change. */ + constructor(private readonly inspection: ReadinessInspection) {} + + /** @returns the latest published state. */ + snapshot(): SpeechPreparationState { return this.state } + + /** @param listener - invalidation callback. @returns subscription disposer. */ + subscribe(listener: () => void): () => void { + this.listeners.add(listener) + return () => { this.listeners.delete(listener) } + } + + /** Re-inspect account and credentials; cloud recognition has no resources to download. */ + prepare(): void { void this.refresh() } + + /** Nothing runs between inspections, so there is no preparation to cancel. */ + async cancel(): Promise {} + + /** + * Record account presence and re-inspect. + * @param signedIn - whether an account is stored. + * @returns after the resulting inspection settles. + */ + async account(signedIn: boolean): Promise { + this.present = signedIn + await this.refresh() + } + + /** + * Run the inspection; an older inspection that settles later is discarded, and a failure publishes `failed`. + * @returns after this inspection settles. + */ + async refresh(): Promise { + const generation = ++this.generation + let next: SpeechPreparationState + try { next = await this.inspection(this.present) } catch (error) { + next = { phase: 'failed', message: error instanceof Error ? error.message : String(error) } + } + if (generation !== this.generation || this.closed) return + this.state = next + for (const listener of this.listeners) listener() + } + + /** Stop publishing; later inspections settle without notifying. */ + dispose(): void { + this.closed = true + this.listeners.clear() + } +} diff --git a/packages/experimental/speech-to-text-deepseek/src/config.ts b/packages/experimental/speech-to-text-deepseek/src/config.ts new file mode 100644 index 0000000000..5b17c3a8c7 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/src/config.ts @@ -0,0 +1,71 @@ +/** Deployment configuration for DeepSeek One-Shot recognition and its one explicit resolve step. */ +import z from '@deepseek-ai/schemastery' +import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import type { SpeechProviderId } from '@deepseek-ai/dsh-experimental-speech-to-text/types' + +/** Endpoint and service limits; requests authenticate with the DeepSeek account token released for the endpoint. */ +export interface Config { + /** Unique registration id; `speech-to-text` selects this exact id. */ + providerId: string + /** Complete One-Shot transcription URL. */ + endpoint: string + /** Permit plain HTTP to a loopback endpoint, for local service doubles. */ + allowLoopbackHttp: boolean + /** Deadline for one request attempt, including its response body. */ + timeoutMs: number + /** Maximum multipart request bytes the service accepts. */ + maxRequestBytes: number + /** Maximum recording duration the service accepts. */ + maxDurationSeconds: number + /** Maximum response body bytes read from the service. */ + maxResponseBytes: number + /** Language codes the service recognizes, sent as `preferred_language`; `auto` sends none and must be listed. */ + languages: string[] +} + +/** Validate deployment-varying choices at plugin activation. */ +export const Config: z, Config> = z.object({ + providerId: z.string().min(1).default('deepseek-asr'), + endpoint: z.string().min(1).default('https://harness.deepseek.com/api/v0/asr/transcribe'), + allowLoopbackHttp: z.boolean().default(false), + timeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(30_000), + maxRequestBytes: z.natural().min(1).default(3_932_160), + maxDurationSeconds: z.number().min(1).default(120), + maxResponseBytes: z.natural().min(1).default(64 * 1024), + languages: z.array(z.string().pattern(/^(auto|[a-z]{2,3})$/)).default(['auto', 'zh', 'en', 'ja', 'es', 'fr', 'de', 'ru', 'pt', 'yue', 'ko']), +}) + +/** One validated configuration generation. */ +export interface ResolvedOptions { + readonly providerId: SpeechProviderId + readonly endpoint: URL + readonly timeoutMs: number + readonly maxRequestBytes: number + readonly maxDurationSeconds: number + readonly maxResponseBytes: number + readonly languages: readonly string[] +} + +const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']) + +/** + * Validate the endpoint and languages before registration. + * @param config - parsed plugin configuration. + * @returns the facts every request uses. + */ +export function resolveOptions(config: Config): ResolvedOptions { + const endpoint = new URL(config.endpoint) + if (endpoint.username !== '' || endpoint.password !== '' || endpoint.search !== '' || endpoint.hash !== '') { + throw new Error('speech-to-text-deepseek: endpoint must not contain credentials, a query or a fragment') + } + const loopbackHttp = endpoint.protocol === 'http:' && LOOPBACK_HOSTS.has(endpoint.hostname) && config.allowLoopbackHttp + if (endpoint.protocol !== 'https:' && !loopbackHttp) { + throw new Error('speech-to-text-deepseek: endpoint must use HTTPS; plain HTTP needs allowLoopbackHttp and a loopback host') + } + if (!config.languages.includes('auto')) throw new Error('speech-to-text-deepseek: languages must include `auto`') + return { + providerId: config.providerId as SpeechProviderId, endpoint, timeoutMs: config.timeoutMs, + maxRequestBytes: config.maxRequestBytes, maxDurationSeconds: config.maxDurationSeconds, maxResponseBytes: config.maxResponseBytes, + languages: [...new Set(config.languages)], + } +} diff --git a/packages/experimental/speech-to-text-deepseek/src/index.ts b/packages/experimental/speech-to-text-deepseek/src/index.ts new file mode 100644 index 0000000000..380b0ae9a7 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/src/index.ts @@ -0,0 +1,98 @@ +/** Optional DeepSeek One-Shot cloud recognizer; activation sends no audio and reads no token. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-deepseek-account' +import { SpeechTranscriptionError } from '@deepseek-ai/dsh-experimental-speech-to-text' +import type { SpeechInput, SpeechPreparationState, Transcript } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import { randomUUID } from 'node:crypto' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { clientLocale, multipartBody, pcmPayload } from './audio.ts' +import { CloudReadiness } from './availability.ts' +import { Config, resolveOptions, type ResolvedOptions } from './config.ts' +import { attemptTranscription, type AttemptOutcome } from './request.ts' + +export { Config } from './config.ts' +export const name = 'speech-to-text-deepseek' +export const inject = ['speechToText'] + +/** Header carrying the account token. */ +const TOKEN_HEADER = 'x-dsh-auth-token' +const LOG_TAG = '[speech-to-text-deepseek]' + +/** + * Register the cloud recognizer and follow the account state without contacting the recognition service. + * @param ctx - Host registry owner; the account service is read when present. + * @param config - validated deployment configuration. + */ +export function apply(ctx: Context, config: Config): void { + const options = resolveOptions(config) + const readiness = new CloudReadiness(signedIn => inspect(ctx, options, signedIn)) + ctx.effect(() => () => { readiness.dispose() }) + ctx.inject(['deepseekAccount'], (scope) => { + scope.effect(() => { + const lifetime = new AbortController() + const watching = (async () => { + for await (const view of scope.deepseekAccount.watch(lifetime.signal)) await readiness.account(view.status === 'credential-stored') + })().catch(async (error: unknown) => { + if (lifetime.signal.aborted) return + console.error(LOG_TAG, 'account observation failed:', error instanceof Error ? error.message : String(error)) + await readiness.account(false) + }) + return async () => { + lifetime.abort() + await watching + await readiness.account(false) + } + }) + }) + ctx.effect(() => ctx.speechToText.register({ + info: { id: options.providerId, name: 'DeepSeek', location: 'cloud', languages: options.languages }, + preparation: readiness, + transcribe: async (input, signal) => await transcribe(ctx, options, input, signal), + })) + void readiness.refresh() +} + +async function inspect(ctx: Context, options: ResolvedOptions, signedIn: boolean): Promise { + if (!signedIn) return { phase: 'unavailable', reason: 'sign-in-required' } + const token = await ctx.get('deepseekAccount')?.resolveToken(options.endpoint.href) + return token !== undefined ? { phase: 'ready' } + : { phase: 'failed', message: `The DeepSeek account does not release a token for ${options.endpoint.origin}` } +} + +async function transcribe(ctx: Context, options: ResolvedOptions, input: SpeechInput, signal: AbortSignal): Promise { + const started = performance.now() + const { pcm, seconds } = pcmPayload(input.audio, options.maxDurationSeconds) + // `auto` sends no preference, so the service matches the client locale instead. + const fields: [string, string][] = [['format', 'pcm'], ['audio_id', randomUUID()]] + if (input.language !== 'auto') fields.push(['preferred_language', input.language]) + const { body, contentType } = multipartBody(fields, + { name: 'file', filename: 'recording.pcm', bytes: pcm }) + if (body.byteLength > options.maxRequestBytes) { + throw new SpeechTranscriptionError('invalid-audio', `Request is ${body.byteLength} bytes; the service accepts ${options.maxRequestBytes}`) + } + const account = ctx.get('deepseekAccount') + const token = await account?.resolveToken(options.endpoint.href) + if (token === undefined) throw new SpeechTranscriptionError('sign-in-required', 'Cloud recognition requires a signed-in DeepSeek account') + const headers: Record = { [TOKEN_HEADER]: token } + if (input.locale !== undefined) headers['x-client-locale'] = clientLocale(input.locale) + const request = { endpoint: options.endpoint, body, contentType, headers, + timeoutMs: options.timeoutMs, maxResponseBytes: options.maxResponseBytes } + let outcome: AttemptOutcome = await attemptTranscription(request, signal) + // The service deduplicates by audio_id, so resubmitting the identical body cannot recognize the recording twice. + if (outcome.kind === 'retryable') outcome = await attemptTranscription(request, signal) + switch (outcome.kind) { + case 'text': return { text: outcome.text, audioSeconds: seconds, inferenceSeconds: (performance.now() - started) / 1000 } + case 'credentials-rejected': + console.error(LOG_TAG, `${options.endpoint.pathname} rejected the account token: ${outcome.diagnostic}`) + try { await account?.rejectToken(token) } catch (_removalFailed) { + // A credential-store failure cannot replace the service's rejection, which the user must still see. + } + throw new SpeechTranscriptionError('sign-in-required', `The DeepSeek account token was rejected (${outcome.diagnostic})`) + case 'retryable': + case 'failed': + console.error(LOG_TAG, `${options.endpoint.pathname} failed (${outcome.code}): ${outcome.diagnostic}`) + throw new SpeechTranscriptionError(outcome.code, `Cloud recognition failed: ${outcome.diagnostic}`) + /* v8 ignore next -- closed-union exhaustiveness guard */ + default: return assertNever(outcome, 'speech attempt outcome') + } +} diff --git a/packages/experimental/speech-to-text-deepseek/src/request.ts b/packages/experimental/speech-to-text-deepseek/src/request.ts new file mode 100644 index 0000000000..4334bd4870 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/src/request.ts @@ -0,0 +1,97 @@ +/** One HTTP attempt against the One-Shot endpoint and the classification of its outcome. */ +import { z } from 'zod' +import type { SpeechFailureCode } from '@deepseek-ai/dsh-experimental-speech-to-text/types' + +/** Classified result of one attempt; diagnostics carry status and codes only, never credentials or audio. */ +export type AttemptOutcome = + | { readonly kind: 'text'; readonly text: string } + | { readonly kind: 'credentials-rejected'; readonly diagnostic: string } + | { readonly kind: 'retryable' | 'failed'; readonly code: SpeechFailureCode; readonly diagnostic: string } + +/** Request facts shared by the first attempt and its retry, which reuses the same `audio_id`. */ +export interface AttemptRequest { + readonly endpoint: URL + readonly body: Uint8Array + readonly contentType: string + readonly headers: Readonly> + readonly timeoutMs: number + readonly maxResponseBytes: number +} + +/** Outer response codes for a missing or rejected token. */ +const TOKEN_REJECTED = new Set([40002, 40003]) +/** `biz_data.code` values of a failed recognition; `empty` means the service heard no speech. */ +const RECOGNITION_FAILURES = new Map([ + [1, 'service-unavailable'], [2, 'rate-limited'], [3, 'service-error'], [4, 'invalid-audio'], [5, 'service-error'], + [6, 'empty'], [7, 'timeout'], [8, 'timeout'], [10, 'empty'], [11, 'quota-exceeded'], +]) +/** `biz_code` of a successful recognition, of a classified failure, and of an earlier failed task to resubmit. */ +const BIZ_SUCCESS = 0, BIZ_FAILED = 2, BIZ_RESUBMIT = 3 + +const envelope = z.object({ code: z.number(), data: z.object({ biz_code: z.number(), biz_data: z.unknown() }).nullish() }) +const recognized = z.object({ text: z.string() }) +const refused = z.object({ code: z.number() }) + +class ResponseTooLarge extends Error {} + +/** + * Send one request; the caller's abort propagates, while timeouts and transport failures become outcomes. + * @param request - endpoint, encoded body, and authentication headers. + * @param signal - caller cancellation. + * @returns the classified outcome. + */ +export async function attemptTranscription(request: AttemptRequest, signal: AbortSignal): Promise { + const timeout = AbortSignal.timeout(request.timeoutMs) + const combined = AbortSignal.any([signal, timeout]) + let text: string, status: number + try { + const response = await fetch(request.endpoint, { method: 'POST', body: request.body, redirect: 'error', signal: combined, + headers: { ...request.headers, 'content-type': request.contentType } }) + status = response.status + text = await readBounded(response, request.maxResponseBytes) + } catch (error) { + signal.throwIfAborted() + if (error instanceof ResponseTooLarge) return { kind: 'failed', code: 'service-error', diagnostic: error.message } + return timeout.aborted ? { kind: 'retryable', code: 'timeout', diagnostic: `no response within ${request.timeoutMs} ms` } + : { kind: 'retryable', code: 'service-error', diagnostic: `request failed: ${String(error)}` } + } + return classify(status, text) +} + +async function readBounded(response: Response, limit: number): Promise { + const chunks: Uint8Array[] = [] + let total = 0 + for await (const chunk of response.body ?? []) { + total += chunk.byteLength + if (total > limit) throw new ResponseTooLarge(`response exceeds ${limit} bytes`) + chunks.push(chunk) + } + return Buffer.concat(chunks).toString('utf8') +} + +function classify(status: number, text: string): AttemptOutcome { + if (status === 401) return { kind: 'credentials-rejected', diagnostic: 'HTTP 401' } + if (status === 429) return { kind: 'failed', code: 'rate-limited', diagnostic: 'HTTP 429' } + if (status >= 500) return { kind: 'retryable', code: 'service-error', diagnostic: `HTTP ${status}` } + if (status !== 200) return { kind: 'failed', code: 'service-error', diagnostic: `HTTP ${status}` } + let json: unknown + try { json = JSON.parse(text) } catch (_notJson) { + // A gateway page or truncated body is not a recognition result; its content stays out of diagnostics. + return { kind: 'failed', code: 'service-error', diagnostic: 'response is not JSON' } + } + const outer = envelope.safeParse(json) + if (!outer.success) return { kind: 'failed', code: 'service-error', diagnostic: 'response envelope is invalid' } + const { code, data } = outer.data + if (TOKEN_REJECTED.has(code)) return { kind: 'credentials-rejected', diagnostic: `code ${code}` } + if (code !== 0 || data == null) return { kind: 'failed', code: 'service-error', diagnostic: `code ${code}` } + if (data.biz_code === BIZ_SUCCESS) { + const result = recognized.safeParse(data.biz_data) + return result.success ? { kind: 'text', text: result.data.text } : { kind: 'failed', code: 'service-error', diagnostic: 'recognition result is invalid' } + } + if (data.biz_code === BIZ_RESUBMIT) return { kind: 'retryable', code: 'service-error', diagnostic: `biz_code ${BIZ_RESUBMIT}` } + const failure = data.biz_code === BIZ_FAILED ? refused.safeParse(data.biz_data) : undefined + if (failure?.success !== true) return { kind: 'failed', code: 'service-error', diagnostic: `biz_code ${data.biz_code}` } + const mapped = RECOGNITION_FAILURES.get(failure.data.code) ?? 'service-error' + return mapped === 'empty' ? { kind: 'text', text: '' } + : { kind: 'failed', code: mapped, diagnostic: `biz_code ${BIZ_FAILED}, code ${failure.data.code}` } +} diff --git a/packages/experimental/speech-to-text-deepseek/tests/availability.spec.ts b/packages/experimental/speech-to-text-deepseek/tests/availability.spec.ts new file mode 100644 index 0000000000..ee297b479a --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tests/availability.spec.ts @@ -0,0 +1,33 @@ +/** Latest-wins readiness inspections, failure publication, and disposal. */ +import { expect, it } from 'vitest' +import type { SpeechPreparationState } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import { CloudReadiness } from '../src/availability.ts' + +it('publishes only the latest inspection and nothing after disposal', async () => { + const pending: ((state: SpeechPreparationState) => void)[] = [] + const readiness = new CloudReadiness(() => new Promise((resolve) => { pending.push(resolve) })) + const seen: SpeechPreparationState[] = [] + const unsubscribe = readiness.subscribe(() => { seen.push(readiness.snapshot()) }) + expect(readiness.snapshot()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) + const first = readiness.refresh(), second = readiness.refresh() + pending[1]!({ phase: 'ready' }); await second + pending[0]!({ phase: 'failed', message: 'stale' }); await first + expect(seen).toEqual([{ phase: 'ready' }]) + unsubscribe() + const third = readiness.refresh() + pending[2]!({ phase: 'unavailable', reason: 'sign-in-required' }); await third + expect(seen).toHaveLength(1) + readiness.dispose() + const fourth = readiness.refresh() + pending[3]!({ phase: 'failed', message: 'late' }); await fourth + expect(readiness.snapshot()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) +}) + +it('publishes inspection failures as failed readiness', async () => { + const errors = [new Error('credential store locked'), 'store offline'] + const readiness = new CloudReadiness(async () => { throw errors.shift() }) + await readiness.account(true) + expect(readiness.snapshot()).toEqual({ phase: 'failed', message: 'credential store locked' }) + await readiness.refresh() + expect(readiness.snapshot()).toEqual({ phase: 'failed', message: 'store offline' }) +}) diff --git a/packages/experimental/speech-to-text-deepseek/tests/payload.spec.ts b/packages/experimental/speech-to-text-deepseek/tests/payload.spec.ts new file mode 100644 index 0000000000..6f1993db7b --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tests/payload.spec.ts @@ -0,0 +1,57 @@ +/** Endpoint validation, credential names, schema defaults, PCM alignment, and multipart encoding. */ +import { describe, expect, it } from 'vitest' +import { multipartBody, pcmPayload } from '../src/audio.ts' +import { Config, resolveOptions } from '../src/config.ts' +import { wave } from './service-double.ts' + +describe('configuration', () => { + it('defaults to the production endpoint and the service limits', () => { + const options = resolveOptions(Config({})) + expect(options).toMatchObject({ providerId: 'deepseek-asr', timeoutMs: 30_000, + maxRequestBytes: 3_932_160, maxDurationSeconds: 120, maxResponseBytes: 65_536, + languages: ['auto', 'zh', 'en', 'ja', 'es', 'fr', 'de', 'ru', 'pt', 'yue', 'ko'] }) + expect(options.endpoint.href).toBe('https://harness.deepseek.com/api/v0/asr/transcribe') + }) + + it('requires automatic detection among the configured languages', () => { + expect(() => resolveOptions(Config({ endpoint: 'https://api.example/asr', languages: ['zh'] }))).toThrow('must include `auto`') + expect(() => Config({ endpoint: 'https://api.example/asr', languages: ['zh-CN'] })).toThrow() + }) + + it('sends tokens only over HTTPS or explicitly allowed loopback HTTP', () => { + for (const endpoint of ['https://user:pass@api.example/asr', 'https://api.example/asr?x=1', 'https://api.example/asr#f']) { + expect(() => resolveOptions(Config({ endpoint }))).toThrow('credentials, a query or a fragment') + } + expect(() => resolveOptions(Config({ endpoint: 'http://api.example/asr', allowLoopbackHttp: true }))).toThrow('HTTPS') + expect(() => resolveOptions(Config({ endpoint: 'http://127.0.0.1:9/asr' }))).toThrow('HTTPS') + expect(resolveOptions(Config({ endpoint: 'http://127.0.0.1:9/asr', allowLoopbackHttp: true })).endpoint.origin).toBe('http://127.0.0.1:9') + expect(() => resolveOptions(Config({ endpoint: 'not a url' }))).toThrow() + }) +}) + +describe('audio payload', () => { + it('strips the WAV header and zero-pads samples to 32 bytes', () => { + const { pcm, seconds } = pcmPayload(wave(93_502), 120) + expect(pcm.byteLength).toBe(93_504) + expect(seconds).toBeCloseTo(93_502 / 32_000) + expect([...pcm.subarray(0, 3)]).toEqual([0, 1, 2]) + expect([...pcm.subarray(93_502)]).toEqual([0, 0]) + expect(pcmPayload(wave(64), 120).pcm.byteLength).toBe(64) + }) + + it('classifies malformed and overlong recordings as invalid audio', () => { + expect(() => pcmPayload(new Uint8Array(10), 120)).toThrow(expect.objectContaining({ code: 'invalid-audio' })) + expect(() => pcmPayload(wave(64_000), 1)).toThrow(expect.objectContaining({ code: 'invalid-audio', message: 'Audio exceeds 1 seconds' })) + }) + + it('encodes fields and the file as standard multipart form data', async () => { + const bytes = new Uint8Array([0, 13, 10, 45, 45, 255]) + const { body, contentType } = multipartBody([['format', 'pcm'], ['audio_id', 'id-1']], { name: 'file', filename: 'recording.pcm', bytes }) + const form = await new Response(body, { headers: { 'content-type': contentType } }).formData() + expect(form.get('format')).toBe('pcm') + expect(form.get('audio_id')).toBe('id-1') + const file = form.get('file') + expect(file).toBeInstanceOf(File) + expect(new Uint8Array(await (file as File).arrayBuffer())).toEqual(bytes) + }) +}) diff --git a/packages/experimental/speech-to-text-deepseek/tests/provider.spec.ts b/packages/experimental/speech-to-text-deepseek/tests/provider.spec.ts new file mode 100644 index 0000000000..7a051dbd0c --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tests/provider.spec.ts @@ -0,0 +1,229 @@ +/** Registration, account-driven readiness and authentication, retries, and disposal of the cloud recognizer. */ +import { Context } from '@deepseek-ai/cordis' +import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import type { AccountView } from '@deepseek-ai/dsh-deepseek-account/types' +import SpeechToText, { SpeechTranscriptionError } from '@deepseek-ai/dsh-experimental-speech-to-text' +import type { SpeechPreparationState, SpeechProviderId } from '@deepseek-ai/dsh-experimental-speech-to-text/types' +import { expect, it, onTestFinished, vi } from 'vitest' +import * as Provider from '../src/index.ts' +import { json, recognized, refused, serviceDouble, wave, type Reply } from './service-double.ts' + +const id = 'deepseek-asr' as SpeechProviderId + +/** Account service double whose stored-account state the test switches. */ +function account(initial: AccountView['status'], token: string | null = 'fixture-account-token') { + let status = initial + const wake = new Set<() => void>() + const rejected: string[] = [] + const service = { + async *watch(signal: AbortSignal): AsyncIterable { + while (!signal.aborted) { + yield { status, links: { usageUrl: '', topUpUrl: '' }, attempt: null } + await new Promise((resolve) => { wake.add(resolve); signal.addEventListener('abort', () => { resolve() }, { once: true }) }) + } + }, + resolveToken: vi.fn(async () => status === 'credential-stored' ? token ?? undefined : undefined), + rejectToken: vi.fn(async (value: string) => { rejected.push(value); set('signed-out') }), + } + function set(next: AccountView['status']): void { + status = next + for (const resolve of wake) resolve() + wake.clear() + } + return { service: service as Partial as DeepSeekAccount, rejectToken: service.rejectToken, rejected, set } +} + +/** Await a classified recognition failure so its code and diagnostic can be checked separately. */ +async function rejection(pending: Promise): Promise { + try { await pending } catch (error) { + if (error instanceof SpeechTranscriptionError) return error + throw error + } + throw new Error('expected a classified recognition failure') +} + +async function host(setup: { account?: DeepSeekAccount } = {}) { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin(SpeechToText, { defaultProvider: 'auto', autoOrder: [id], language: 'zh' }) + const removeAccount = setup.account === undefined ? undefined : ctx.provide('deepseekAccount', setup.account) + const speech = ctx.get('speechToText')! + const state = (): SpeechPreparationState | undefined => speech.snapshot().providers.find(row => row.id === id)?.preparation + return { ctx, speech, state, removeAccount } +} + +async function mount(ctx: Context, endpoint: string, config: object = {}) { + const fiber = ctx.plugin(Provider, { endpoint, allowLoopbackHttp: true, ...config }) + await fiber + return fiber +} + +async function dictate(speech: SpeechToText, pcmBytes = 100) { + return await speech.transcribe(speech.resolve({ audio: wave(pcmBytes) }), new AbortController().signal) +} + +it('sends aligned PCM with the account token once a DeepSeek account is stored', async () => { + const { endpoint, requests } = await serviceDouble(recognized('你好')) + const { ctx, speech, state } = await host({ account: account('credential-stored').service }) + await mount(ctx, endpoint) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + expect(speech.snapshot().providers[0]).toMatchObject({ name: 'DeepSeek', location: 'cloud', + languages: ['auto', 'zh', 'en', 'ja', 'es', 'fr', 'de', 'ru', 'pt', 'yue', 'ko'] }) + expect(await dictate(speech)).toMatchObject({ text: '你好', audioSeconds: 100 / 32_000 }) + const [sent] = requests + expect(sent!.headers['x-dsh-auth-token']).toBe('fixture-account-token') + expect(sent!.headers.cookie).toBeUndefined() + expect(sent!.headers['x-client-locale']).toBeUndefined() + expect(sent!.fields.get('format')).toBe('pcm') + expect(sent!.fields.get('audio_id')).toMatch(/^[0-9a-f-]{36}$/) + expect(sent!.fields.get('preferred_language')).toBe('zh') + expect(sent!.file.byteLength).toBe(128) +}) + +it('sends the preferred language and the client locale in the service spelling', async () => { + const { endpoint, requests } = await serviceDouble(recognized('ok')) + const { ctx, speech, state } = await host({ account: account('credential-stored').service }) + await mount(ctx, endpoint, { languages: ['auto', 'es', 'es'] }) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + expect(speech.snapshot().providers[0]!.languages).toEqual(['auto', 'es']) + for (const [language, locale] of [['es', 'zh'], ['auto', 'pt-BR'], ['es', 'zh-Hant'], ['es', 'en'], ['es', 'pt'], ['es', 'ja']] as const) { + await speech.transcribe(speech.resolve({ audio: wave(64), language, locale }), new AbortController().signal) + } + expect(requests.map(request => [request.fields.get('preferred_language') ?? null, request.headers['x-client-locale']])).toEqual([ + ['es', 'zh_CN'], [null, 'pt_BR'], ['es', 'zh_Hant'], ['es', 'en_US'], ['es', 'pt_BR'], ['es', 'ja'], + ]) + expect(() => speech.resolve({ audio: wave(64), language: 'zh' })).toThrow('No registered speech provider supports language: zh') +}) + +it('follows sign-in without contacting the service and offers nothing to prepare', async () => { + const { endpoint, requests } = await serviceDouble(recognized('ok')) + const user = account('signed-out') + const { ctx, speech, state } = await host({ account: user.service }) + await mount(ctx, endpoint) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) }) + await expect(dictate(speech)).rejects.toMatchObject({ code: 'sign-in-required' }) + user.set('credential-stored') + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + speech.prepare(id) + await speech.cancelPreparation(id) + expect(state()).toEqual({ phase: 'ready' }) + expect(requests).toHaveLength(0) +}) + +it('resubmits the same audio_id once after a service failure and classifies the final outcome', async () => { + const unavailable: Reply = json(503, {}) + const { endpoint, requests } = await serviceDouble(unavailable, recognized('retried')) + const { ctx, speech, state } = await host({ account: account('credential-stored').service }) + await mount(ctx, endpoint) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + expect((await dictate(speech)).text).toBe('retried') + expect(requests.map(request => request.fields.get('audio_id'))).toEqual([requests[0]!.fields.get('audio_id'), requests[0]!.fields.get('audio_id')]) + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + const again = await serviceDouble(unavailable) + const second = await host({ account: account('credential-stored').service }) + await mount(second.ctx, again.endpoint) + await vi.waitFor(() => { expect(second.state()).toEqual({ phase: 'ready' }) }) + await expect(dictate(second.speech)).rejects.toMatchObject({ code: 'service-error', message: 'Cloud recognition failed: HTTP 503' }) + expect(again.requests).toHaveLength(2) + expect(errors).toHaveBeenCalledWith('[speech-to-text-deepseek]', '/api/v0/asr/transcribe failed (service-error): HTTP 503') + errors.mockRestore() +}) + +it('does not retry classified failures and rejects oversized requests before sending', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { endpoint, requests } = await serviceDouble(refused(2)) + const { ctx, speech, state } = await host({ account: account('credential-stored').service }) + await mount(ctx, endpoint, { maxRequestBytes: 1000 }) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + await expect(dictate(speech)).rejects.toMatchObject({ code: 'rate-limited' }) + expect(requests).toHaveLength(1) + const oversized = await rejection(dictate(speech, 2000)) + expect(oversized.code).toBe('invalid-audio') + expect(oversized.message).toContain('the service accepts 1000') + await expect(speech.transcribe(speech.resolve({ audio: new Uint8Array(8) }), new AbortController().signal)) + .rejects.toMatchObject({ code: 'invalid-audio' }) + expect(requests).toHaveLength(1) +}) + +it('authenticates with the account token and invalidates exactly that token when the service rejects it', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { endpoint } = await serviceDouble(recognized('账号'), json(200, { code: 40003, msg: 'INVALID_TOKEN', data: null })) + const user = account('credential-stored') + const { ctx, speech, state } = await host({ account: user.service }) + await mount(ctx, endpoint) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + expect((await dictate(speech)).text).toBe('账号') + const expired = await rejection(dictate(speech)) + expect(expired.code).toBe('sign-in-required') + expect(expired.message).toContain('code 40003') + expect(user.rejected).toEqual(['fixture-account-token']) + expect(errors).toHaveBeenCalledWith('[speech-to-text-deepseek]', '/api/v0/asr/transcribe rejected the account token: code 40003') + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) }) + await expect(dictate(speech)).rejects.toMatchObject({ code: 'sign-in-required' }) +}) + +it('keeps the service rejection when invalidating the account token fails', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { endpoint } = await serviceDouble(json(401, {})) + const user = account('credential-stored') + user.rejectToken.mockRejectedValueOnce(new Error('keychain locked')) + const { ctx, speech, state } = await host({ account: user.service }) + await mount(ctx, endpoint) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + await expect(dictate(speech)).rejects.toMatchObject({ code: 'sign-in-required' }) +}) + +it('fails readiness and refuses recordings when a stored account does not authorize the endpoint origin', async () => { + const { endpoint, requests } = await serviceDouble(recognized('ok')) + const { ctx, speech, state } = await host({ account: account('credential-stored', null).service }) + await mount(ctx, endpoint) + await vi.waitFor(() => { + expect(state()).toEqual({ phase: 'failed', message: `The DeepSeek account does not release a token for ${new URL(endpoint).origin}` }) + }) + await expect(speech.transcribe(speech.resolve({ audio: wave(64), providerId: id }), new AbortController().signal)) + .rejects.toMatchObject({ code: 'sign-in-required' }) + expect(requests).toHaveLength(0) +}) + +it('requires sign-in without an account service and recovers when one appears or fails', async () => { + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { errors.mockRestore() }) + const { endpoint } = await serviceDouble(recognized('ok')) + const { ctx, state } = await host() + await mount(ctx, endpoint) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) }) + const removeAccount = ctx.provide('deepseekAccount', account('credential-stored').service) + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'ready' }) }) + removeAccount() + await vi.waitFor(() => { expect(state()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) }) + let watched = 0 + const failing = (failure: unknown) => ({ watch: (signal: AbortSignal) => (watched++, { [Symbol.asyncIterator]: () => ({ + next: () => failure === undefined + ? new Promise>((_resolve, reject) => { signal.addEventListener('abort', () => { reject(new Error('aborted')) }) }) + // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- covers an account stream rejecting with a non-Error reason + : Promise.reject(failure), + }) }) }) as Partial as DeepSeekAccount + const removeHanging = ctx.provide('deepseekAccount', failing(undefined)) + await vi.waitFor(() => { expect(watched).toBe(1) }) + removeHanging() + for (const [failure, message] of [[new Error('stream closed'), 'stream closed'], ['socket reset', 'socket reset']] as const) { + const remove = ctx.provide('deepseekAccount', failing(failure)) + await vi.waitFor(() => { expect(errors).toHaveBeenCalledWith('[speech-to-text-deepseek]', 'account observation failed:', message) }) + expect(state()).toEqual({ phase: 'unavailable', reason: 'sign-in-required' }) + remove() + } + expect(errors).toHaveBeenCalledTimes(2) +}) + +it('withdraws the registration and stops publishing when the plugin unloads', async () => { + const { endpoint } = await serviceDouble(recognized('ok')) + const { ctx, speech } = await host({ account: account('credential-stored').service }) + const fiber = await mount(ctx, endpoint) + expect(speech.listProviders().map(row => row.id)).toEqual([id]) + await fiber.dispose() + expect(speech.listProviders()).toEqual([]) + expect(() => speech.resolve({ audio: wave(100) })).toThrow('unavailable') +}) diff --git a/packages/experimental/speech-to-text-deepseek/tests/request.spec.ts b/packages/experimental/speech-to-text-deepseek/tests/request.spec.ts new file mode 100644 index 0000000000..656fcaa52f --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tests/request.spec.ts @@ -0,0 +1,78 @@ +/** One attempt's HTTP and envelope classification, bounds, timeouts, and caller cancellation. */ +import { createServer } from 'node:http' +import { describe, expect, it } from 'vitest' +import { attemptTranscription, type AttemptRequest } from '../src/request.ts' +import { json, recognized, refused, serviceDouble, silent, type Reply } from './service-double.ts' + +const body = new Uint8Array(new ArrayBuffer(4)) +function request(endpoint: string, overrides: Partial = {}): AttemptRequest { + return { endpoint: new URL(endpoint), body, contentType: 'application/octet-stream', headers: { 'x-dsh-auth-token': 't' }, + timeoutMs: 2000, maxResponseBytes: 64 * 1024, ...overrides } +} +async function outcome(reply: Reply, overrides: Partial = {}) { + const { endpoint } = await serviceDouble(reply) + return await attemptTranscription(request(endpoint, overrides), new AbortController().signal) +} +const raw = (status: number, text: string): Reply => (_request, response) => { response.writeHead(status).end(text) } + +describe('attempt classification', () => { + it('returns recognized text and treats no-speech codes as empty text', async () => { + expect(await outcome(recognized('你好'))).toEqual({ kind: 'text', text: '你好' }) + expect(await outcome(refused(6))).toEqual({ kind: 'text', text: '' }) + expect(await outcome(refused(10))).toEqual({ kind: 'text', text: '' }) + }) + + it('maps classified recognition failures', async () => { + for (const [code, failure] of [[1, 'service-unavailable'], [2, 'rate-limited'], [3, 'service-error'], [4, 'invalid-audio'], + [5, 'service-error'], [7, 'timeout'], [8, 'timeout'], [11, 'quota-exceeded'], [99, 'service-error']] as const) { + expect(await outcome(refused(code))).toEqual({ kind: 'failed', code: failure, diagnostic: `biz_code 2, code ${code}` }) + } + }) + + it('distinguishes credential rejection, rate limits, and retryable service failures', async () => { + expect(await outcome(json(401, { error: { code: 'UNAUTHENTICATED' } }))).toEqual({ kind: 'credentials-rejected', diagnostic: 'HTTP 401' }) + expect(await outcome(json(200, { code: 40003, msg: 'INVALID_TOKEN', data: null }))).toEqual({ kind: 'credentials-rejected', diagnostic: 'code 40003' }) + expect(await outcome(json(200, { code: 40002, msg: 'Missing Token', data: null }))).toMatchObject({ kind: 'credentials-rejected' }) + expect(await outcome(raw(429, ''))).toEqual({ kind: 'failed', code: 'rate-limited', diagnostic: 'HTTP 429' }) + expect(await outcome(raw(503, ''))).toEqual({ kind: 'retryable', code: 'service-error', diagnostic: 'HTTP 503' }) + expect(await outcome(json(200, { code: 0, data: { biz_code: 3, biz_data: null } }))).toEqual({ kind: 'retryable', code: 'service-error', diagnostic: 'biz_code 3' }) + }) + + it('rejects unexpected statuses and malformed envelopes without echoing the body', async () => { + const failed = (diagnostic: string) => ({ kind: 'failed', code: 'service-error', diagnostic }) + expect(await outcome(raw(404, ''))).toEqual(failed('HTTP 404')) + expect(await outcome(raw(204, ''))).toEqual(failed('HTTP 204')) + expect(await outcome(raw(200, 'secret'))).toEqual(failed('response is not JSON')) + expect(await outcome(json(200, { data: {} }))).toEqual(failed('response envelope is invalid')) + expect(await outcome(json(200, { code: 5, data: null }))).toEqual(failed('code 5')) + expect(await outcome(json(200, { code: 0 }))).toEqual(failed('code 0')) + expect(await outcome(json(200, { code: 0, data: { biz_code: 0, biz_data: { text: 1 } } }))).toEqual(failed('recognition result is invalid')) + expect(await outcome(json(200, { code: 0, data: { biz_code: 2, biz_data: null } }))).toEqual(failed('biz_code 2')) + expect(await outcome(json(200, { code: 0, data: { biz_code: 7, biz_data: null } }))).toEqual(failed('biz_code 7')) + }) + + it('bounds the response body', async () => { + expect(await outcome(recognized('x'.repeat(200)), { maxResponseBytes: 100 })) + .toEqual({ kind: 'failed', code: 'service-error', diagnostic: 'response exceeds 100 bytes' }) + }) + + it('turns deadlines and transport failures into retryable outcomes', async () => { + expect(await outcome(silent, { timeoutMs: 50 })).toEqual({ kind: 'retryable', code: 'timeout', diagnostic: 'no response within 50 ms' }) + const closed = createServer() + await new Promise((resolve) => { closed.listen(0, '127.0.0.1', resolve) }) + const address = closed.address() + await new Promise((resolve) => { closed.close(() => { resolve() }) }) + const port = typeof address === 'object' && address !== null ? address.port : 0 + const refused = await attemptTranscription(request(`http://127.0.0.1:${port}/asr`), new AbortController().signal) + expect(refused).toMatchObject({ kind: 'retryable', code: 'service-error' }) + expect('diagnostic' in refused && refused.diagnostic).toMatch(/^request failed: TypeError: /) + }) + + it('propagates caller cancellation instead of classifying it', async () => { + const { endpoint } = await serviceDouble(silent) + const caller = new AbortController() + const pending = attemptTranscription(request(endpoint), caller.signal) + caller.abort(new Error('dictation cancelled')) + await expect(pending).rejects.toThrow('dictation cancelled') + }) +}) diff --git a/packages/experimental/speech-to-text-deepseek/tests/service-double.ts b/packages/experimental/speech-to-text-deepseek/tests/service-double.ts new file mode 100644 index 0000000000..57ce5cce18 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tests/service-double.ts @@ -0,0 +1,86 @@ +/** Loopback double of the One-Shot endpoint and canonical WAV recordings for provider specs. */ +import { createServer, type IncomingHttpHeaders, type ServerResponse } from 'node:http' +import { onTestFinished } from 'vitest' + +/** One request as the service received it. */ +export interface RecordedRequest { + readonly headers: IncomingHttpHeaders + readonly fields: ReadonlyMap + readonly file: Uint8Array +} + +/** Response behavior for one request; the last reply repeats for later requests. */ +export type Reply = (request: RecordedRequest, response: ServerResponse) => void + +/** + * Start a listener owned by the current test. + * @param replies - responses in request order. + * @returns the endpoint URL and the recorded requests. + */ +export async function serviceDouble(...replies: Reply[]): Promise<{ endpoint: string; requests: RecordedRequest[] }> { + const requests: RecordedRequest[] = [] + const server = createServer((request, response) => { + const chunks: Buffer[] = [] + request.on('data', (chunk: Buffer) => { chunks.push(chunk) }) + request.on('end', () => { + void (async () => { + const body = Buffer.concat(chunks), type = request.headers['content-type'] ?? '' + const fields = new Map() + let file = new Uint8Array(body) + if (type.startsWith('multipart/form-data')) { + for (const [name, value] of await new Response(body, { headers: { 'content-type': type } }).formData()) { + if (typeof value === 'string') fields.set(name, value) + else file = new Uint8Array(await value.arrayBuffer()) + } + } + const recorded = { headers: request.headers, fields, file } + requests.push(recorded) + replies[Math.min(requests.length, replies.length) - 1]!(recorded, response) + })() + }) + }) + await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) + onTestFinished(() => new Promise((resolve) => { server.closeAllConnections(); server.close(() => { resolve() }) })) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('service double: missing listener address') + return { endpoint: `http://127.0.0.1:${address.port}/api/v0/asr/transcribe`, requests } +} + +/** + * @param status - HTTP status. + * @param body - JSON body. + * @returns a reply sending the JSON body. + */ +export const json = (status: number, body: unknown): Reply => (_request, response) => { + response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body)) +} + +/** + * @param text - recognized text. + * @returns a successful recognition reply. + */ +export const recognized = (text: string): Reply => json(200, { code: 0, msg: '', data: { biz_code: 0, biz_msg: '', biz_data: { text, audio_id: 'echo' } } }) + +/** + * @param code - `biz_data.code` of the failed recognition. + * @returns a classified recognition failure reply. + */ +export const refused = (code: number): Reply => json(200, { code: 0, msg: '', data: { biz_code: 2, biz_msg: 'asr failed', biz_data: { code, toast: 'x', audio_id: 'echo' } } }) + +/** A reply that never answers; the listener closes the socket at teardown. */ +export const silent: Reply = () => {} + +/** + * Build a canonical 16 kHz mono PCM16 WAV recording. + * @param pcmBytes - sample bytes after the 44-byte header. + * @returns WAV bytes whose samples are a repeating ramp. + */ +export function wave(pcmBytes: number): Uint8Array { + const data = Buffer.alloc(44 + pcmBytes) + data.write('RIFF'); data.writeUInt32LE(data.length - 8, 4); data.write('WAVEfmt ', 8) + data.writeUInt32LE(16, 16); data.writeUInt16LE(1, 20); data.writeUInt16LE(1, 22) + data.writeUInt32LE(16000, 24); data.writeUInt32LE(32000, 28); data.writeUInt16LE(2, 32) + data.writeUInt16LE(16, 34); data.write('data', 36); data.writeUInt32LE(pcmBytes, 40) + for (let index = 0; index < pcmBytes; index++) data[44 + index] = index % 251 + return new Uint8Array(data) +} diff --git a/packages/experimental/speech-to-text-deepseek/tsconfig.json b/packages/experimental/speech-to-text-deepseek/tsconfig.json new file mode 100644 index 0000000000..68e6da94fe --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/timeout" + }, + { + "path": "../../util/values" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../credentials/deepseek-account" + }, + { + "path": "../speech-to-text" + } + ] +} diff --git a/packages/experimental/speech-to-text-deepseek/tsdown.config.ts b/packages/experimental/speech-to-text-deepseek/tsdown.config.ts new file mode 100644 index 0000000000..be29690579 --- /dev/null +++ b/packages/experimental/speech-to-text-deepseek/tsdown.config.ts @@ -0,0 +1,3 @@ +import { defineConfig } from 'tsdown' + +export default defineConfig({ entry: ['lib/types/index.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', fixedExtension: false, dts: false, clean: false }) diff --git a/packages/experimental/speech-to-text/README.i18n.yaml b/packages/experimental/speech-to-text/README.i18n.yaml index 5149d7e2ea..fdf9459317 100644 --- a/packages/experimental/speech-to-text/README.i18n.yaml +++ b/packages/experimental/speech-to-text/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 364c80ee00a374ff /deepseek-ai-dsh-experimental-speech-to-text/use-this-package: - en: faf7c49d8870eaad - zh: 9c1c42eba9660f75 + en: 70fb6f67f4e49e4a + zh: 39b4497887d90bd6 /deepseek-ai-dsh-experimental-speech-to-text/understand-the-implementation: - en: 2b1648ac92551bc0 - zh: 41c5a2405711d7c2 + en: 16c805e00cdbe72c + zh: 60842fb4425a0a7c /deepseek-ai-dsh-experimental-speech-to-text/further-exploration: en: 5c64426add9d79d6 zh: 4e06aa2ead8d2ccd diff --git a/packages/experimental/speech-to-text/README.md b/packages/experimental/speech-to-text/README.md index afaa0089dc..be82271967 100644 --- a/packages/experimental/speech-to-text/README.md +++ b/packages/experimental/speech-to-text/README.md @@ -25,10 +25,12 @@ This Service Definition selects named speech recognizers through `ctx.speechToTe ## Use this package -Load through the [voice input bundle](../voice-input-bundle/README.md), or compose the service with a provider and consumer. `defaultProvider` is required and selects an exact registered id; the bundle supplies `sensevoice-local`. `language` supplies the omitted language hint. A missing or duplicate provider fails explicitly. +Load through the [voice input bundle](../voice-input-bundle/README.md), or compose the service with a provider and consumer. `defaultProvider` is required and selects an exact registered id, or `auto`; the bundle supplies `auto` with `autoOrder: [deepseek-asr, sensevoice-local]`. Automatic selection takes the first registered `autoOrder` provider that is not `unavailable`, otherwise the first registered one so that its state explains the refusal; the choice is made before recording and never replaces a provider after a failure. `language` supplies the omitted language hint; it must be listed by at least one registered provider, and a provider that does not list it receives `auto`, so one saved hint serves every provider. Every provider must list `auto`. `locale` carries the client's UI language to the provider unchanged. A missing or duplicate provider, an `auto` preference without `autoOrder`, and a provider registering the reserved id `auto` fail explicitly. Providers advertise preparation origins through `downloadSources`. `prepare(id, options)` forwards an optional `downloadSource` for one task; the provider validates the choice and refuses source changes during active preparation. Omission retains provider policy. Source choices are not persisted recognition preferences. +Providers publish readiness as `SpeechPreparationState`; `unavailable` with `sign-in-required` marks a provider that refuses recordings until the user signs in to DeepSeek. Expected recognition failures throw `SpeechTranscriptionError`, whose `SpeechFailureCode` Consumers localize; its message stays a Host diagnostic. + ----- @@ -39,7 +41,7 @@ Providers advertise preparation origins through `downloadSources`. `prepare(id, `resolve()` captures the provider instance, recording and language. `transcribe()` rejects a withdrawn or replaced registration. A registration disposer closes admission, aborts accepted requests and joins provider settlement; providers must honor cancellation. No fallback selects a different recognizer or uploads audio. -`defaultProvider` and `language` are volatile Config fields: `configure()` writes the supplied fields into this plugin's profile entry through the `settings` service, and the running instance reads the updated values without remounting; composition defaults apply until an override is saved. Settings addresses the entry by its configured id (`entry.options.id`), without the Loader's Include path. `configure()` fails without `settings` or a profile entry, and rejects a language unsupported by the selected provider before saving. Providers advertise accepted language hints through `languages`; `resolve()` validates the selected hint before transcription. Provider-owned preparation is observed through complete `SpeechSnapshot` values; closing an observer never cancels preparation. +`defaultProvider` and `language` are volatile Config fields: `configure()` writes the supplied fields into this plugin's profile entry through the `settings` service, and the running instance reads the updated values without remounting; composition defaults apply until an override is saved. Settings addresses the entry by its configured id (`entry.options.id`), without the Loader's Include path. `configure()` fails without `settings` or a profile entry, and rejects, before saving, a language the selected provider does not accept; under `auto`, every registered `autoOrder` provider that accepts hints must accept it. Providers advertise accepted language hints through `languages`; `resolve()` validates the selected hint before transcription. Provider-owned preparation is observed through complete `SpeechSnapshot` values; closing an observer never cancels preparation. The `./wave` helper validates canonical 16 kHz mono PCM16 WAV for the Remote consumer and the native recognition process. Both reject inconsistent headers and lengths before decoding samples. diff --git a/packages/experimental/speech-to-text/README.zh.md b/packages/experimental/speech-to-text/README.zh.md index a613480e0d..c65ac93737 100644 --- a/packages/experimental/speech-to-text/README.zh.md +++ b/packages/experimental/speech-to-text/README.zh.md @@ -25,10 +25,12 @@ kind: "package-reference" ## 使用此包 -通过[语音输入 Bundle](../voice-input-bundle/README.zh.md)加载,或组合此服务、Provider 与消费者。`defaultProvider` 为必填项,选择确切的注册 id;Bundle 提供 `sensevoice-local`。`language` 提供省略的语言提示。缺失或重复的 Provider 会明确报错。 +通过[语音输入 Bundle](../voice-input-bundle/README.zh.md)加载,或组合此服务、Provider 与消费者。`defaultProvider` 为必填项,选择确切的注册 id 或 `auto`;Bundle 提供 `auto`,并配置 `autoOrder: [deepseek-asr, sensevoice-local]`。自动选择取 `autoOrder` 中第一个已注册且状态不是 `unavailable` 的 Provider;都不可用时取第一个已注册的 Provider,由它的状态说明拒绝原因。选择在录音前确定,失败后也不会换用其他 Provider。`language` 提供省略的语言提示;提示必须至少被一个已注册的 Provider 列出;未列出该提示的 Provider 收到 `auto`,因此一份保存的提示适用于所有 Provider。每个 Provider 都必须列出 `auto`。`locale` 把客户端的界面语言原样传给 Provider。缺失或重复的 Provider、没有 `autoOrder` 的 `auto` 偏好,以及注册保留 id `auto` 的 Provider 都会明确报错。 提供方通过 `downloadSources` 公布准备阶段可用的源。`prepare(id, options)` 为单次任务转发可选的 `downloadSource`;提供方校验选择,并拒绝在准备期间改源。省略时沿用提供方策略。下载源选择不属于持久化的识别偏好。 +Provider 通过 `SpeechPreparationState` 发布就绪状态;带 `sign-in-required` 的 `unavailable` 表示在用户登录 DeepSeek 之前拒绝录音。可预期的识别失败抛出 `SpeechTranscriptionError`,消费者按其中的 `SpeechFailureCode` 本地化提示;错误消息只作为 Host 诊断信息。 + ----- @@ -39,7 +41,7 @@ kind: "package-reference" `resolve()` 捕获 Provider 实例、录音和语言。`transcribe()` 拒绝已撤销或替换的注册。注册的清理函数先拒绝新请求,再取消已接收的请求并等待 Provider 完成;Provider 必须响应取消。服务不会回退到其他识别器或上传音频。 -`defaultProvider` 与 `language` 是 volatile Config 字段:`configure()` 通过 `settings` 服务把传入的字段写入本插件的 profile 条目,运行中的实例无需重挂载即可读到更新值;保存覆盖值之前使用组合配置默认值。Settings 使用条目配置中的 id(`entry.options.id`)定位条目,不包含 Loader 的 Include 路径。没有 `settings` 或 profile 条目时 `configure()` 失败,并在保存前拒绝所选 Provider 不支持的语言。Provider 通过 `languages` 公布支持的语言提示;`resolve()` 在转写前校验所选提示。观察者通过完整 `SpeechSnapshot` 接收 Provider 拥有的准备状态;关闭观察者不会取消准备。 +`defaultProvider` 与 `language` 是 volatile Config 字段:`configure()` 通过 `settings` 服务把传入的字段写入本插件的 profile 条目,运行中的实例无需重挂载即可读到更新值;保存覆盖值之前使用组合配置默认值。Settings 使用条目配置中的 id(`entry.options.id`)定位条目,不包含 Loader 的 Include 路径。没有 `settings` 或 profile 条目时 `configure()` 失败,并在保存前拒绝所选 Provider 不支持的语言;选择 `auto` 时,`autoOrder` 中每个已注册且接受语言提示的 Provider 都必须支持该语言。Provider 通过 `languages` 公布支持的语言提示;`resolve()` 在转写前校验所选提示。观察者通过完整 `SpeechSnapshot` 接收 Provider 拥有的准备状态;关闭观察者不会取消准备。 `./wave` 辅助函数为 Remote 消费者与原生识别进程校验规范的 16 kHz 单声道 PCM16 WAV。两者均在解码采样前拒绝不一致的头部和长度。 diff --git a/packages/experimental/speech-to-text/src/failure.ts b/packages/experimental/speech-to-text/src/failure.ts new file mode 100644 index 0000000000..6c7d108fab --- /dev/null +++ b/packages/experimental/speech-to-text/src/failure.ts @@ -0,0 +1,16 @@ +/** Classified provider failures that Consumers report without parsing provider messages. */ +import type { SpeechFailureCode } from './types.ts' + +/** An expected recognition failure; its `code` selects localized guidance and `message` stays a Host diagnostic. */ +export class SpeechTranscriptionError extends Error { + override readonly name = 'SpeechTranscriptionError' + + /** + * @param code - failure class that Consumers localize. + * @param message - Host diagnostic without credentials or audio. + * @param options - optional underlying cause. + */ + constructor(readonly code: SpeechFailureCode, message: string, options?: ErrorOptions) { + super(message, options) + } +} diff --git a/packages/experimental/speech-to-text/src/index.ts b/packages/experimental/speech-to-text/src/index.ts index d88bf7aa39..b33bb79e21 100644 --- a/packages/experimental/speech-to-text/src/index.ts +++ b/packages/experimental/speech-to-text/src/index.ts @@ -5,9 +5,16 @@ import z from '@deepseek-ai/schemastery' // entry and `loader/volatile-update` merges. import type {} from '@deepseek-ai/dsh-settings' import type {} from '@deepseek-ai/cordis-plugin-loader' -import type { SpeechPreparationOptions, SpeechProvider, SpeechProviderId, SpeechProviderInfo, SpeechSnapshot, SpeechSelectionPatch, SpeechRequest, SpeechSpec, Transcript } from './types.ts' +import type { + SpeechPreparationOptions, SpeechProvider, SpeechProviderId, SpeechProviderInfo, SpeechSelection, SpeechSnapshot, SpeechSelectionPatch, + SpeechRequest, SpeechSpec, Transcript, +} from './types.ts' export type * from './types.ts' +export { SpeechTranscriptionError } from './failure.ts' + +/** Preference value that follows `autoOrder`; no provider may register it as an id. */ +const AUTO = 'auto' declare module '@deepseek-ai/cordis' { interface Context { @@ -18,8 +25,10 @@ declare module '@deepseek-ai/cordis' { /** Live selection read before a transcription starts; `configure()` writes it through the profile. */ export interface Config { - /** Registered provider selected when the caller omits an id. */ + /** Registered provider selected when the caller omits an id, or `auto` to follow `autoOrder`. */ defaultProvider: Volatile + /** Provider ids considered by automatic selection, in preference order; required while `defaultProvider` is `auto`. */ + autoOrder: string[] /** Provider language hint selected when the caller omits one. */ language: Volatile } @@ -35,6 +44,7 @@ interface Registration { export default class SpeechToText extends Service { static Config = z.object({ defaultProvider: z.string().min(1).required().volatile(), + autoOrder: z.array(z.string().min(1)).default([]), language: z.string().min(1).default('auto').volatile(), }) @@ -46,6 +56,10 @@ export default class SpeechToText extends Service { constructor(ctx: Context, private readonly config: Config) { super(ctx, 'speechToText') + if (config.autoOrder.includes(AUTO)) throw new Error('Speech autoOrder lists provider ids; `auto` is reserved') + if (config.defaultProvider.get() === AUTO && config.autoOrder.length === 0) { + throw new Error('Automatic speech provider selection requires a non-empty autoOrder') + } this.entryId = ctx.fiber.entry?.options.id ctx.on('loader/volatile-update', () => { this.changed() }) ctx.effect(() => async () => { @@ -62,6 +76,8 @@ export default class SpeechToText extends Service { */ register(provider: SpeechProvider): () => Promise { this.lifetime.signal.throwIfAborted() + if (provider.info.id === AUTO) throw new Error('Speech provider id `auto` is reserved for automatic selection') + if (!provider.info.languages.includes(AUTO)) throw new Error(`Speech provider ${provider.info.id} must accept the language hint \`auto\``) if (this.providers.has(provider.info.id)) throw new Error(`Speech provider already registered: ${provider.info.id}`) const registration: Registration = { provider, lifetime: new AbortController(), pending: new Set(), unsubscribe: provider.preparation?.subscribe(() => { this.changed() }) ?? (() => {}) } @@ -123,33 +139,54 @@ export default class SpeechToText extends Service { snapshot(): SpeechSnapshot { return { providers: [...this.providers.values()].map(({ provider }) => ({ ...provider.info, preparation: provider.preparation?.snapshot() ?? { phase: 'ready' }, - })), selection: { providerId: this.config.defaultProvider.get() as SpeechProviderId, language: this.config.language.get() } } + })), selection: this.selection() } } /** - * Persist changed selection fields into this plugin's profile entry; the resulting language must be accepted by the selected provider. - * @param patch - explicit provider or language changes. + * Apply the saved preference: an explicit id is kept even while unregistered; `auto` takes the first registered + * `autoOrder` provider that is not unavailable, else the first registered one so its state explains the refusal. + */ + private selection(): SpeechSelection { + const language = this.config.language.get(), choice = this.config.defaultProvider.get() + if (choice !== AUTO) return { mode: 'explicit', providerId: choice as SpeechProviderId, language } + const registered = this.config.autoOrder.flatMap(id => this.providers.get(id as SpeechProviderId)?.provider ?? []) + const chosen = registered.find(provider => provider.preparation?.snapshot().phase !== 'unavailable') ?? registered[0] + return { mode: 'auto', providerId: chosen?.info.id ?? this.config.autoOrder[0] as SpeechProviderId, language } + } + + /** + * Persist changed selection fields into this plugin's profile entry. The language must be listed by at least one + * registered provider; a provider that does not list it receives `auto` when it transcribes. + * @param patch - explicit provider, `auto`, or language changes. * @returns after the profile write and the live update it applies. */ async configure(patch: SpeechSelectionPatch): Promise { const settings = this.ctx.get('settings') const entry = this.entryId if (settings === undefined || entry === undefined) throw new Error('Speech selection requires the settings service and a profile entry') - const id = patch.providerId ?? this.config.defaultProvider.get() as SpeechProviderId - this.selectedProvider(id, patch.language ?? this.config.language.get()) + const choice = patch.providerId ?? this.config.defaultProvider.get() + if (choice === AUTO) { + if (this.config.autoOrder.length === 0) throw new Error('Automatic speech provider selection requires a non-empty autoOrder') + } else { + this.registered(choice as SpeechProviderId) + } + this.knownLanguage(patch.language ?? this.config.language.get()) await settings.update(entry, { ...patch.providerId === undefined ? {} : { defaultProvider: patch.providerId }, ...patch.language === undefined ? {} : { language: patch.language } }) } - private selectedProvider(id: SpeechProviderId, language: string): SpeechProvider { + private registered(id: SpeechProviderId): SpeechProvider { const registration = this.providers.get(id) if (!registration) throw new Error(`Speech provider is unavailable: ${id}`) - if (!registration.provider.info.languages.includes(language)) { - throw new Error(`Speech provider ${id} does not support language: ${language}`) - } return registration.provider } + /** Reject a hint that no registered provider lists; such a value cannot come from any offered choice. */ + private knownLanguage(language: string): string { + for (const { provider } of this.providers.values()) if (provider.info.languages.includes(language)) return language + throw new Error(`No registered speech provider supports language: ${language}`) + } + /** * Start or join provider-owned preparation. * @param id - exact registered provider identity. @@ -173,14 +210,19 @@ export default class SpeechToText extends Service { } /** - * Apply composition defaults and capture the selected provider. Missing providers and unsupported languages fail explicitly. - * @param request - complete recording and optional selection. + * Apply the saved selection and capture the provider. Missing providers and hints no registered provider lists fail + * explicitly; the captured provider receives the hint when it lists it and `auto` otherwise. + * @param request - complete recording, optional selection and the client's UI language. * @returns provider-pinned input for transcribe(). */ resolve(request: SpeechRequest): SpeechSpec { - const id = request.providerId ?? this.config.defaultProvider.get() as SpeechProviderId - const language = request.language ?? this.config.language.get() - return { provider: this.selectedProvider(id, language), audio: request.audio, language } + if (request.providerId === undefined && this.config.defaultProvider.get() === AUTO && this.config.autoOrder.length === 0) { + throw new Error('Automatic speech provider selection requires a non-empty autoOrder') + } + const provider = this.registered(request.providerId ?? this.selection().providerId) + const language = this.knownLanguage(request.language ?? this.config.language.get()) + return { provider, audio: request.audio, language: provider.info.languages.includes(language) ? language : AUTO, + ...request.locale === undefined ? {} : { locale: request.locale } } } /** @@ -196,7 +238,8 @@ export default class SpeechToText extends Service { const combined = AbortSignal.any([signal, registration.lifetime.signal]) const pending = Promise.resolve().then(() => { combined.throwIfAborted() - return spec.provider.transcribe({ audio: spec.audio, language: spec.language }, combined) + return spec.provider.transcribe({ audio: spec.audio, language: spec.language, + ...spec.locale === undefined ? {} : { locale: spec.locale } }, combined) }) registration.pending.add(pending) try { diff --git a/packages/experimental/speech-to-text/src/types.ts b/packages/experimental/speech-to-text/src/types.ts index 1500aabe3e..c78ebc8085 100644 --- a/packages/experimental/speech-to-text/src/types.ts +++ b/packages/experimental/speech-to-text/src/types.ts @@ -17,7 +17,7 @@ export interface SpeechProviderInfo { readonly id: SpeechProviderId readonly name: string readonly location: 'host-local' | 'cloud' - /** Accepted language hints, including automatic detection when supported. */ + /** Accepted language hints; must include `auto`, which a provider receives for any other hint it does not list. */ readonly languages: readonly string[] readonly setupEstimate?: SpeechSetupEstimate /** Origins offered for an explicit preparation download; omitted or empty when no choice applies. */ @@ -43,9 +43,13 @@ export interface SpeechDownloadFailure { readonly status?: number } +/** Why a provider refuses recordings until the user acts; automatic selection skips it. `sign-in-required`: no stored DeepSeek account. */ +export type SpeechUnavailableReason = 'sign-in-required' + /** Host-owned preparation state; byte totals describe downloads, never estimated installation percentages. */ export type SpeechPreparationState = ( | { readonly phase: 'unprepared' | 'ready' | 'standby' | 'cancelled' } + | { readonly phase: 'unavailable'; readonly reason: SpeechUnavailableReason } | { readonly phase: 'downloading'; readonly resource: string; readonly completedBytes: number; readonly totalBytes?: number } | { readonly phase: 'checking' | 'loading' | 'waking' | 'cancelling'; readonly startedAt: number } | { readonly phase: 'failed'; readonly message: string; readonly download?: SpeechDownloadFailure } @@ -59,18 +63,34 @@ export interface SpeechProviderView extends SpeechProviderInfo { readonly preparation: SpeechPreparationState } +/** Reserved preference value selecting the first available provider of the configured automatic order. */ +export type SpeechAutomaticChoice = 'auto' + /** Host-persisted default selection captured when a recording starts. */ export interface SpeechSelection { + /** `auto` follows the configured order; `explicit` keeps the user's exact provider. */ + readonly mode: 'auto' | 'explicit' + /** Provider that a recording started now uses. */ readonly providerId: SpeechProviderId + /** Saved language hint; a provider accepting only `auto` receives `auto` instead. */ readonly language: string } /** User intent updates only the preference fields explicitly changed. */ export interface SpeechSelectionPatch { - readonly providerId?: SpeechProviderId + readonly providerId?: SpeechProviderId | SpeechAutomaticChoice readonly language?: string } +/** + * Stable recognition failure classes that Consumers localize. + * `sign-in-required` needs a new sign-in; `rate-limited`, `timeout` and `service-error` allow a later retry; + * `service-unavailable` and `quota-exceeded`, the exhausted daily allowance, need another provider until the service + * recovers or the allowance resets; `invalid-audio` needs a different recording. + */ +export type SpeechFailureCode = 'sign-in-required' | 'rate-limited' | 'quota-exceeded' + | 'service-unavailable' | 'invalid-audio' | 'timeout' | 'service-error' + /** One consistent provider roster and default-selection observation. */ export interface SpeechSnapshot { readonly providers: readonly SpeechProviderView[] @@ -101,7 +121,10 @@ export interface SpeechPreparation { /** Complete audio recording and an explicit language hint. */ export interface SpeechInput { readonly audio: Uint8Array + /** A hint the provider lists in `languages`. */ readonly language: string + /** UI language of the requesting client, such as `zh` or `pt-BR`; absent for clients that send none. */ + readonly locale?: string | undefined } /** Final transcription; an empty string means no speech was recognized. */ @@ -129,6 +152,8 @@ export interface SpeechRequest { readonly audio: Uint8Array readonly providerId?: SpeechProviderId readonly language?: string + /** UI language of the requesting client, forwarded to the provider unchanged. */ + readonly locale?: string | undefined } /** Resolved selection pins the exact registered provider, including its lifetime. */ diff --git a/packages/experimental/speech-to-text/tests/automatic.spec.ts b/packages/experimental/speech-to-text/tests/automatic.spec.ts new file mode 100644 index 0000000000..eed90c2280 --- /dev/null +++ b/packages/experimental/speech-to-text/tests/automatic.spec.ts @@ -0,0 +1,123 @@ +/** Automatic provider preference, availability-driven routing, and the auto-only language rule. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, vi } from 'vitest' +import SpeechToText from '../src/index.ts' +import type { SpeechPreparationState, SpeechProvider, SpeechProviderId, Transcript } from '../src/types.ts' +import { liveConfig } from '../../../settings/settings/tests/live-config.ts' + +const result: Transcript = { text: 'hello', audioSeconds: 1, inferenceSeconds: 0.1 } +const audio = new Uint8Array([1, 2]) + +/** A provider whose availability the test changes through its preparation listener. */ +function provider(id: string, languages: string[], initial: SpeechPreparationState = { phase: 'ready' }) { + let state = initial + const listeners = new Set<() => void>() + const transcribe = vi.fn(async () => result) + const value: SpeechProvider = { + info: { id: id as SpeechProviderId, name: id, location: 'cloud', languages }, + preparation: { + snapshot: () => state, + subscribe: (listener) => { listeners.add(listener); return () => { listeners.delete(listener) } }, + prepare: () => {}, + cancel: async () => {}, + }, + transcribe, + } + return { value, transcribe, set(next: SpeechPreparationState) { state = next; for (const listener of listeners) listener() } } +} + +async function mounted(ctx: Context, config: object) { + const live = await liveConfig(ctx, SpeechToText, config) + const writes: object[] = [] + ctx.provide('settings', { update: async (_entry: string, patch: Record) => { writes.push(patch); await live.update(patch) } } as never) + return { speech: ctx.get('speechToText')!, writes, live } +} + +it('rejects an automatic preference without an order and reserves the automatic id', async () => { + expect(() => new SpeechToText(new Context(), SpeechToText.Config({ defaultProvider: 'auto', language: 'auto' }))) + .toThrow('non-empty autoOrder') + expect(() => new SpeechToText(new Context(), SpeechToText.Config({ defaultProvider: 'local', autoOrder: ['auto'] }))) + .toThrow('reserved') + const ctx = new Context() + try { + await ctx.plugin(SpeechToText, { defaultProvider: 'local', autoOrder: ['local'] }) + expect(() => ctx.get('speechToText')!.register(provider('auto', ['auto']).value)).toThrow('reserved') + } finally { await ctx.fiber.dispose() } +}) + +it('routes automatic selection to the first available provider and follows availability changes', async () => { + const ctx = new Context() + try { + const { speech } = await mounted(ctx, { defaultProvider: 'auto', autoOrder: ['cloud', 'local'], language: 'zh' }) + expect(speech.snapshot().selection).toEqual({ mode: 'auto', providerId: 'cloud', language: 'zh' }) + const cloud = provider('cloud', ['auto'], { phase: 'unavailable', reason: 'sign-in-required' }) + const local = provider('local', ['auto', 'zh'], { phase: 'unprepared' }) + speech.register(cloud.value) + expect(speech.snapshot().selection.providerId).toBe('cloud') + speech.register(local.value) + const stream = speech.follow(new AbortController().signal)[Symbol.asyncIterator]() + expect((await stream.next()).value).toMatchObject({ selection: { mode: 'auto', providerId: 'local' } }) + expect(speech.resolve({ audio })).toMatchObject({ provider: local.value, language: 'zh' }) + const next = stream.next() + cloud.set({ phase: 'ready' }) + expect((await next).value).toMatchObject({ selection: { mode: 'auto', providerId: 'cloud', language: 'zh' } }) + expect(speech.resolve({ audio })).toEqual({ provider: cloud.value, audio, language: 'auto' }) + expect(speech.resolve({ audio, providerId: local.value.info.id })).toMatchObject({ provider: local.value, language: 'zh' }) + local.set({ phase: 'unavailable', reason: 'sign-in-required' }) + cloud.set({ phase: 'unavailable', reason: 'sign-in-required' }) + expect(speech.snapshot().selection.providerId).toBe('cloud') + } finally { await ctx.fiber.dispose() } +}) + +it('saves any language some provider lists and gives each provider auto for hints it does not list', async () => { + const ctx = new Context() + try { + const { speech, writes } = await mounted(ctx, { defaultProvider: 'local', autoOrder: ['cloud', 'local'], language: 'auto' }) + const cloud = provider('cloud', ['auto', 'zh', 'es']), local = provider('local', ['auto', 'zh']) + speech.register(cloud.value); speech.register(local.value) + await expect(speech.configure({ providerId: 'auto', language: 'fr' })).rejects.toThrow('No registered speech provider supports language: fr') + await speech.configure({ providerId: 'auto', language: 'es' }) + expect(speech.snapshot().selection).toEqual({ mode: 'auto', providerId: 'cloud', language: 'es' }) + expect(speech.resolve({ audio, locale: 'pt-BR' })).toEqual({ provider: cloud.value, audio, language: 'es', locale: 'pt-BR' }) + expect(speech.resolve({ audio, providerId: local.value.info.id })).toEqual({ provider: local.value, audio, language: 'auto' }) + expect(() => speech.resolve({ audio, language: 'fr' })).toThrow('No registered speech provider supports language: fr') + await speech.transcribe(speech.resolve({ audio, locale: 'ja' }), new AbortController().signal) + expect(cloud.transcribe).toHaveBeenLastCalledWith({ audio, language: 'es', locale: 'ja' }, expect.any(AbortSignal)) + await speech.transcribe(speech.resolve({ audio, providerId: local.value.info.id }), new AbortController().signal) + expect(local.transcribe).toHaveBeenLastCalledWith({ audio, language: 'auto' }, expect.any(AbortSignal)) + await speech.configure({ providerId: 'local' as SpeechProviderId }) + expect(speech.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'local', language: 'es' }) + expect(writes).toEqual([{ defaultProvider: 'auto', language: 'es' }, { defaultProvider: 'local' }]) + } finally { await ctx.fiber.dispose() } +}) + +it('requires every provider to accept automatic language detection', async () => { + const ctx = new Context() + try { + await ctx.plugin(SpeechToText, { defaultProvider: 'local', autoOrder: ['local'] }) + expect(() => ctx.get('speechToText')!.register(provider('local', ['zh']).value)).toThrow('must accept the language hint `auto`') + } finally { await ctx.fiber.dispose() } +}) + +it('checks only registered automatic providers when saving the automatic preference', async () => { + const ctx = new Context() + try { + const { speech, writes } = await mounted(ctx, { defaultProvider: 'local', autoOrder: ['cloud', 'local'], language: 'zh' }) + speech.register(provider('local', ['auto', 'zh']).value) + await speech.configure({ providerId: 'auto' }) + expect(speech.snapshot().selection).toEqual({ mode: 'auto', providerId: 'local', language: 'zh' }) + expect(writes).toEqual([{ defaultProvider: 'auto' }]) + } finally { await ctx.fiber.dispose() } +}) + +it('fails explicitly when the live preference becomes automatic without an order', async () => { + const ctx = new Context() + try { + const { speech, live } = await mounted(ctx, { defaultProvider: 'local', language: 'auto' }) + speech.register(provider('local', ['auto']).value) + await expect(speech.configure({ providerId: 'auto' })).rejects.toThrow('non-empty autoOrder') + await live.update({ defaultProvider: 'auto' }) + expect(() => speech.resolve({ audio })).toThrow('non-empty autoOrder') + expect(speech.resolve({ audio, providerId: 'local' as SpeechProviderId })).toMatchObject({ language: 'auto' }) + } finally { await ctx.fiber.dispose() } +}) diff --git a/packages/experimental/speech-to-text/tests/configuration.spec.ts b/packages/experimental/speech-to-text/tests/configuration.spec.ts index 05a2b97f35..27f5423077 100644 --- a/packages/experimental/speech-to-text/tests/configuration.spec.ts +++ b/packages/experimental/speech-to-text/tests/configuration.spec.ts @@ -41,10 +41,10 @@ it('saves language and provider preferences without remounting and restores them const fiber = entry.fiber for (const language of [...languages, 'zh']) { await speech.configure({ language }) - expect(speech.snapshot().selection).toEqual({ providerId: 'sensevoice-local', language }) + expect(speech.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'sensevoice-local', language }) } await speech.configure({ providerId: 'another-provider' as SpeechProviderId }) - expect(speech.snapshot().selection).toEqual({ providerId: 'another-provider', language: 'zh' }) + expect(speech.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'another-provider', language: 'zh' }) expect(entry.fiber === fiber).toBe(true) const saved = readFileSync(profile.patchPath, 'utf8') expect(saved).toContain('id: speech-to-text') @@ -52,7 +52,7 @@ it('saves language and provider preferences without remounting and restores them expect(saved).toContain('language: zh') await ctx.fiber.dispose() ctx = await start() - expect(ctx.get('speechToText')!.snapshot().selection).toEqual({ providerId: 'another-provider', language: 'zh' }) + expect(ctx.get('speechToText')!.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'another-provider', language: 'zh' }) } finally { try { await ctx?.fiber.dispose() } finally { rmSync(home, { recursive: true, force: true }) } } diff --git a/packages/experimental/speech-to-text/tests/service.spec.ts b/packages/experimental/speech-to-text/tests/service.spec.ts index bf09c0af5f..2adffb64b6 100644 --- a/packages/experimental/speech-to-text/tests/service.spec.ts +++ b/packages/experimental/speech-to-text/tests/service.spec.ts @@ -64,12 +64,12 @@ it('persists explicit provider and language changes through the profile and publ await speech.configure({ providerId: 'cloud' as SpeechProviderId }) expect((await next).value).toMatchObject({ selection: { providerId: 'cloud', language: 'auto' } }) await speech.configure({ language: 'en' }) - expect(speech.snapshot().selection).toEqual({ providerId: 'cloud', language: 'en' }) + expect(speech.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'cloud', language: 'en' }) expect(speech.resolve({ audio })).toMatchObject({ provider: { info: { id: 'cloud' } }, language: 'en' }) expect(writes).toEqual([{ defaultProvider: 'cloud' }, { language: 'en' }]) await expect(speech.configure({ providerId: 'missing' as SpeechProviderId })).rejects.toThrow('unavailable') await expect(speech.configure({ language: '' })).rejects.toThrow() - expect(speech.snapshot().selection).toEqual({ providerId: 'cloud', language: 'en' }) + expect(speech.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'cloud', language: 'en' }) } finally { await ctx.fiber.dispose() } }) @@ -82,7 +82,7 @@ it('refuses to configure without the settings service or a profile entry', async await expect(speech.configure({ language: 'zh' })).rejects.toThrow('settings service') ctx.provide('settings', { update: vi.fn() } as never) await expect(speech.configure({ language: 'zh' })).rejects.toThrow('profile entry') - expect(speech.snapshot().selection).toEqual({ providerId: 'local', language: 'auto' }) + expect(speech.snapshot().selection).toEqual({ mode: 'explicit', providerId: 'local', language: 'auto' }) } finally { await ctx.fiber.dispose() } }) @@ -173,21 +173,23 @@ describe('speech providers', () => { }) }) -it('rejects unsupported language selections before persistence or transcription', async () => { +it('rejects language selections no provider lists before persistence or transcription', async () => { const ctx = new Context() try { const { speech, writes } = await mounted(ctx, { defaultProvider: 'local', language: 'auto' }) const transcribe = vi.fn(async () => result) speech.register(provider('local', transcribe)) const cloud = provider('cloud', transcribe) - speech.register({ ...cloud, info: { ...cloud.info, languages: ['fr'] } }) - await expect(speech.configure({ language: 'fr' })).rejects.toThrow('does not support language') - await expect(speech.configure({ providerId: cloud.info.id })).rejects.toThrow('does not support language') + speech.register({ ...cloud, info: { ...cloud.info, languages: ['auto', 'fr'] } }) + await expect(speech.configure({ language: 'it' })).rejects.toThrow('No registered speech provider supports language: it') expect(writes).toEqual([]) - expect(() => speech.resolve({ audio, language: 'fr' })).toThrow('does not support language') + expect(() => speech.resolve({ audio, language: 'it' })).toThrow('No registered speech provider supports language: it') expect(transcribe).not.toHaveBeenCalled() - await speech.configure({ providerId: cloud.info.id, language: 'fr' }) - expect(speech.resolve({ audio })).toMatchObject({ provider: { info: { id: 'cloud', languages: ['fr'] } }, language: 'fr' }) + await speech.configure({ language: 'fr' }) + expect(speech.resolve({ audio })).toMatchObject({ provider: { info: { id: 'local' } }, language: 'auto' }) + await speech.configure({ providerId: cloud.info.id }) + expect(speech.resolve({ audio })).toMatchObject({ provider: { info: { id: 'cloud' } }, language: 'fr' }) + expect(writes).toEqual([{ language: 'fr' }, { defaultProvider: 'cloud' }]) } finally { await ctx.fiber.dispose() } }) diff --git a/packages/experimental/voice-input-bundle/README.i18n.yaml b/packages/experimental/voice-input-bundle/README.i18n.yaml index 1bcaba6dac..6948540576 100644 --- a/packages/experimental/voice-input-bundle/README.i18n.yaml +++ b/packages/experimental/voice-input-bundle/README.i18n.yaml @@ -9,14 +9,14 @@ en: 338585d3575a8f90 zh: 22a493cbeefec8f0 /deepseek-ai-dsh-experimental-voice-input-bundle/summary: - en: e84cf8d1493e2a08 - zh: f0549f75a5234388 + en: 1c29181a3fd5793f + zh: 7cf08ce00f2f6f59 /deepseek-ai-dsh-experimental-voice-input-bundle/table-of-contents: en: d152484eb41ac6b4 zh: 364c80ee00a374ff /deepseek-ai-dsh-experimental-voice-input-bundle/use-this-package: - en: 9151bf11e64b4f1c - zh: 7c9638c16ac6a0db + en: 8b716ba9a9d55c91 + zh: b6320e2696a64860 /deepseek-ai-dsh-experimental-voice-input-bundle/understand-the-implementation: en: 45c5f442f85483a8 zh: 1e6d54bcaef39b89 diff --git a/packages/experimental/voice-input-bundle/README.md b/packages/experimental/voice-input-bundle/README.md index 70046ec145..5c238fafa3 100644 --- a/packages/experimental/voice-input-bundle/README.md +++ b/packages/experimental/voice-input-bundle/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This optional bundle composes a speech Service Definition, local SenseVoice provider, authenticated Remote and browser microphone control. Shipped profiles leave it disabled. +This optional bundle composes a speech Service Definition, DeepSeek cloud and local SenseVoice providers, authenticated Remote and browser microphone control. Shipped profiles leave it disabled. ## Table of Contents @@ -27,6 +27,8 @@ This optional bundle composes a speech Service Definition, local SenseVoice prov Open Plugins in the Web sidebar and enable Voice Input, marked by a blue waveform icon. If models need preparation, a dialog offers Go to setup or Later; Go to setup opens the bundle details. Complete caches need no setup prompt. In the details, choose Download and prepare; the collapsed current-step summary expands to the complete step list. Downloads report actual bytes; verification and loading show elapsed time. Once ready, click the microphone between the model selector and Send, then Stop to insert a transcript. Bundle details store the recognizer and language through the Settings service. Disabling the bundle cancels active work; cached assets remain on disk. +Recognition defaults to Automatic: a signed-in DeepSeek account uses the DeepSeek cloud provider, otherwise the local SenseVoice provider. The cloud provider sends recordings to the DeepSeek service as its [README](../speech-to-text-deepseek/README.md) describes. + ----- diff --git a/packages/experimental/voice-input-bundle/README.zh.md b/packages/experimental/voice-input-bundle/README.zh.md index 51ed5a6c34..facaa07afd 100644 --- a/packages/experimental/voice-input-bundle/README.zh.md +++ b/packages/experimental/voice-input-bundle/README.zh.md @@ -9,7 +9,7 @@ kind: "package-bundle" ## 概述 -此可选 Bundle 组合语音服务定义、本地 SenseVoice Provider、带认证的 Remote 与浏览器麦克风控件。随包配置默认禁用。 +此可选 Bundle 组合语音服务定义、DeepSeek 云端与本地 SenseVoice Provider、带认证的 Remote 与浏览器麦克风控件。随包配置默认禁用。 ## 目录 @@ -27,6 +27,8 @@ kind: "package-bundle" 打开 Web 侧栏的插件管理页并启用带蓝色声波图标的“语音输入”。模型需要准备时,弹窗提供“前往安装”和“稍后”选项;“前往安装”打开 Bundle 详情。缓存完整时不会提示安装。在详情中选择“下载并准备”;默认折叠的当前步骤摘要可展开为完整步骤列表。下载报告真实字节,校验和加载显示等待时间。就绪后点击模型选择器与发送按钮之间的麦克风,再点击停止以插入转写文字。Bundle 详情通过 Settings 服务保存识别器和语言。禁用 Bundle 会取消当前任务;缓存资源保留在磁盘上。 +识别服务默认为“自动”:已登录 DeepSeek 账号时使用 DeepSeek 云端 Provider,否则使用本地 SenseVoice Provider。云端 Provider 按其 [README](../speech-to-text-deepseek/README.zh.md) 所述把录音发送到 DeepSeek 服务。 + ----- diff --git a/packages/experimental/voice-input-bundle/cordis.patch.yml b/packages/experimental/voice-input-bundle/cordis.patch.yml index 255734df80..10233d7d27 100644 --- a/packages/experimental/voice-input-bundle/cordis.patch.yml +++ b/packages/experimental/voice-input-bundle/cordis.patch.yml @@ -2,11 +2,14 @@ - id: speech-to-text name: '@deepseek-ai/dsh-experimental-speech-to-text' config: - defaultProvider: sensevoice-local + defaultProvider: auto + autoOrder: [deepseek-asr, sensevoice-local] - id: speech-to-text-sensevoice name: '@deepseek-ai/dsh-experimental-speech-to-text-sensevoice' config: dataRoot: !!js dshHomePath('speech-to-text', 'sensevoice') + - id: speech-to-text-deepseek + name: '@deepseek-ai/dsh-speech-to-text-deepseek' - id: api-speech-to-text name: '@deepseek-ai/dsh-experimental-api-speech-to-text' - id: ui-voice-input diff --git a/packages/experimental/voice-input-bundle/locale/de.json b/packages/experimental/voice-input-bundle/locale/de.json index ceb1ff524d..12e0ff416b 100644 --- a/packages/experimental/voice-input-bundle/locale/de.json +++ b/packages/experimental/voice-input-bundle/locale/de.json @@ -1,7 +1,7 @@ { "meta": { "title": "Spracheingabe", - "description": "Transkribieren Sie Aufnahmen lokal mit SenseVoice; Für die erste Verwendung müssen Abhängigkeiten installiert werden.", + "description": "Diktieren Sie nach der Anmeldung mit der DeepSeek-Cloud-Erkennung oder laden Sie das lokale SenseVoice-Modell herunter.", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/en.json b/packages/experimental/voice-input-bundle/locale/en.json index a88375bd63..b89924553b 100644 --- a/packages/experimental/voice-input-bundle/locale/en.json +++ b/packages/experimental/voice-input-bundle/locale/en.json @@ -1,7 +1,7 @@ { "meta": { "title": "Voice input", - "description": "Transcribe recordings locally with SenseVoice; first use requires installing dependencies.", + "description": "Dictate with DeepSeek cloud recognition after signing in, or download the local SenseVoice model.", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/es.json b/packages/experimental/voice-input-bundle/locale/es.json index cf5515a994..38729d044e 100644 --- a/packages/experimental/voice-input-bundle/locale/es.json +++ b/packages/experimental/voice-input-bundle/locale/es.json @@ -1,7 +1,7 @@ { "meta": { "title": "Entrada de voz", - "description": "Transcribe grabaciones localmente con SenseVoice; El primer uso requiere instalar dependencias.", + "description": "Dicta con el reconocimiento en la nube de DeepSeek tras iniciar sesión, o descarga el modelo local SenseVoice.", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/fr.json b/packages/experimental/voice-input-bundle/locale/fr.json index efcb87ff7c..02b3879f47 100644 --- a/packages/experimental/voice-input-bundle/locale/fr.json +++ b/packages/experimental/voice-input-bundle/locale/fr.json @@ -1,7 +1,7 @@ { "meta": { "title": "Saisie vocale", - "description": "Transcrivez les enregistrements localement avec SenseVoice ; la première utilisation nécessite l'installation de dépendances.", + "description": "Dictez avec la reconnaissance cloud DeepSeek après connexion, ou téléchargez le modèle local SenseVoice.", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/ja.json b/packages/experimental/voice-input-bundle/locale/ja.json index b5d9ea6c48..35daee3bb7 100644 --- a/packages/experimental/voice-input-bundle/locale/ja.json +++ b/packages/experimental/voice-input-bundle/locale/ja.json @@ -1,7 +1,7 @@ { "meta": { "title": "音声入力", - "description": "ローカルの SenseVoice で録音を文字に起こします。初回利用時には依存関係のインストールが必要です。", + "description": "DeepSeek にログインするとクラウド認識で音声入力できます。ローカルの SenseVoice モデルをダウンロードすることもできます。", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/pt.json b/packages/experimental/voice-input-bundle/locale/pt.json index a50a67956c..9efca4a4c9 100644 --- a/packages/experimental/voice-input-bundle/locale/pt.json +++ b/packages/experimental/voice-input-bundle/locale/pt.json @@ -1,7 +1,7 @@ { "meta": { "title": "Entrada de voz", - "description": "Transcreva gravações localmente com SenseVoice; o primeiro uso requer a instalação de dependências.", + "description": "Dite com o reconhecimento na nuvem da DeepSeek após iniciar sessão, ou transfira o modelo local SenseVoice.", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/ru.json b/packages/experimental/voice-input-bundle/locale/ru.json index 474fc4c149..c2da3613db 100644 --- a/packages/experimental/voice-input-bundle/locale/ru.json +++ b/packages/experimental/voice-input-bundle/locale/ru.json @@ -1,7 +1,7 @@ { "meta": { "title": "Голосовой ввод", - "description": "Транскрибируйте записи локально с помощью SenseVoice; при первом использовании требуется установка зависимостей.", + "description": "Диктуйте с облачным распознаванием DeepSeek после входа в аккаунт или скачайте локальную модель SenseVoice.", "detail": "docs/DETAIL.md" } } diff --git a/packages/experimental/voice-input-bundle/locale/zh.json b/packages/experimental/voice-input-bundle/locale/zh.json index e5f76bc6ac..caf1dfeeaf 100644 --- a/packages/experimental/voice-input-bundle/locale/zh.json +++ b/packages/experimental/voice-input-bundle/locale/zh.json @@ -1,7 +1,7 @@ { "meta": { "title": "语音输入", - "description": "在本机使用 SenseVoice 转写录音,首次使用需安装依赖。", + "description": "登录 DeepSeek 账号后使用云端识别转写录音,也可以下载本地 SenseVoice 模型。", "detail": "docs/DETAIL.zh.md" } } diff --git a/packages/experimental/voice-input-bundle/package.json b/packages/experimental/voice-input-bundle/package.json index ba00f6afa8..e9204a8ac6 100644 --- a/packages/experimental/voice-input-bundle/package.json +++ b/packages/experimental/voice-input-bundle/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-experimental-voice-input-bundle", - "description": "Experimental voice input with local SenseVoice; downloads its runtime on first use", + "description": "Experimental voice input with DeepSeek cloud recognition for signed-in users and optional local SenseVoice", "version": "0.2.2-rc.1", "icon": "./icon.svg", "publishConfig": { @@ -36,6 +36,7 @@ "dependencies": { "@deepseek-ai/dsh-experimental-speech-to-text": "workspace:*", "@deepseek-ai/dsh-experimental-speech-to-text-sensevoice": "workspace:*", + "@deepseek-ai/dsh-speech-to-text-deepseek": "workspace:*", "@deepseek-ai/dsh-experimental-api-speech-to-text": "workspace:*", "@deepseek-ai/dsh-experimental-client-ui-voice-input": "workspace:*" }, diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 6d2208cf96..b215079a0c 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1037,7 +1037,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'abstract resolveToken(url: string): Promise', - description: 'Resolve a credential only for the inference origin allowed by the provider.', + description: 'Resolve a credential only for an origin the provider allows, such as its inference and service origins.', parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], returns: 'stored token, or undefined for other origins or a signed-out account.', }, @@ -3539,8 +3539,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async configure(patch: SpeechSelectionPatch): Promise', - description: 'Persist changed selection fields into this plugin\'s profile entry; the resulting language must be accepted by the selected provider.', - parameters: [{ name: 'patch', description: 'explicit provider or language changes.' }], + description: 'Persist changed selection fields into this plugin\'s profile entry. The language must be listed by at least one registered provider; a provider that does not list it receives `auto` when it transcribes.', + parameters: [{ name: 'patch', description: 'explicit provider, `auto`, or language changes.' }], returns: 'after the profile write and the live update it applies.', }, { @@ -3556,8 +3556,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'resolve(request: SpeechRequest): SpeechSpec', - description: 'Apply composition defaults and capture the selected provider. Missing providers and unsupported languages fail explicitly.', - parameters: [{ name: 'request', description: 'complete recording and optional selection.' }], + description: 'Apply the saved selection and capture the provider. Missing providers and hints no registered provider lists fail explicitly; the captured provider receives the hint when it lists it and `auto` otherwise.', + parameters: [{ name: 'request', description: 'complete recording, optional selection and the client\'s UI language.' }], returns: 'provider-pinned input for transcribe().', }, { @@ -9099,6 +9099,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SkillViewOptions', declaration: 'export interface SkillViewOptions extends SkillLookupOptions {\n readonly scope?: ScopeKey | undefined;\n}', }, + { + name: 'SpeechAutomaticChoice', + declaration: 'export type SpeechAutomaticChoice = \'auto\';', + }, { name: 'SpeechCatalog', declaration: 'export interface SpeechCatalog extends SpeechSnapshot {\n readonly maxAudioBytes: number;\n readonly maxDurationSeconds: number;\n}', @@ -9109,7 +9113,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SpeechInput', - declaration: 'export interface SpeechInput {\n readonly audio: Uint8Array;\n readonly language: string;\n}', + declaration: 'export interface SpeechInput {\n readonly audio: Uint8Array;\n readonly language: string;\n readonly locale?: string | undefined;\n}', }, { name: 'SpeechPreparation', @@ -9121,7 +9125,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SpeechPreparationState', - declaration: 'export type SpeechPreparationState = ({\n readonly phase: \'unprepared\' | \'ready\' | \'standby\' | \'cancelled\';\n} | {\n readonly phase: \'downloading\';\n readonly resource: string;\n readonly completedBytes: number;\n readonly totalBytes?: number;\n} | {\n readonly phase: \'checking\' | \'loading\' | \'waking\' | \'cancelling\';\n readonly startedAt: number;\n} | {\n readonly phase: \'failed\';\n readonly message: string;\n readonly download?: SpeechDownloadFailure;\n}) & {\n readonly step?: SpeechPreparationStepKind;\n readonly steps?: readonly SpeechPreparationStep[];\n};', + declaration: 'export type SpeechPreparationState = ({\n readonly phase: \'unprepared\' | \'ready\' | \'standby\' | \'cancelled\';\n} | {\n readonly phase: \'unavailable\';\n readonly reason: SpeechUnavailableReason;\n} | {\n readonly phase: \'downloading\';\n readonly resource: string;\n readonly completedBytes: number;\n readonly totalBytes?: number;\n} | {\n readonly phase: \'checking\' | \'loading\' | \'waking\' | \'cancelling\';\n readonly startedAt: number;\n} | {\n readonly phase: \'failed\';\n readonly message: string;\n readonly download?: SpeechDownloadFailure;\n}) & {\n readonly step?: SpeechPreparationStepKind;\n readonly steps?: readonly SpeechPreparationStep[];\n};', }, { name: 'SpeechPreparationStep', @@ -9149,15 +9153,15 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SpeechRequest', - declaration: 'export interface SpeechRequest {\n readonly audio: Uint8Array;\n readonly providerId?: SpeechProviderId;\n readonly language?: string;\n}', + declaration: 'export interface SpeechRequest {\n readonly audio: Uint8Array;\n readonly providerId?: SpeechProviderId;\n readonly language?: string;\n readonly locale?: string | undefined;\n}', }, { name: 'SpeechSelection', - declaration: 'export interface SpeechSelection {\n readonly providerId: SpeechProviderId;\n readonly language: string;\n}', + declaration: 'export interface SpeechSelection {\n readonly mode: \'auto\' | \'explicit\';\n readonly providerId: SpeechProviderId;\n readonly language: string;\n}', }, { name: 'SpeechSelectionPatch', - declaration: 'export interface SpeechSelectionPatch {\n readonly providerId?: SpeechProviderId;\n readonly language?: string;\n}', + declaration: 'export interface SpeechSelectionPatch {\n readonly providerId?: SpeechProviderId | SpeechAutomaticChoice;\n readonly language?: string;\n}', }, { name: 'SpeechSetupEstimate', @@ -9171,6 +9175,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SpeechSpec', declaration: 'export interface SpeechSpec extends SpeechInput {\n readonly provider: SpeechProvider;\n}', }, + { + name: 'SpeechUnavailableReason', + declaration: 'export type SpeechUnavailableReason = \'sign-in-required\';', + }, { name: 'SpillLocator', declaration: 'export type SpillLocator = Branded<\'SpillLocator\'>;', @@ -9741,7 +9749,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'TranscriptionRequest', - declaration: 'export interface TranscriptionRequest {\n readonly audioBase64: string;\n readonly providerId?: SpeechProviderId;\n readonly language?: string;\n}', + declaration: 'export interface TranscriptionRequest {\n readonly audioBase64: string;\n readonly providerId?: SpeechProviderId;\n readonly language?: string;\n readonly locale?: string;\n}', }, { name: 'TranslationProvider', diff --git a/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md b/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md index 9f1f6d71b6..1464c873de 100644 --- a/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md +++ b/packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md @@ -229,6 +229,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-plugin-recommendations` | no | Official plugin suggestions with explicit user activation and persistent conversation decisions | | `@deepseek-ai/dsh-session-title-all-prompts-llm` | yes | All-user-messages LLM provider plugin for DeepSeek Harness session titles | | `@deepseek-ai/dsh-skill-badge` | no | Bundled dsh badge skill provider for DeepSeek Harness | +| `@deepseek-ai/dsh-speech-to-text-deepseek` | yes | DeepSeek One-Shot cloud transcription authenticated by the DeepSeek account | | `@deepseek-ai/dsh-tool-ralph` | yes | Model-facing fresh-agent Ralph loop over the workflow and subagent seams | | `@deepseek-ai/dsh-tool-session-query` | yes | Workspace-authorized model-facing session history search, trace, and event read tools | | `@deepseek-ai/dsh-tool-terminal` | yes | Six model-facing persistent PTY tools with owner isolation and generic background-job integration | diff --git a/packages/web/web-search-deepseek/README.i18n.yaml b/packages/web/web-search-deepseek/README.i18n.yaml index 5cbf683924..f2f1ce874e 100644 --- a/packages/web/web-search-deepseek/README.i18n.yaml +++ b/packages/web/web-search-deepseek/README.i18n.yaml @@ -24,8 +24,8 @@ en: 0553b6c926c44cf4 zh: 5cd3221d3e8eebd9 /deepseek-ai-dsh-web-search-deepseek/use-this-package/authentication: - en: 7a765ba931329067 - zh: 6fc14edcc378684a + en: 39b9e8ceeba56474 + zh: e4e5cd007ac53b45 /deepseek-ai-dsh-web-search-deepseek/use-this-package/what-a-search-returns: en: e30442c90365357b zh: 9c9e2f1182963a8a diff --git a/packages/web/web-search-deepseek/README.md b/packages/web/web-search-deepseek/README.md index 78329bf915..b44dc0782d 100644 --- a/packages/web/web-search-deepseek/README.md +++ b/packages/web/web-search-deepseek/README.md @@ -58,7 +58,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Authentication -A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names the `deepseek-account` provider route and `ctx.deepseekAccount` resolves a token for the search endpoint. The account service resolves one only while signed in and only for its deployment-configured inference origin, `https://api.deepseek.com` by default. That search sends only `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the token that search sent: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. +A search authenticates with the DeepSeek account when the latest `request/context` event of the initiating Session names the `deepseek-account` provider route and `ctx.deepseekAccount` resolves a token for the search endpoint. The account service resolves one only while signed in and only for the origins its deployment allows, by default `https://api.deepseek.com` for inference and `https://harness.deepseek.com` for speech recognition. That search sends only `x-dsh-auth-token`, even when an API key is configured. Every other search, including a call without an initiating Session and a search whose endpoint has another origin, sends the API key as both `x-api-key` and `Authorization: Bearer`. An HTTP 401 response to an account-authenticated search fails as `WEB_PROVIDER_ERROR` with sign-in guidance instead of endpoint guidance, and invalidates only the token that search sent: a newer sign-in is preserved, and a credential-removal failure or a cancelled error-body read does not skip invalidation or replace the reported failure. An API-key 401 and every HTTP 403 leave the account signed in. The provider's `ready()` answers whether the search a model request would make has a credential, on any model route: the request's route is `deepseek-account` and `ctx.deepseekAccount` resolves a token for the configured search endpoint, or a literal `apiKey` is set or `ctx.credentials.describe` reports the `apiKeyEnv` reference configured (without that service, the process environment must carry it). It checks them in the order a search resolves them, and a failed account-token or credential-store read answers false, because the search fails on that read instead of trying the next credential. While this provider is the selected search provider, [`dsh-tool-web`](../tool-web/README.md#search-readiness) withholds `web_search` and its prompt guidance from each request for which it answers false. Only presence is checked: a wrong key, or an endpoint that does not serve the native `web_search_20250305` server tool, counts as ready and fails each call. A call that still arrives resolves credentials when it runs. diff --git a/packages/web/web-search-deepseek/README.zh.md b/packages/web/web-search-deepseek/README.zh.md index 4755a0deaf..e509915343 100644 --- a/packages/web/web-search-deepseek/README.zh.md +++ b/packages/web/web-search-deepseek/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 鉴权 -当发起会话最近的 `request/context` 事件指明 `deepseek-account` 提供方路由,且 `ctx.deepseekAccount` 为搜索端点解析出 token 时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署配置的推理 origin(默认 `https://api.deepseek.com`)解析 token。这类搜索只发送 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并只作废该搜索实际发送的 token:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 +当发起会话最近的 `request/context` 事件指明 `deepseek-account` 提供方路由,且 `ctx.deepseekAccount` 为搜索端点解析出 token 时,搜索使用 DeepSeek 账号鉴权。账号服务仅在已登录时、且仅对部署允许的 origin 解析 token,默认是用于推理的 `https://api.deepseek.com` 和用于语音识别的 `https://harness.deepseek.com`。这类搜索只发送 `x-dsh-auth-token`,即使配置了 API 密钥也是如此。其余所有搜索,包括没有发起会话的调用以及端点属于其他 origin 的搜索,都把 API 密钥同时作为 `x-api-key` 与 `Authorization: Bearer` 发送。账号鉴权的搜索收到 HTTP 401 时以 `WEB_PROVIDER_ERROR` 失败,附带登录指引而非端点指引,并只作废该搜索实际发送的 token:更新的登录不受影响,凭据删除失败或错误正文读取被取消既不会跳过作废,也不会替换所报告的失败。API 密钥请求的 401 与所有 HTTP 403 不影响账号登录状态。 提供方的 `ready()` 回答模型请求将发起的搜索是否有凭据,不论模型路由:该请求的路由是 `deepseek-account` 且 `ctx.deepseekAccount` 为配置的搜索端点解析出 token,或者设置了字面 `apiKey`,或 `ctx.credentials.describe` 报告 `apiKeyEnv` 引用已配置(没有该服务时,进程环境中必须存在该变量)。它按搜索解析凭据的顺序检查,读取账号 token 或凭据存储失败时回答 false,因为搜索会在该次读取上失败,而不会尝试下一种凭据。本提供方是选中的搜索提供方时,[`dsh-tool-web`](../tool-web/README.zh.md#search-readiness) 会从它回答 false 的每个请求中撤下 `web_search` 及其提示词说明。这里只检查凭据是否存在:错误的密钥,或不提供原生 `web_search_20250305` 服务器工具的端点,都视为就绪并使每次调用失败。仍然到达的调用会在运行时解析凭据。 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e6ccbecbec..8e3a373193 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9438,6 +9438,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:* version: link:../../client/ui-session + '@deepseek-ai/dsh-client-ui-settings-account': + specifier: workspace:* + version: link:../../client/ui-settings-account '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:* version: link:../../client/ui-slots @@ -10951,6 +10954,31 @@ importers: specifier: workspace:* version: link:../../settings/settings + packages/experimental/speech-to-text-deepseek: + dependencies: + '@deepseek-ai/dsh-timeout': + specifier: workspace:* + version: link:../../util/timeout + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: 4.4.3 + version: 4.4.3 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-deepseek-account': + specifier: workspace:* + version: link:../../credentials/deepseek-account + '@deepseek-ai/dsh-experimental-speech-to-text': + specifier: workspace:* + version: link:../speech-to-text + packages/experimental/speech-to-text-sensevoice: dependencies: '@deepseek-ai/dsh-timeout': @@ -11448,6 +11476,9 @@ importers: '@deepseek-ai/dsh-experimental-speech-to-text-sensevoice': specifier: workspace:* version: link:../speech-to-text-sensevoice + '@deepseek-ai/dsh-speech-to-text-deepseek': + specifier: workspace:* + version: link:../speech-to-text-deepseek devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ diff --git a/scripts/experimental-package-policy.ts b/scripts/experimental-package-policy.ts index 38e972b1a5..f00cba584d 100644 --- a/scripts/experimental-package-policy.ts +++ b/scripts/experimental-package-policy.ts @@ -25,6 +25,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly /** Legacy npm namespace, allowed only in `LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES`. */ diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index cc05f1e2a9..e4be45e219 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -209,6 +209,7 @@ export const SERVICE_WALK_EXEMPTIONS: Record = { layout: 'client-side interface-typed browser service — packages/client/ui-layout/README.md owns the API', pluginNavigation: 'client-side bundle navigation — packages/client/ui-plugin-manager/README.md owns the API', pluginChanges: 'client-side read-only management activity — packages/client/ui-plugin-manager/README.md owns the API', + accountSignIn: 'client-side account sign-in entry — packages/client/ui-settings-account/README.md owns the API', locale: 'client-side interface-typed browser service — packages/client/locale/README.md owns the API', modelDirectories: 'client-side interface-typed browser service — packages/client/ui-model-selection/README.md owns the API', modules: 'client-side interface-typed browser service — packages/client/modules/README.md owns the API', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index b179c0d8f4..3621e068bd 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -58,6 +58,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/experimental/speech-to-text': { kind: 'none', reason: 'Routes transient recognition without adding model requests or Session events.' }, 'packages/experimental/api-speech-to-text': { kind: 'none', reason: 'Transports audio and preparation state; ordinary user submission owns model-visible text.' }, 'packages/experimental/speech-to-text-sensevoice': { kind: 'none', reason: 'Local recognition returns transient text without modifying model context.' }, + 'packages/experimental/speech-to-text-deepseek': { kind: 'none', reason: 'Cloud recognition returns transient text without modifying model context.' }, 'packages/experimental/client-ui-voice-input': { kind: 'none', reason: 'Inserts reviewable text into the unsent draft without submitting to the Agent.' }, 'packages/experimental/liveshare': { kind: 'indirect', reason: 'The host drives viewer prompts into the shared Session, so model requests follow the viewer input the host forwards.' }, 'packages/experimental/plugin-market-bundle': { kind: 'indirect', reason: 'Mounts the pluginMarket service, which lets the Creator preset register the plugin_market tool documented in packages/boot/plugin-market.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 483542be3a..5bde0b3548 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -76,6 +76,7 @@ "@deepseek-ai/dsh-experimental-client-ui-cot-translation/client": ["./packages/experimental/client-ui-cot-translation/src/client/index.ts"], "@deepseek-ai/dsh-experimental-cot-translation-bundle": ["./packages/experimental/cot-translation-bundle/src/index.ts"], "@deepseek-ai/dsh-experimental-speech-to-text-sensevoice": ["./packages/experimental/speech-to-text-sensevoice/src/index.ts"], + "@deepseek-ai/dsh-speech-to-text-deepseek": ["./packages/experimental/speech-to-text-deepseek/src/index.ts"], "@deepseek-ai/dsh-experimental-api-speech-to-text": ["./packages/experimental/api-speech-to-text/src/index.ts"], "@deepseek-ai/dsh-experimental-client-ui-voice-input": ["./packages/experimental/client-ui-voice-input/src/index.ts"], "@deepseek-ai/dsh-experimental-voice-input-bundle": ["./packages/experimental/voice-input-bundle/src/index.ts"], diff --git a/tsconfig.host.json b/tsconfig.host.json index fcfa6b4612..409d95672a 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -38,6 +38,7 @@ "apps/web/tests/scaffold.ts", "apps/web/tests/clock.e2e.ts", "apps/web/tests/voice-input.e2e.ts", + "apps/web/tests/voice-input-cloud.e2e.ts", "apps/web/tests/cot-translation.e2e.ts", "apps/web/tests/cot-translation-paid.e2e.ts", "apps/web/tests/forge-panel.e2e.ts", @@ -293,6 +294,7 @@ { "path": "./packages/telemetry/otel" }, { "path": "./packages/experimental/speech-to-text" }, { "path": "./packages/experimental/speech-to-text-sensevoice" }, + { "path": "./packages/experimental/speech-to-text-deepseek" }, { "path": "./packages/experimental/api-speech-to-text" }, { "path": "./packages/experimental/voice-input-bundle" }, { "path": "./packages/experimental/plugin-market-bundle" },