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
This commit is contained in:
LegGasai committed 2026-11-06 17:28:46 +08:00
1 parent 36c44b9b7d
commit fadf0ca9f4
121 files changed
+2915 -213

No files matched your search

@@ -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
@@ -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.
@@ -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` 的重试,以及在真实组合中通过浏览器登录并对本机服务听写。
@@ -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]
@@ -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"
@@ -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"
@@ -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
@@ -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
@@ -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
+5 -2
View File
@@ -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
+172
View File
@@ -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('<title>Authorized</title>'); return }
if (req.method === 'POST' && url.pathname === '/auth-api/v0/dsh/auth_init') {
const payload = JSON.parse(body.toString('utf8')) as Record<string, unknown>
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<void>((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<void>((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<ReturnType<typeof mockServices>>
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)
})
+2 -1
View File
@@ -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 }] },
+6 -6
View File
@@ -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([])
})
+1
View File
@@ -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",
+39 -4
View File
@@ -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<string>
/** 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<string>
}
@@ -3437,6 +3441,37 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-skill-office -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-speech-to-text-deepseek -->
<a id="deepseek-aidsh-speech-to-text-deepseek"></a>
## `@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[]
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-speech-to-text-deepseek -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-spill-local -->
<a id="deepseek-aidsh-spill-local"></a>
+39 -4
View File
@@ -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<string>
/** 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<string>
}
@@ -3439,6 +3443,37 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-skill-office -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-speech-to-text-deepseek -->
<a id="deepseek-aidsh-speech-to-text-deepseek"></a>
## `@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[]
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-speech-to-text-deepseek -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-spill-local -->
<a id="deepseek-aidsh-spill-local"></a>
+4
View File
@@ -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) |
+4
View File
@@ -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) |
+1 -1
View File
@@ -338,7 +338,7 @@ abstract signOut(client: AccountClientMetadata): Promise<AccountView>
abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable<AccountView>
/**
* 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.
*/
+1 -1
View File
@@ -338,7 +338,7 @@ abstract signOut(client: AccountClientMetadata): Promise<AccountView>
abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable<AccountView>
/**
* 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.
*/
+2 -2
View File
@@ -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
+8 -4
View File
@@ -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<SpeechSnapshot>
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<void>
@@ -145,8 +148,9 @@ prepare(id: SpeechProviderId, options?: SpeechPreparationOptions): void
async cancelPreparation(id: SpeechProviderId): Promise<void>
/**
* 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
+8 -4
View File
@@ -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<SpeechSnapshot>
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<void>
@@ -145,8 +148,9 @@ prepare(id: SpeechProviderId, options?: SpeechPreparationOptions): void
async cancelPreparation(id: SpeechProviderId): Promise<void>
/**
* 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
@@ -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
@@ -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.
@@ -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 与账号状态分开。
@@ -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 = () => {
@@ -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<string, number | undefined> => 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 })
@@ -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 }) => {
@@ -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()
@@ -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
@@ -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.
<a id="understand-the-implementation"></a>
@@ -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 或响应校验失败不会删除来源匹配的授权。
<a id="understand-the-implementation"></a>
@@ -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<string> = new Set(['https://api.deepseek.com', 'https://harness.deepseek.com'])
const LOOPBACK_HOSTS: ReadonlySet<string> = 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<string>
private readonly rewriteBrowserOrigin: boolean
private readonly platform: 'darwin' | 'win32' | null
private readonly requestHeaders: Record<string, string>
@@ -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<string | undefined> {
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
}
@@ -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 () => {
@@ -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
@@ -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.
@@ -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 和响应校验失败区分开,使客户端可以提示检查网络。
@@ -93,7 +93,7 @@ export abstract class DeepSeekAccount extends Service {
*/
abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable<AccountView>
/**
* 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.
*/
@@ -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
@@ -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.
-----
@@ -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` 提供选择器选项。提供方拒绝不可用的源,以及对进行中任务的源变更。
-----
@@ -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<Transcript> {
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 })
}
}
}
@@ -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. */
@@ -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' },
})
})
@@ -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
@@ -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.
@@ -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;固定私有部署仅显示配置的源。手动选择只使用指定源,自动选择沿用提供方的比较与回退策略。当前卡片中的重试会保留选择,不修改部署配置或识别偏好。准备期间不能改源,资源就绪后隐藏源选择器。
@@ -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": {
@@ -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<InjectFace<VoiceInputInjected>, 'prepare' | 'cancelPreparation'>
& PropsLocale<typeof NS> & { readonly provider: SpeechProviderView; readonly connected: boolean }
& PropsLocale<typeof NS> & {
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<SpeechPreparationStat
}
/** Render a collapsed current-step summary or all Host-owned preparation steps. */
export function PreparationCard({ provider, connected, prepare, cancelPreparation, t }: PreparationCardProps) {
export function PreparationCard({ provider, connected, prepare, cancelPreparation, signIn, t }: PreparationCardProps) {
const state = provider.preparation
const [expanded, setExpanded] = useState(false), [now, setNow] = useState(Date.now), [error, setError] = useState('')
const [source, setSource] = useState(''), [submitting, setSubmitting] = useState(false)
@@ -69,9 +75,10 @@ export function PreparationCard({ provider, connected, prepare, cancelPreparatio
: state.phase === 'downloading' ? t('short.downloading')
: state.phase === 'failed' ? t('short.failed')
: state.phase === 'ready' && provider.location === 'cloud' ? t('cloudReady')
: t(`preparation.${state.phase}`, { name: provider.name })
: state.phase === 'unavailable' ? t(`unavailable.${state.reason}`)
: t(`preparation.${state.phase}`, { name: provider.name })
return <section className={css.preparation} data-speech-provider={provider.id}>
<strong>{provider.name}</strong>
<strong>{providerLabel(provider, t)}</strong>
{state.phase === 'unprepared' && provider.location === 'host-local' && provider.setupEstimate && <div className={css.setupEstimate}>
<p>{t('setup.local')}</p>
<dl>
@@ -119,6 +126,8 @@ export function PreparationCard({ provider, connected, prepare, cancelPreparatio
<small className={css.metric}>{t(selectedSource === '' ? 'sourceAutoHelp' : 'sourceManualHelp')}</small>
</div>}
<div className={css.preparationActions}>
{state.phase === 'unavailable' && signIn !== undefined
&& <Button variant="outline" size="sm" disabled={!connected} onClick={signIn}>{t('signIn')}</Button>}
{canPrepare && <Button variant="outline" size="sm" disabled={!connected || submitting}
onClick={() => { void run(() => selectedSource === '' ? prepare(provider.id) : prepare(provider.id, { downloadSource: selectedSource })) }}>{t(state.phase === 'unprepared' ? 'prepare' : 'retryPrepare')}</Button>}
{preparing && state.phase !== 'waking' && <Button variant="ghost" size="sm" disabled={!connected || submitting || state.phase === 'cancelling'}
@@ -129,36 +138,58 @@ export function PreparationCard({ provider, connected, prepare, cancelPreparatio
}
/** Recognition preferences and preparation cards shared by plugin details and Settings. */
export function VoicePreparation({ useSpeechReadiness, ...props }: Pick<InjectFace<VoiceInputInjected>,
'useSpeechReadiness' | 'configure' | 'prepare' | 'cancelPreparation' | 'createRecording' | 'useMicrophoneDevice' | 'selectMicrophone'> & PropsLocale<typeof NS>) {
export function VoicePreparation({ useSpeechReadiness, useAccountSignIn, signIn, ...props }: Pick<InjectFace<VoiceInputInjected>,
'useSpeechReadiness' | 'useAccountSignIn' | 'signIn' | 'configure' | 'prepare' | 'cancelPreparation' | 'createRecording'
| 'useMicrophoneDevice' | 'selectMicrophone'> & PropsLocale<typeof NS>) {
const readiness = useSpeechReadiness(value => value), catalog = readiness.catalog
const signInPresent = useAccountSignIn(present => present)
const [saving, setSaving] = useState(false), [error, setError] = useState('')
const configure = async (patch: SpeechSelectionPatch): Promise<void> => {
setSaving(true); setError('')
try { await props.configure(patch) } catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)) }
finally { setSaving(false) }
}
const selected = catalog?.providers.find(provider => provider.id === catalog.selection.providerId)
const selected = selectedProvider(catalog)
const cloud = catalog?.providers.find(provider => provider.location === 'cloud')
const signedIn = cloud !== undefined && cloud.preparation.phase !== 'unavailable'
// Key order is the menu order: automatic detection, the UI languages, then the remaining recognition languages.
const languageNames: Readonly<Record<string, string>> = {
auto: props.t('auto'), zh: props.t('zh'), en: props.t('en'), yue: props.t('yue'), ja: props.t('ja'), es: props.t('es'), fr: props.t('fr'), de: props.t('de'), ru: props.t('ru'), pt: props.t('pt'), ko: props.t('ko'),
auto: props.t('auto'), zh: props.t('zh'), en: props.t('en'), ja: props.t('ja'), es: props.t('es'), fr: props.t('fr'), de: props.t('de'), ru: props.t('ru'), pt: props.t('pt'), yue: props.t('yue'), ko: props.t('ko'),
}
const language = catalog?.selection.language
const languages = offeredLanguages(catalog, Object.keys(languageNames))
const fallback = selected !== undefined && language !== undefined && !selected.languages.includes(language)
// An explicit choice shows only its provider; Automatic lists cloud providers before Host-local ones.
const cards = catalog === null ? []
: catalog.selection.mode === 'explicit' ? catalog.providers.filter(provider => provider.id === catalog.selection.providerId)
: [...catalog.providers].sort((a, b) => Number(a.location !== 'cloud') - Number(b.location !== 'cloud'))
return <div>
{catalog && <div className={css.preferences}>
<MicrophonePicker {...props} />
<label>{props.t('provider')}<select value={catalog.selection.providerId} disabled={!readiness.connected || saving}
onChange={(event) => { void configure({ providerId: event.target.value as SpeechProviderId }) }}>
{catalog.providers.map(provider => <option key={provider.id} value={provider.id}>{provider.name}</option>)}
<label>{props.t('provider')}<select value={catalog.selection.mode === 'auto' ? 'auto' : catalog.selection.providerId}
disabled={!readiness.connected || saving}
onChange={(event) => { void configure({ providerId: event.target.value === 'auto' ? 'auto' : event.target.value as SpeechProviderId }) }}>
<option value="auto">{props.t('providerAuto')}</option>
{catalog.providers.map(provider => <option key={provider.id} value={provider.id}>{providerLabel(provider, props.t)}</option>)}
</select></label>
{selected && <p className={css.selectionHint} role="status">
<span>{props.t('selection.current', { name: providerLabel(selected, props.t) })}</span>
{catalog.selection.mode === 'auto' && cloud !== undefined
&& <span className={css.metric}>{props.t(signedIn ? 'selection.signedIn' : 'selection.signedOut')}</span>}
</p>}
<label>{props.t('language')}<select value={catalog.selection.language} disabled={!readiness.connected || saving}
onChange={(event) => { void configure({ language: event.target.value }) }}>
{selected?.languages.map(language =>
<option key={language} value={language}>{languageNames[language] ?? language}</option>)}
{languages.map(code => <option key={code} value={code}>{languageNames[code] ?? code}</option>)}
</select></label>
{fallback && <p className={css.metric} role="status">
{props.t(`languageFallback.${selected.location}`, { language: languageNames[catalog.selection.language] ?? catalog.selection.language })}
</p>}
<p>{props.t(selected?.location === 'cloud' ? 'cloud' : 'local')}</p>
{catalog.selection.mode === 'auto' && <p className={css.metric}>{props.t('selection.autoHelp')}</p>}
{error && <p role="alert">{props.t('failed', { message: error })}</p>}
</div>}
{catalog?.providers.map(provider =>
<PreparationCard key={provider.id} provider={provider} connected={readiness.connected} {...props} />)}
{cards.map(provider => <PreparationCard key={provider.id} provider={provider} connected={readiness.connected}
signIn={signInPresent ? signIn : undefined} {...props} />)}
{!catalog && <p role="status">{props.t('loading')}</p>}
{readiness.error && <p role="alert">{props.t('failed', { message: readiness.error })}</p>}
</div>
@@ -18,6 +18,7 @@
.summaryRow { min-height: 28px; height: auto; flex-wrap: wrap; gap: 4px; }
.summaryTitle { flex: 1; min-width: 0; }
.metric { font-size: 12px; color: var(--dsw-alias-label-tertiary); }
.selectionHint { display: flex; flex-wrap: wrap; gap: 4px 8px; margin: 0; font-size: 12px; color: var(--dsw-alias-label-secondary); }
.progress { width: 100%; height: 6px; accent-color: var(--dsw-alias-state-business-primary); }
.steps { list-style: none; display: flex; flex-direction: column; gap: 14px; padding: 16px 0 2px; margin: 0; }
.steps li { display: flex; align-items: flex-start; gap: 10px; line-height: 18px; }
@@ -29,6 +30,7 @@
.preferences { display: grid; gap: 12px; font-size: 13px; margin: 18px 0; }
.deviceRow, .preferences label, .sourceChoice label { display: grid; grid-template-columns: 100px minmax(120px, 280px); align-items: center; gap: 12px; }
.preferences select, .sourceChoice select { border: 0.5px solid var(--dsw-alias-border-l1); border-radius: 6px; padding: 6px 10px; background: transparent; color: inherit; font: inherit; }
.preferences select:disabled { opacity: 0.5; cursor: default; }
.sourceChoice { display: grid; gap: 6px; }
.preferences p { margin: 0; }
.settingsCard { list-style: none; padding: 16px; border: 0.5px solid var(--dsw-alias-border-l1); border-radius: 10px; }
@@ -3,10 +3,13 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type { TokenSpan } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type { TranscriptionRequest } from '@deepseek-ai/dsh-experimental-api-speech-to-text/types'
import type { SpeechPreparationOptions, SpeechProviderId, SpeechSelection, SpeechSelectionPatch, Transcript } from '@deepseek-ai/dsh-experimental-speech-to-text/types'
import type {
SpeechPreparationOptions, SpeechProviderId, SpeechProviderView, SpeechSelection, SpeechSelectionPatch, Transcript,
} from '@deepseek-ai/dsh-experimental-speech-to-text/types'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { audioBase64, type Recording } from './audio.ts'
import { failureText } from './failure-text.ts'
import { canRecord, localProvider, selectedProvider, voiceGuidance } from './guidance.ts'
import type { MicrophoneDevice } from './microphone-device.ts'
import type { SpeechReadiness } from './readiness.ts'
import { Waveform } from './Waveform.tsx'
@@ -27,6 +30,8 @@ export interface VoiceInputActions {
prepare: (providerId: SpeechProviderId, options?: SpeechPreparationOptions) => Promise<void>
cancelPreparation: (providerId: SpeechProviderId) => Promise<void>
configure: (patch: SpeechSelectionPatch) => Promise<void>
/** Open account sign-in from the current click; does nothing while the account UI offers no entry. */
signIn: () => void
}
/** Entry-injected Host readiness and microphone operations. */
@@ -36,6 +41,8 @@ export interface VoiceInputInjected extends VoiceInputActions {
microphoneDevice: HostObservable<MicrophoneDevice>
/** Whether the Plugins page navigation service is present; the setup dialog offers the details only while it is. */
pluginNavigation: HostObservable<boolean>
/** Whether the account UI offers sign-in; sign-in actions appear only while it does. */
accountSignIn: HostObservable<boolean>
}
}
@@ -44,6 +51,8 @@ export type VoiceInputProps = Pick<PropsRuntime<'conversation.input.activity'>,
& PropsLocale<typeof NS> & InjectFace<VoiceInputInjected>
type Phase = 'idle' | 'requesting' | 'recording' | 'transcribing' | 'feedback'
/** Recovery offered beside a classified failure; switching to local recognition names its target. */
type FeedbackAction = { readonly kind: 'sign-in' } | { readonly kind: 'use-local'; readonly provider: SpeechProviderView }
interface ActiveRecording {
readonly capture: Recording
readonly abort: AbortController
@@ -62,14 +71,16 @@ async function disposeRecording(capture: Recording): Promise<void> {
}
/** Render a compact microphone or an expanded capture, transcription, or retry row. */
export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
createRecording, transcribe, openSettings, useSpeechReadiness, usePluginNavigation, t }: VoiceInputProps) {
export function VoiceInput({ sessionId, inputActions, locked, onActiveChange, createRecording, transcribe, openSettings,
configure, signIn, useSpeechReadiness, usePluginNavigation, useAccountSignIn, t }: VoiceInputProps) {
const readiness = useSpeechReadiness(value => value), catalog = readiness.catalog
const navigable = usePluginNavigation(present => present)
const provider = catalog?.providers.find(item => item.id === catalog.selection.providerId)
const usable = readiness.connected && (provider?.preparation.phase === 'ready' || provider?.preparation.phase === 'standby'
|| provider?.preparation.phase === 'waking')
const signInPresent = useAccountSignIn(present => present)
const provider = selectedProvider(catalog), local = localProvider(catalog)
const usable = readiness.connected && canRecord(provider)
const cloud = provider?.location === 'cloud'
const [phase, setPhase] = useState<Phase>('idle'), [message, setMessage] = useState(''), [pending, setPending] = useState('')
const [action, setAction] = useState<FeedbackAction>()
const [setupOpen, setSetupOpen] = useState(false)
useEffect(() => { if (usable) setSetupOpen(false) }, [usable])
const current = useRef<ActiveRecording>(), generation = useRef(0)
@@ -81,10 +92,10 @@ export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
const active = current.current
current.current = undefined
if (active) { clearTimeout(active.timer); active.abort.abort(); void disposeRecording(active.capture) }
setPending(''); setMessage(''); setPhase('idle'); setSetupOpen(false)
setPending(''); setMessage(''); setAction(undefined); setPhase('idle'); setSetupOpen(false)
}
useEffect(() => {
setPending(''); setMessage(''); setPhase('idle'); setSetupOpen(false)
setPending(''); setMessage(''); setAction(undefined); setPhase('idle'); setSetupOpen(false)
const blur = (): void => { if (current.current?.phase === 'recording') cancel() }
const visibility = (): void => {
if (document.hidden && current.current && current.current.phase !== 'transcribing') cancel()
@@ -104,7 +115,7 @@ export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
}
}, [sessionId])
const feedback = (text: string): void => { setMessage(text); setPhase('feedback') }
const feedback = (text: string, recovery?: FeedbackAction): void => { setMessage(text); setAction(recovery); setPhase('feedback') }
const finish = async (): Promise<void> => {
const active = current.current
if (!active || active.phase !== 'recording') return
@@ -115,9 +126,17 @@ export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
const audio = await active.capture.stop(active.maxDurationSeconds)
if (run !== generation.current) return
if (audio.byteLength > active.maxAudioBytes) { feedback(t('tooLarge')); return }
const result = await transcribe({ audioBase64: audioBase64(audio), ...active.selection }, active.abort.signal)
const result = await transcribe({ audioBase64: audioBase64(audio), providerId: active.selection.providerId,
language: active.selection.language }, active.abort.signal)
if (run !== generation.current) return
if (!result.ok) { feedback(t('failed', { message: result.error.message })); return }
if (!result.ok) {
const code = result.error.code === 'speech/transcription-failed' ? result.error.details.code : undefined
if (code === undefined) { feedback(t('failed', { message: result.error.message })); return }
feedback(t(`failure.${code}`), code === 'sign-in-required' && signInPresent ? { kind: 'sign-in' }
: (code === 'service-unavailable' || code === 'quota-exceeded') && local !== undefined
? { kind: 'use-local', provider: local } : undefined)
return
}
if (result.value.text === '') { feedback(t('empty')); return }
if (!inputActions.insertText(result.value.text, active.span)) { setPending(result.value.text); feedback(t('conflict')); return }
setPhase('idle')
@@ -133,7 +152,7 @@ export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
span: inputActions.captureInsertion(), selection: catalog.selection,
maxDurationSeconds: catalog.maxDurationSeconds, maxAudioBytes: catalog.maxAudioBytes, phase: 'requesting' }
current.current = active
setMessage(''); setPending(''); setPhase('requesting')
setMessage(''); setPending(''); setAction(undefined); setPhase('requesting')
try {
await active.capture.start((failure) => {
if (run !== generation.current || current.current !== active || active.phase === 'transcribing') return
@@ -150,17 +169,25 @@ export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
if (run === generation.current) { current.current = undefined; feedback(failureText(failure, t)) }
}
}
const guidance = voiceGuidance(catalog, readiness.connected)
const useLocal = (target: SpeechProviderView): void => {
setSetupOpen(false); setAction(undefined); setPhase('idle')
void configure({ providerId: target.id }).then(() => {
if (target.preparation.phase === 'unprepared' && navigable) openSettings()
}, (failure: unknown) => { feedback(failureText(failure, t)) })
}
const requestSignIn = (): void => { setSetupOpen(false); setAction(undefined); setPhase('idle'); signIn() }
if (!expanded) return <>
<Tooltip label={t('dictate')} disabled={!usable} side="top" portal>
<Tooltip label={t(cloud ? 'dictateCloud' : 'dictate')} disabled={!usable} side="top" portal>
<span className={css.triggerAnchor}><Button className={css.trigger} size="sm" disabled={locked}
aria-label={t(usable ? 'start' : 'setupPrompt.trigger')} aria-haspopup={usable ? undefined : 'dialog'}
onMouseDown={(event) => { event.preventDefault() }}
onClick={() => { if (usable) void start(); else setSetupOpen(true) }}><IconMicrophoneOutlineRegular size={18} /></Button></span>
</Tooltip>
<VoiceSetupDialog open={setupOpen && !usable}
needsInstallation={readiness.connected && provider?.location === 'host-local' && provider.preparation.phase === 'unprepared'}
<VoiceSetupDialog open={setupOpen && guidance !== null} kind={guidance ?? 'unavailable'}
onDismiss={() => { 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 <div className={css.captureRow} data-voice-activity={phase}>
<Button type="button" className={css.roundButton} size="sm" aria-label={t(pending ? 'discard' : 'cancel')}
@@ -169,9 +196,12 @@ export function VoiceInput({ sessionId, inputActions, locked, onActiveChange,
: <span className={css.activityMessage} role="status" title={pending || message}>
{(phase === 'requesting' || phase === 'transcribing') && <StateDot state="ongoing" />}
{phase === 'feedback' ? message : t(phase === 'requesting' ? 'requesting'
: provider?.preparation.phase === 'waking' ? 'wakingShort' : 'transcribingShort')}</span>}
: provider?.preparation.phase === 'waking' ? 'wakingShort' : cloud ? 'transcribingCloud' : 'transcribingShort')}</span>}
{phase === 'recording' && <Button type="button" className={css.roundButton} size="sm" aria-label={t('stop')}
onClick={() => { void finish() }}><IconStopFillRegular size={14} /></Button>}
{phase === 'feedback' && action !== undefined && <Button className={css.inlineAction} size="sm" type="button"
onClick={action.kind === 'sign-in' ? requestSignIn : () => { useLocal(action.provider) }}>
{t(action.kind === 'sign-in' ? 'signIn' : 'useLocal')}</Button>}
{phase === 'feedback' && (pending
? <Button className={css.inlineAction} size="sm" type="button" onClick={() => {
if (inputActions.insertText(pending, inputActions.captureInsertion())) { setPending(''); setPhase('idle') }
@@ -2,31 +2,45 @@
import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
import type { VoiceGuidance } from './guidance.ts'
import type { NS } from './locales.ts'
type VoiceSetupDialogProps = PropsLocale<typeof NS>
& Pick<PropsRuntime<'plugins.bundle.activation'>, 'onDismiss'>
& {
open: boolean
needsInstallation: boolean
kind: VoiceGuidance
/** Open the plugin details; the details button is absent while it is undefined. */
onOpenDetails: PropsRuntime<'plugins.bundle.activation'>['onOpenDetails'] | undefined
/** Open account sign-in from this click; absent while the account UI offers no sign-in entry. */
onSignIn?: (() => void) | undefined
/** Switch the saved preference to local recognition; absent without a local provider. */
onUseLocal?: (() => void) | undefined
}
const TITLE = { install: 'setupPrompt.title', 'install-or-sign-in': 'choicePrompt.title', 'sign-in': 'signInPrompt.title', unavailable: 'setupPrompt.unavailableTitle' } as const
const BODY = { install: 'setupPrompt.body', 'install-or-sign-in': 'choicePrompt.body', 'sign-in': 'signInPrompt.body', unavailable: 'setupPrompt.unavailableBody' } as const
/**
* Guide activation or microphone clicks to the existing plugin details.
* @param props - visibility, installation need and navigation callbacks.
* Guide activation or microphone clicks to sign-in or the existing plugin details.
* @param props - visibility, guidance kind and navigation callbacks.
* @returns a dismissible prompt that never starts preparation or recording.
*/
export function VoiceSetupDialog({ open, needsInstallation, onDismiss, onOpenDetails, t }: VoiceSetupDialogProps) {
return <Modal open={open} title={t(needsInstallation ? 'setupPrompt.title' : 'setupPrompt.unavailableTitle')}
closeLabel={t('cancel')} onClose={onDismiss}
export function VoiceSetupDialog({ open, kind, onDismiss, onOpenDetails, onSignIn, onUseLocal, t }: VoiceSetupDialogProps) {
const offersSignIn = kind === 'sign-in' || kind === 'install-or-sign-in'
const signIn = offersSignIn && onSignIn !== undefined
const details = onOpenDetails !== undefined && kind !== 'sign-in'
return <Modal open={open} title={t(TITLE[kind])} closeLabel={t('cancel')} onClose={onDismiss}
footer={<>
<Button variant="ghost" onClick={onDismiss}>{t('setupPrompt.later')}</Button>
{onOpenDetails !== undefined && <Button variant="primary" data-modal-autofocus onClick={onOpenDetails}>
{t(needsInstallation ? 'setupPrompt.open' : 'setupPrompt.details')}
{kind === 'sign-in' && onUseLocal !== undefined
? <Button variant="ghost" onClick={onUseLocal}>{t('useLocal')}</Button>
: <Button variant="ghost" onClick={onDismiss}>{t('setupPrompt.later')}</Button>}
{details && <Button variant={signIn ? 'outline' : 'primary'} data-modal-autofocus={signIn ? undefined : true} onClick={onOpenDetails}>
{t(kind === 'install' ? 'setupPrompt.open' : kind === 'install-or-sign-in' ? 'choicePrompt.download' : 'setupPrompt.details')}
</Button>}
{signIn && <Button variant="primary" data-modal-autofocus onClick={onSignIn}>{t('signIn')}</Button>}
</>}>
<p>{t(needsInstallation ? 'setupPrompt.body' : 'setupPrompt.unavailableBody')}</p>
<p>{t(BODY[kind])}</p>
{offersSignIn && !signIn && <p>{t('signInFromSettings')}</p>}
</Modal>
}
@@ -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<typeof NS>
& Pick<InjectFace<VoiceInputInjected>, 'useSpeechReadiness'>
& Pick<InjectFace<VoiceInputInjected>, '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 <VoiceSetupDialog open={needsSetup} needsInstallation onDismiss={onDismiss} onOpenDetails={onOpenDetails} t={t} />
if (phase !== undefined && phase !== 'checking' && prompt === null) onDismiss()
}, [phase, prompt, onDismiss])
return <VoiceSetupDialog open={prompt !== null} kind={prompt ?? 'install'} onDismiss={onDismiss} onOpenDetails={onOpenDetails}
onSignIn={signInPresent ? () => { onDismiss(); signIn() } : undefined} t={t} />
}
@@ -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<typeof NS>['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))]
}
@@ -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<VoiceKey, string> = {
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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** 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<keyof typeof en, string>
/** 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<keyof typeof en, string>
@@ -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
@@ -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<Recording['start']>(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<SpeechReadiness>({ connected: true, error: null, catalog: initial })
const settle = Promise.withResolvers<RemoteResult<Transcript>>()
const transcribe = vi.fn<(request: TranscriptionRequest, signal: AbortSignal) => Promise<RemoteResult<Transcript>>>(() => 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(<VoiceInput {...props} />)
return { props, settle, transcribe, inputActions }
}
async function record(): Promise<void> {
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<typeof composer>, code: SpeechFailureCode | undefined): Promise<void> {
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<SpeechReadiness>({ 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(<VoicePreparation {...props} />)
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<HTMLSelectElement>(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<HTMLSelectElement>(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<HTMLSelectElement>(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<SpeechReadiness>({ connected: true, error: null, catalog: initial })),
useAccountSignIn: bindSnapshotSelector(createSnapshotStore(true)) } as VoiceSetupPromptProps
render(<VoiceSetupPrompt {...props} />)
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()
})
})
@@ -31,6 +31,7 @@ function assertVoiceActions(value: Record<string, unknown>): 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)
@@ -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<SpeechReadiness>({ 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(<VoicePreparation {...props} />)
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<HTMLOptionElement>('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')
@@ -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) {
@@ -15,11 +15,12 @@ function fixture() {
const state = createSnapshotStore<SpeechReadiness>({ 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(<VoiceSetupPrompt {...props} />)
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 }],
} }) })
} }
@@ -27,7 +27,7 @@ function fixture(recording?: Recording, navigable = true) {
pruneAttachments: vi.fn(), submit: vi.fn() }
const readiness = createSnapshotStore<SpeechReadiness>({ 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<RemoteResult<Transcript>>>(
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(<VoiceInput {...props} />)
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))
@@ -55,6 +55,9 @@
},
{
"path": "../../client/ui-plugin-manager/tsconfig.client.json"
},
{
"path": "../../client/ui-settings-account"
}
]
}
@@ -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
@@ -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)
-----
<a id="use-this-package"></a>
## 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.
-----
<a id="understand-the-implementation"></a>
## Understand the implementation
<details>
<summary>Maintainer details — click to expand</summary>
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.
</details>
-----
<a id="further-exploration"></a>
## Further Exploration
[Voice input subsystem](../../../docs/subsystems/voice-input.md)
-----
<a id="model-experience"></a>
## 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
<a id="known-limitations-and-deferred-work"></a>
- 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.
-----
<a id="dev-note"></a>
### Dev Note
<details>
<summary>Maintainer details — click to expand</summary>
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.
</details>
@@ -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)
-----
<a id="use-this-package"></a>
## 使用此包
[语音输入 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)时,只作废被拒绝的那个令牌,账号随之退出登录,失败提示用户重新登录。
-----
<a id="understand-the-implementation"></a>
## 理解实现
<details>
<summary>维护者信息 — 点击展开</summary>
就绪状态跟随账号服务的 `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 路径、状态码和返回码,从不记录音频、令牌或响应正文。
</details>
-----
<a id="further-exploration"></a>
## 进一步探索
[语音输入子系统](../../../docs/subsystems/voice-input.zh.md)
-----
<a id="model-experience"></a>
## 模型体验
无,因为录音与转写不进入模型请求;之后的文字由普通用户提交拥有。
#### KV 缓存影响
没有直接影响;普通提交拥有消息内容。
## 已知限制与后续工作
<a id="known-limitations-and-deferred-work"></a>
- 只支持对完整录音做 One-Shot 转写,不使用 WebSocket 流式接口和 `fetch_cached`。录音不能超过 120 秒。
-----
<a id="dev-note"></a>
### 开发备注
<details>
<summary>维护者信息 — 点击展开</summary>
测试都使用本机回环服务替身:Provider 测试使用 `tests/service-double.ts`,`apps/web/tests/voice-input-cloud.e2e.ts` 在发布的组合中验证浏览器登录与听写。没有测试访问生产接口,因为其账号令牌只能通过交互式浏览器登录获得。
</details>
@@ -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."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "DeepSeek cloud recognition",
"description": "Transcribe recordings with the DeepSeek cloud service after signing in to a DeepSeek account."
}
}
@@ -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."
}
}
@@ -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."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "DeepSeek クラウド認識",
"description": "DeepSeek アカウントにログインすると、DeepSeek のクラウドサービスで録音を文字起こしします。"
}
}
@@ -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."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "Облачное распознавание DeepSeek",
"description": "Расшифровывает записи облачным сервисом DeepSeek после входа в аккаунт DeepSeek."
}
}
@@ -0,0 +1,6 @@
{
"meta": {
"title": "DeepSeek 云端识别",
"description": "登录 DeepSeek 账号后,使用 DeepSeek 云端服务转写录音。"
}
}
@@ -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
}
}
}
@@ -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<Record<string, string>> = { 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<ArrayBuffer>
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}` }
}
@@ -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<SpeechPreparationState>
/** 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<void> {}
/**
* Record account presence and re-inspect.
* @param signedIn - whether an account is stored.
* @returns after the resulting inspection settles.
*/
async account(signedIn: boolean): Promise<void> {
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<void> {
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()
}
}
@@ -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<Partial<Config>, 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)],
}
}
@@ -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<SpeechPreparationState> {
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<Transcript> {
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<string, string> = { [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')
}
}
@@ -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<ArrayBuffer>
readonly contentType: string
readonly headers: Readonly<Record<string, string>>
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<number, SpeechFailureCode | 'empty'>([
[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<AttemptOutcome> {
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<string> {
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}` }
}
@@ -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' })
})
@@ -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)
})
})
@@ -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<AccountView> {
while (!signal.aborted) {
yield { status, links: { usageUrl: '', topUpUrl: '' }, attempt: null }
await new Promise<void>((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<DeepSeekAccount> 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<unknown>): Promise<SpeechTranscriptionError> {
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<IteratorResult<AccountView>>((_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<DeepSeekAccount> 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')
})
@@ -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> = {}): 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<AttemptRequest> = {}) {
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, '<html>'))).toEqual(failed('HTTP 404'))
expect(await outcome(raw(204, ''))).toEqual(failed('HTTP 204'))
expect(await outcome(raw(200, '<html>secret</html>'))).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<void>((resolve) => { closed.listen(0, '127.0.0.1', resolve) })
const address = closed.address()
await new Promise<void>((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')
})
})
@@ -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<string, string>
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<string, string>()
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<void>((resolve) => { server.listen(0, '127.0.0.1', resolve) })
onTestFinished(() => new Promise<void>((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)
}
@@ -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"
}
]
}
@@ -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 })
@@ -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
@@ -25,10 +25,12 @@ This Service Definition selects named speech recognizers through `ctx.speechToTe
<a id="use-this-package"></a>
## 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.
-----
<a id="understand-the-implementation"></a>
@@ -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.
@@ -25,10 +25,12 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用此包
通过[语音输入 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 诊断信息。
-----
<a id="understand-the-implementation"></a>
@@ -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。两者均在解码采样前拒绝不一致的头部和长度。
@@ -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)
}
}
@@ -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<string>
/** 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<string>
}
@@ -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<void> {
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<void> {
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 {
@@ -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. */
@@ -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<string, unknown>) => { 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() }
})
@@ -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 }) }
}
@@ -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() }
})
@@ -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
@@ -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.
-----
<a id="understand-the-implementation"></a>
@@ -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 服务。
-----
<a id="understand-the-implementation"></a>
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more