From 2d0360870cd61ed70886b14b609ffb72ea1ac30b Mon Sep 17 00:00:00 2001 From: yudshj Date: Mon, 5 Oct 2026 16:28:30 +0800 Subject: [PATCH] feat(voice-input): select microphone with menu-only input levels --- apps/web/tests/voice-input.e2e.ts | 38 +++- .../client-ui-voice-input/README.i18n.yaml | 4 +- .../client-ui-voice-input/README.md | 2 + .../client-ui-voice-input/README.zh.md | 2 + .../src/client/MicrophonePicker.tsx | 93 +++++++++ .../src/client/PreparationCard.tsx | 4 +- .../src/client/VoiceInput.module.css | 14 ++ .../src/client/VoiceInput.tsx | 5 +- .../client-ui-voice-input/src/client/audio.ts | 56 ++++-- .../src/client/locales.ts | 10 + .../src/client/microphone-device.ts | 20 ++ .../client-ui-voice-input/src/client/mount.ts | 7 +- .../tests/audio-fixture.client.ts | 7 +- .../tests/audio.client.spec.ts | 53 +++++ .../tests/microphone-picker.client.spec.tsx | 182 ++++++++++++++++++ .../tests/preparation.client.spec.tsx | 3 + .../tests/voice-input.client.spec.tsx | 1 + snapshots/web/voice-input/device.expected.md | 6 + 18 files changed, 481 insertions(+), 26 deletions(-) create mode 100644 packages/experimental/client-ui-voice-input/src/client/MicrophonePicker.tsx create mode 100644 packages/experimental/client-ui-voice-input/src/client/microphone-device.ts create mode 100644 packages/experimental/client-ui-voice-input/tests/microphone-picker.client.spec.tsx create mode 100644 snapshots/web/voice-input/device.expected.md diff --git a/apps/web/tests/voice-input.e2e.ts b/apps/web/tests/voice-input.e2e.ts index 82634fa7eb..853cd1508e 100644 --- a/apps/web/tests/voice-input.e2e.ts +++ b/apps/web/tests/voice-input.e2e.ts @@ -62,7 +62,14 @@ it.skipIf(webSnapshotMode() === 'record')('guides voice setup, records from stan resources.browser = browser const page = await newEnglishPage(browser), tripwire = watchConsole(page) await page.addInitScript(() => { - const holder = window as Window & { voiceTestRecorder?: MediaRecorder } + const holder = window as Window & { voiceTestRecorder?: MediaRecorder; voiceTestStreams?: MediaStream[] } + holder.voiceTestStreams = [] + const getUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices) + navigator.mediaDevices.getUserMedia = async (constraints) => { + const stream = await getUserMedia(constraints) + holder.voiceTestStreams!.push(stream) + return stream + } const NativeRecorder = window.MediaRecorder window.MediaRecorder = class extends NativeRecorder { constructor(stream: MediaStream, options?: MediaRecorderOptions) { super(stream, options); holder.voiceTestRecorder = this } @@ -120,6 +127,33 @@ it.skipIf(webSnapshotMode() === 'record')('guides voice setup, records from stan expect(recognize).not.toHaveBeenCalled() preparation = { phase: 'standby' } for (const listener of readinessListeners) listener() + const devicePicker = page.getByRole('button', { name: 'Input device', exact: true }) + await devicePicker.click() + const level = page.getByRole('img', { name: 'Microphone input level', exact: true }) + await level.waitFor() + const devices = await page.evaluate(async () => (await navigator.mediaDevices.enumerateDevices()) + .filter(device => device.kind === 'audioinput' && device.deviceId !== 'default')) + const selectedDevice = devices[0]! + await page.getByRole('menuitem', { name: selectedDevice.label, exact: true }).click() + await page.getByRole('menuitem', { name: `${selectedDevice.label} Microphone input level`, exact: true }).waitFor() + await expect.poll(() => page.evaluate(() => { + const streams = (window as Window & { voiceTestStreams?: MediaStream[] }).voiceTestStreams! + return streams.filter(stream => stream.getTracks().some(track => track.readyState === 'live')).length + })).toBe(1) + await compareOrRefreshGolden(fileURLToPath(new URL('../../../snapshots/web/voice-input/device.expected.md', import.meta.url)), + await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), webSnapshotMode()) + for (const width of [1280, 360]) { + await page.setViewportSize({ width, height: 900 }) + await expect.poll(async () => { + const bounds = await page.getByRole('menu').boundingBox() + return bounds !== null && bounds.x >= 0 && bounds.x + bounds.width <= width + }).toBe(true) + } + await page.keyboard.press('Escape') + await level.waitFor({ state: 'hidden' }) + await expect.poll(() => page.evaluate(() => (window as Window & { voiceTestStreams?: MediaStream[] }).voiceTestStreams! + .every(stream => stream.getTracks().every(track => track.readyState === 'ended')))).toBe(true) + await page.setViewportSize({ width: 1280, height: 900 }) await page.getByRole('button', { name: 'New session', exact: true }).filter({ hasText: 'New Session' }).click() await mic.waitFor() await page.getByRole('button', { name: 'Plugins', exact: true }).click() @@ -134,6 +168,8 @@ it.skipIf(webSnapshotMode() === 'record')('guides voice setup, records from stan await input.fill(prefix) await mic.click() await page.getByRole('button', { name: 'Stop and transcribe', exact: true }).waitFor() + expect(await page.evaluate(() => (window as Window & { voiceTestStreams?: MediaStream[] }).voiceTestStreams! + .at(-1)!.getAudioTracks()[0]!.getSettings().deviceId)).toBe(selectedDevice.deviceId) await compareOrRefreshGolden(recordingExpected, await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd), webSnapshotMode()) expect(await page.getByRole('dialog').count()).toBe(0) diff --git a/packages/experimental/client-ui-voice-input/README.i18n.yaml b/packages/experimental/client-ui-voice-input/README.i18n.yaml index dd577cb202..3ca00b2971 100644 --- a/packages/experimental/client-ui-voice-input/README.i18n.yaml +++ b/packages/experimental/client-ui-voice-input/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 364c80ee00a374ff /deepseek-ai-dsh-experimental-client-ui-voice-input/use-this-package: - en: 44f25ad14ceda123 - zh: 43c4680be42af1cf + en: ff0d98de2970f93d + zh: c234972ea1803afb /deepseek-ai-dsh-experimental-client-ui-voice-input/understand-the-implementation: en: b3a7bb1a4f0b3c1e zh: 233d1c5ea2b16de8 diff --git a/packages/experimental/client-ui-voice-input/README.md b/packages/experimental/client-ui-voice-input/README.md index ea4b42a6fe..457341427e 100644 --- a/packages/experimental/client-ui-voice-input/README.md +++ b/packages/experimental/client-ui-voice-input/README.md @@ -27,6 +27,8 @@ This optional browser plugin adds an outline microphone icon between the model s Enable the [voice input bundle](../voice-input-bundle/README.md) from Plugins. After cache inspection, missing models trigger a setup prompt with Go to setup and Later actions. Go to setup opens bundle details; Download and prepare starts installation there. Intact cached models need no prompt or repeated installation. Before recognition is ready, guidance appears only on click, with no microphone tooltip. Clicking the microphone opens the same guidance dialog; its action opens the voice bundle details without recording or downloading. Cache inspection, preparation in progress, failures and disconnected services instead offer navigation to status, progress or error details. The dialog moves focus to its navigation action and keeps Tab traversal inside it; Later or Escape restores the previous focus without changing or submitting the draft. Before preparation, local providers can show their estimated disk, memory and setup-time requirements. The preparation summary starts collapsed; expand it to inspect completed, current and pending steps. Once ready, click the microphone, allow access and click Stop to transcribe. Cancel or Escape discards capture. Recognition feedback stays inside the toolbar. Provider and language preferences are saved from bundle details through the Settings service. Browser microphone access requires HTTPS or loopback and operating-system permission. +Choose **Input device** in bundle details to follow the system default or select a browser microphone. The selected input shows its live level only while the menu is open; selecting another input keeps the menu open for comparison. Closing the menu, hiding 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. A missing device or denied permission keeps the menu available for another choice; recording never silently substitutes a different device. + Before downloading or retrying, **Model download source** offers Automatic and the origins advertised by the Host. SenseVoice normally offers Hugging Face and HF-Mirror; a fixed private deployment exposes only its configured origin. Manual selection uses only that source, while Automatic preserves the provider’s comparison and fallback policy. The choice is retained for retries in the current card, without changing deployment configuration or recognition preferences. Source controls are unavailable during preparation and hidden when resources are ready. ----- diff --git a/packages/experimental/client-ui-voice-input/README.zh.md b/packages/experimental/client-ui-voice-input/README.zh.md index ab742a6043..b1861742fd 100644 --- a/packages/experimental/client-ui-voice-input/README.zh.md +++ b/packages/experimental/client-ui-voice-input/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" 在插件管理页启用[语音输入 Bundle](../voice-input-bundle/README.zh.md)。缓存检查后,缺少模型时弹出安装引导,可选择“前往安装”或“稍后”。“前往安装”打开 Bundle 详情,再点击“下载并准备”才开始安装。缓存完整时不弹引导,也无需重复安装。识别未就绪时不显示麦克风悬停提示,点击后才打开同一个引导弹窗;点击引导按钮进入语音 Bundle 详情,不会录音或下载。缓存检查、正在准备、准备失败或服务断连时,弹窗改为引导查看状态、进度或错误详情。弹窗将焦点移到导航按钮,并将 Tab 切换约束在弹窗内;选择“稍后”或按 Escape 关闭时恢复此前焦点,不改变或提交草稿。准备前,本地 Provider 可展示磁盘、内存与安装时间的估算。准备摘要默认折叠;展开后可查看已完成、当前和未开始的步骤。就绪后点击麦克风,允许访问,再点击停止以转写。取消或 Escape 丢弃录音。识别反馈留在工具栏内部。Provider 和语言偏好在 Bundle 详情中通过 Settings 服务保存。浏览器麦克风访问需要 HTTPS 或环回地址,以及操作系统权限。 +在 Bundle 详情的**输入设备**中选择系统默认或浏览器可用的麦克风。菜单展开时,选中设备旁显示实时输入电平;切换设备后菜单保持展开,便于比较。关闭菜单、隐藏页面或禁用插件会释放预览,包括随后才批准的麦克风授权。浏览器会记住设备选择并用于后续录音,与 Host 的识别设置分别保存。设备缺失或权限被拒绝时,菜单仍可用于重新选择;录音不会静默改用其他设备。 + 下载或重试前,**模型下载源**提供自动选择及 Host 公布的源。SenseVoice 默认提供 Hugging Face 和 HF-Mirror;固定私有部署仅显示配置的源。手动选择只使用指定源,自动选择沿用提供方的比较与回退策略。当前卡片中的重试会保留选择,不修改部署配置或识别偏好。准备期间不能改源,资源就绪后隐藏源选择器。 ----- diff --git a/packages/experimental/client-ui-voice-input/src/client/MicrophonePicker.tsx b/packages/experimental/client-ui-voice-input/src/client/MicrophonePicker.tsx new file mode 100644 index 0000000000..57c2eb55c7 --- /dev/null +++ b/packages/experimental/client-ui-voice-input/src/client/MicrophonePicker.tsx @@ -0,0 +1,93 @@ +/** Device selection owns microphone previews only while its portaled menu is open. */ +import { useEffect, useRef, useState } from 'react' +import { IconCheckOutlineRegular, IconChevronDownOutlineRegular, Menu, StateDot, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { VoiceInputInjected } from './VoiceInput.tsx' +import { RecordingError, type Recording } from './audio.ts' +import type { MicrophoneDevice } from './microphone-device.ts' +import { NS } from './locales.ts' +import css from './VoiceInput.module.css' + +function InputLevel({ recording, label }: { recording: Recording; label: string }) { + const meter = useRef(null) + useEffect(() => { + const bars = Array.from((meter.current as HTMLSpanElement).children) + let frame: number + const draw = (): void => { + const decibels = 20 * Math.log10(Math.max(recording.amplitude(), 0.00001)) + const count = Math.ceil(Math.max(0, Math.min(1, (decibels + 60) / 60)) * bars.length) + for (const [index, bar] of bars.entries()) bar.setAttribute('data-active', String(index < count)) + frame = requestAnimationFrame(draw) + } + draw() + return () => { cancelAnimationFrame(frame) } + }, [recording]) + return + {Array.from({ length: 8 }, (_, index) => )} + +} + +/** Render the selected input and preview its measured level without recording audio. */ +export function MicrophonePicker({ useMicrophoneDevice, selectMicrophone, createRecording, t }: + Pick, 'useMicrophoneDevice' | 'selectMicrophone' | 'createRecording'> & PropsLocale) { + const selected = useMicrophoneDevice(value => value) + const [open, setOpen] = useState(false), [devices, setDevices] = useState([]) + const [preview, setPreview] = useState(), [error, setError] = useState(''), [revision, setRevision] = useState(0) + useEffect(() => { + if (!open) return + const capture = createRecording(), media = (navigator as Partial).mediaDevices + const lifetime = new AbortController() + const release = (): void => { void capture.dispose().catch(() => undefined) } + setPreview(undefined); setError('') + const fail = (failure: unknown): void => { + if (lifetime.signal.aborted) return + release(); setPreview(undefined) + setError(failure instanceof RecordingError ? t(failure.kind) : t('failed', { + message: failure instanceof Error ? failure.message : String(failure), + })) + } + const refresh = async (): Promise => { + if (!media) throw new RecordingError('unavailable') + const inputs = (await media.enumerateDevices()).filter(device => device.kind === 'audioinput' && device.deviceId !== '' && device.deviceId !== 'default') + if (!lifetime.signal.aborted) setDevices(inputs.map((device, index) => ({ id: device.deviceId, + label: device.label || t('unnamedMicrophone', { number: String(index + 1) }) }))) + } + void (async () => { + try { + await capture.preview(fail) + if (!lifetime.signal.aborted) setPreview(capture) + } catch (failure) { fail(failure) } + if (lifetime.signal.aborted) return + try { await refresh() } catch (failure) { fail(failure) } + })() + const changed = (): void => { setRevision(value => value + 1) } + const hidden = (): void => { if (document.hidden) setOpen(false) } + media?.addEventListener('devicechange', changed, { signal: lifetime.signal }) + document.addEventListener('visibilitychange', hidden, { signal: lifetime.signal }) + return () => { + lifetime.abort() + release() + } + }, [open, selected.id, revision, createRecording, t]) + const choices = [{ id: '', label: t('systemMicrophone') }, ...devices] + const title = selected.id === '' ? t('systemMicrophone') : selected.label + return
+ {t('inputDevice')} + { setOpen(false) }} portal autoFocus dense selection="fill" + className={css.deviceAnchor} listClassName={css.deviceMenu} selectedId={selected.id} + items={choices.map(device => ({ id: device.id, + icon: {device.id === selected.id && }, + label: + {device.label} + {device.id === selected.id && (preview ? + : !error && )} + , + }))} + onSelect={(id) => { selectMicrophone(choices.find(item => item.id === id) as MicrophoneDevice) }} + footer={error ? [{ id: 'error', type: 'label', text: error }] : []} + anchor={} /> +
+} diff --git a/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx b/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx index 8d9fcaff5e..bdff8e4b85 100644 --- a/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx +++ b/packages/experimental/client-ui-voice-input/src/client/PreparationCard.tsx @@ -4,6 +4,7 @@ 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 { MicrophonePicker } from './MicrophonePicker.tsx' import { NS } from './locales.ts' import css from './VoiceInput.module.css' @@ -129,7 +130,7 @@ export function PreparationCard({ provider, connected, prepare, cancelPreparatio /** Recognition preferences and preparation cards shared by plugin details and Settings. */ export function VoicePreparation({ useSpeechReadiness, ...props }: Pick, - 'useSpeechReadiness' | 'configure' | 'prepare' | 'cancelPreparation'> & PropsLocale) { + 'useSpeechReadiness' | 'configure' | 'prepare' | 'cancelPreparation' | 'createRecording' | 'useMicrophoneDevice' | 'selectMicrophone'> & PropsLocale) { const readiness = useSpeechReadiness(value => value), catalog = readiness.catalog const [saving, setSaving] = useState(false), [error, setError] = useState('') const configure = async (patch: SpeechSelectionPatch): Promise => { @@ -143,6 +144,7 @@ export function VoicePreparation({ useSpeechReadiness, ...props }: Pick {catalog &&
+