🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(chat): add realtime voice dictation (#18132)
Tsuki6e4497b32f72
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 3c32b4c1ae5..6f0941e9451 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1770,6 +1770,39 @@"viewSwitcher.chat": "Chat","viewSwitcher.page": "Page","viewSwitcher.task": "Task",+ "voiceDictation.action": "Dictate with microphone",+ "voiceDictation.cancel": "Cancel dictation",+ "voiceDictation.connecting": "Connecting…",+ "voiceDictation.dismiss": "Dismiss dictation error",+ "voiceDictation.error.AUDIO_CAPTURE_FAILED": "Microphone capture failed. Check the selected input device and retry.",+ "voiceDictation.error.AUDIO_FORMAT_INVALID": "The captured audio format was rejected.",+ "voiceDictation.error.AUTH_FAILED": "The dictation session could not be authorized.",+ "voiceDictation.error.BACKPRESSURE": "The connection could not keep up with live audio. Retry on a stable network.",+ "voiceDictation.error.FINAL_TIMEOUT": "Dictation took too long to finish. Confirmed text has been kept.",+ "voiceDictation.error.INTERNAL_ERROR": "Dictation stopped because of an internal error.",+ "voiceDictation.error.MICROPHONE_NOT_SUPPORTED": "Realtime dictation is not supported in this browser. Try the latest Chrome or Safari.",+ "voiceDictation.error.MICROPHONE_PERMISSION_DENIED": "Microphone access is blocked. Allow it in browser site settings, then retry.",+ "voiceDictation.error.NETWORK_DISCONNECTED": "The dictation connection was interrupted. Confirmed text has been kept.",+ "voiceDictation.error.PROTOCOL_ERROR": "The dictation service returned an invalid response.",+ "voiceDictation.error.PROVIDER_BILLING_BLOCKED": "Realtime dictation is unavailable for this account.",+ "voiceDictation.error.PROVIDER_CAPACITY": "Realtime dictation is busy. Try again shortly.",+ "voiceDictation.error.PROVIDER_DISCONNECTED": "The transcription service disconnected. Confirmed text has been kept.",+ "voiceDictation.error.PROVIDER_NOT_CONFIGURED": "Realtime dictation is not configured.",+ "voiceDictation.error.PROVIDER_REGION_UNAVAILABLE": "Realtime dictation is unavailable in the current region.",+ "voiceDictation.error.PROVIDER_TIMEOUT": "The transcription service timed out.",+ "voiceDictation.error.PROVIDER_UNAVAILABLE": "Realtime dictation is temporarily unavailable.",+ "voiceDictation.error.SESSION_CREATE_FAILED": "A dictation session could not be created.",+ "voiceDictation.error.SESSION_EXPIRED": "The dictation session expired. Start a new session.",+ "voiceDictation.error.SESSION_LIMIT_EXCEEDED": "The dictation session limit was reached.",+ "voiceDictation.error.WORKER_RESTART": "The dictation service restarted. Try again.",+ "voiceDictation.finalizing": "Finishing dictation…",+ "voiceDictation.listening": "Listening…",+ "voiceDictation.otherAudioModeActive": "Finish the voice message recording first.",+ "voiceDictation.replyInProgress": "Wait for the current response to finish before dictating.",+ "voiceDictation.requestingPermission": "Requesting microphone access…",+ "voiceDictation.retry": "Retry dictation",+ "voiceDictation.statusLabel": "Realtime dictation",+ "voiceDictation.stop": "Finish dictation","voiceMessage.action": "Send voice message","voiceMessage.cancel": "Cancel recording","voiceMessage.cancelUpload": "Cancel voice message upload",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex f2324dc5029..0726442d93f 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1770,6 +1770,39 @@"viewSwitcher.chat": "对话","viewSwitcher.page": "文稿","viewSwitcher.task": "任务",+ "voiceDictation.action": "使用麦克风听写",+ "voiceDictation.cancel": "取消听写",+ "voiceDictation.connecting": "正在连接…",+ "voiceDictation.dismiss": "关闭听写错误",+ "voiceDictation.error.AUDIO_CAPTURE_FAILED": "麦克风采集失败,请检查输入设备后重试",+ "voiceDictation.error.AUDIO_FORMAT_INVALID": "采集的音频格式未被服务接受",+ "voiceDictation.error.AUTH_FAILED": "听写会话授权失败",+ "voiceDictation.error.BACKPRESSURE": "当前连接无法及时发送实时音频,请在网络稳定后重试",+ "voiceDictation.error.FINAL_TIMEOUT": "听写结束超时,已保留确认的文字",+ "voiceDictation.error.INTERNAL_ERROR": "听写因内部错误而停止",+ "voiceDictation.error.MICROPHONE_NOT_SUPPORTED": "当前浏览器不支持实时听写,请使用最新版 Chrome 或 Safari",+ "voiceDictation.error.MICROPHONE_PERMISSION_DENIED": "麦克风权限已被阻止,请在浏览器网站设置中允许后重试",+ "voiceDictation.error.NETWORK_DISCONNECTED": "听写连接已中断,已保留确认的文字",+ "voiceDictation.error.PROTOCOL_ERROR": "听写服务返回了无效响应",+ "voiceDictation.error.PROVIDER_BILLING_BLOCKED": "当前账号暂时无法使用实时听写",+ "voiceDictation.error.PROVIDER_CAPACITY": "实时听写服务繁忙,请稍后重试",+ "voiceDictation.error.PROVIDER_DISCONNECTED": "转写服务连接已中断,已保留确认的文字",+ "voiceDictation.error.PROVIDER_NOT_CONFIGURED": "实时听写尚未配置",+ "voiceDictation.error.PROVIDER_REGION_UNAVAILABLE": "实时听写在当前区域不可用",+ "voiceDictation.error.PROVIDER_TIMEOUT": "转写服务响应超时",+ "voiceDictation.error.PROVIDER_UNAVAILABLE": "实时听写暂时不可用",+ "voiceDictation.error.SESSION_CREATE_FAILED": "无法创建听写会话",+ "voiceDictation.error.SESSION_EXPIRED": "听写会话已过期,请重新开始",+ "voiceDictation.error.SESSION_LIMIT_EXCEEDED": "已达到听写会话限制",+ "voiceDictation.error.WORKER_RESTART": "听写服务已重启,请重试",+ "voiceDictation.finalizing": "正在完成听写…",+ "voiceDictation.listening": "正在聆听…",+ "voiceDictation.otherAudioModeActive": "请先结束语音消息录音",+ "voiceDictation.replyInProgress": "请等待当前回复完成后再开始听写",+ "voiceDictation.requestingPermission": "正在请求麦克风权限…",+ "voiceDictation.retry": "重试听写",+ "voiceDictation.statusLabel": "实时听写",+ "voiceDictation.stop": "完成听写","voiceMessage.action": "发送语音消息","voiceMessage.cancel": "取消录音","voiceMessage.cancelUpload": "取消发送语音消息",diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex cff2a4d12d5..84ebbc6a8c1 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -129,6 +129,12 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mappedState.enableStorageOverage).toBe(true);});+ it('should keep realtime voice dictation disabled by default', () => {+ const mappedState = mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS);++ expect(mappedState.enableVoiceDictation).toBe(false);+ });+it('should keep onboarding v2 off by default outside development', () => {const mappedState = mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS);@@ -181,6 +187,7 @@ describe('mapFeatureFlagsEnvToState', () => {auth_captcha: true,market: true,speech_to_text: true,+ voice_dictation: true,changelog: false,api_key_manage: false,cloud_promotion: true,@@ -209,6 +216,7 @@ describe('mapFeatureFlagsEnvToState', () => {enableStorageOverage: false,showMarket: true,enableSTT: true,+ enableVoiceDictation: true,showCloudPromotion: true,hideGitHub: false,hideDocs: true,diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 3405b832670..d34fe082c79 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -20,6 +20,7 @@ export const FeatureFlagsSchema = z.object({ai_image: FeatureFlagValue.optional(),speech_to_text: FeatureFlagValue.optional(),+ voice_dictation: FeatureFlagValue.optional(),token_counter: FeatureFlagValue.optional(),welcome_suggest: FeatureFlagValue.optional(),@@ -97,6 +98,7 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {market: true,speech_to_text: true,+ voice_dictation: false,changelog: true,// the flags below can only be used with commercial license@@ -142,6 +144,7 @@ export const mapFeatureFlagsEnvToState = (showMarket: evaluateFeatureFlag(config.market, userId),enableSTT: evaluateFeatureFlag(config.speech_to_text, userId),+ enableVoiceDictation: evaluateFeatureFlag(config.voice_dictation, userId),hideGitHub: evaluateFeatureFlag(config.commercial_hide_github, userId),hideDocs: evaluateFeatureFlag(config.commercial_hide_docs, userId),diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 429558f13c6..f745c79b8a6 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1991,6 +1991,48 @@ export default {'Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.','upload.validation.videoSizeExceeded':'Video file size must not exceed {{maxSize}}. Current file size is {{actualSize}}.',+ 'voiceDictation.action': 'Dictate with microphone',+ 'voiceDictation.cancel': 'Cancel dictation',+ 'voiceDictation.connecting': 'Connecting…',+ 'voiceDictation.dismiss': 'Dismiss dictation error',+ 'voiceDictation.error.AUDIO_CAPTURE_FAILED':+ 'Microphone capture failed. Check the selected input device and retry.',+ 'voiceDictation.error.AUDIO_FORMAT_INVALID': 'The captured audio format was rejected.',+ 'voiceDictation.error.AUTH_FAILED': 'The dictation session could not be authorized.',+ 'voiceDictation.error.BACKPRESSURE':+ 'The connection could not keep up with live audio. Retry on a stable network.',+ 'voiceDictation.error.FINAL_TIMEOUT':+ 'Dictation took too long to finish. Confirmed text has been kept.',+ 'voiceDictation.error.INTERNAL_ERROR': 'Dictation stopped because of an internal error.',+ 'voiceDictation.error.MICROPHONE_NOT_SUPPORTED':+ 'Realtime dictation is not supported in this browser. Try the latest Chrome or Safari.',+ 'voiceDictation.error.MICROPHONE_PERMISSION_DENIED':+ 'Microphone access is blocked. Allow it in browser site settings, then retry.',+ 'voiceDictation.error.NETWORK_DISCONNECTED':+ 'The dictation connection was interrupted. Confirmed text has been kept.',+ 'voiceDictation.error.PROTOCOL_ERROR': 'The dictation service returned an invalid response.',+ 'voiceDictation.error.PROVIDER_BILLING_BLOCKED':+ 'Realtime dictation is unavailable for this account.',+ 'voiceDictation.error.PROVIDER_CAPACITY': 'Realtime dictation is busy. Try again shortly.',+ 'voiceDictation.error.PROVIDER_DISCONNECTED':+ 'The transcription service disconnected. Confirmed text has been kept.',+ 'voiceDictation.error.PROVIDER_NOT_CONFIGURED': 'Realtime dictation is not configured.',+ 'voiceDictation.error.PROVIDER_REGION_UNAVAILABLE':+ 'Realtime dictation is unavailable in the current region.',+ 'voiceDictation.error.PROVIDER_TIMEOUT': 'The transcription service timed out.',+ 'voiceDictation.error.PROVIDER_UNAVAILABLE': 'Realtime dictation is temporarily unavailable.',+ 'voiceDictation.error.SESSION_CREATE_FAILED': 'A dictation session could not be created.',+ 'voiceDictation.error.SESSION_EXPIRED': 'The dictation session expired. Start a new session.',+ 'voiceDictation.error.SESSION_LIMIT_EXCEEDED': 'The dictation session limit was reached.',+ 'voiceDictation.error.WORKER_RESTART': 'The dictation service restarted. Try again.',+ 'voiceDictation.finalizing': 'Finishing dictation…',+ 'voiceDictation.listening': 'Listening…',+ 'voiceDictation.otherAudioModeActive': 'Finish the voice message recording first.',+ 'voiceDictation.replyInProgress': 'Wait for the current response to finish before dictating.',+ 'voiceDictation.requestingPermission': 'Requesting microphone access…',+ 'voiceDictation.retry': 'Retry dictation',+ 'voiceDictation.statusLabel': 'Realtime dictation',+ 'voiceDictation.stop': 'Finish dictation','voiceMessage.action': 'Send voice message','voiceMessage.cancel': 'Cancel recording','voiceMessage.cancelUpload': 'Cancel voice message upload',diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 2db5ddfa5aa..07ae8ab9cc0 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -28,6 +28,7 @@ export type IFeatureFlagsState = {enableRAGEval: boolean | undefined;enableSTT: boolean | undefined;enableStorageOverage: boolean | undefined;+ enableVoiceDictation: boolean | undefined;enableWorkspace: boolean | undefined;hideDocs: boolean | undefined;hideGitHub: boolean | undefined;diff --git a/src/features/ChatInput/ActionBar/config.ts b/src/features/ChatInput/ActionBar/config.tsindex a1153858ff2..c63b08d6b48 100644--- a/src/features/ChatInput/ActionBar/config.ts+++ b/src/features/ChatInput/ActionBar/config.ts@@ -1,3 +1,4 @@+import VoiceDictation from '../Dictation';import VoiceMessage from '../VoiceMessage';import AgentMode from './AgentMode';import Clear from './Clear';@@ -34,6 +35,7 @@ export const actionMap = {temperature: Params,tools: Tools,typo: Typo,+ voiceDictation: VoiceDictation,voiceMessage: VoiceMessage,} as const;diff --git a/src/features/ChatInput/Dictation/audio.test.ts b/src/features/ChatInput/Dictation/audio.test.tsnew file mode 100644index 00000000000..da189eeea30--- /dev/null+++ b/src/features/ChatInput/Dictation/audio.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';++import { PcmFrameProcessor } from './audio';++describe('PcmFrameProcessor', () => {+ it('downmixes stereo, resamples 48 kHz to 16 kHz, and emits 6400-byte LE frames', () => {+ const processor = new PcmFrameProcessor(48_000);+ const left = new Float32Array(9600).fill(1);+ const right = new Float32Array(9600).fill(0);++ const frames = [...processor.process([left, right]), ...processor.flush()];++ expect(frames).toHaveLength(1);+ expect(frames[0].byteLength).toBe(6400);+ const view = new DataView(frames[0]);+ expect(view.getInt16(0, true)).toBe(16_384);+ expect(view.getInt16(2, true)).toBe(16_384);+ });++ it('aggregates chunks into one 200 ms frame', () => {+ const processor = new PcmFrameProcessor(16_000);++ expect(processor.process([new Float32Array(1000).fill(0.25)])).toEqual([]);+ expect(processor.process([new Float32Array(2200).fill(0.25)])).toEqual([]);++ const frames = processor.flush();+ expect(frames).toHaveLength(1);+ expect(frames[0].byteLength).toBe(6400);+ });++ it('pads the final short frame with silence and clamps PCM16 values', () => {+ const processor = new PcmFrameProcessor(16_000);+ processor.process([Float32Array.from([2, -2])]);++ const [frame] = processor.flush();+ const view = new DataView(frame);+ expect(view.getInt16(0, true)).toBe(32_767);+ expect(view.getInt16(2, true)).toBe(-32_768);+ expect(view.getInt16(4, true)).toBe(0);+ expect(frame.byteLength).toBe(6400);+ });+});diff --git a/src/features/ChatInput/Dictation/audio.ts b/src/features/ChatInput/Dictation/audio.tsnew file mode 100644index 00000000000..f61d77a3db0--- /dev/null+++ b/src/features/ChatInput/Dictation/audio.ts@@ -0,0 +1,254 @@+import { REALTIME_ASR_AUDIO } from './contract';++const WORKLET_NAME = 'lobe-realtime-asr-pcm';++export class PcmFrameProcessor {+ inputBuffer: number[] = [];+ outputBuffer: number[] = [];+ sourcePosition = 0;++ constructor(+ readonly inputSampleRate: number,+ readonly outputSampleRate = 16_000,+ readonly frameSamples = 3200,+ ) {+ if (!Number.isFinite(inputSampleRate) || inputSampleRate <= 0) {+ throw new Error('invalid_input_sample_rate');+ }+ }++ process(channels: readonly Float32Array[]): ArrayBuffer[] {+ if (channels.length === 0 || channels[0].length === 0) return [];++ const sampleCount = channels[0].length;+ for (let index = 0; index < sampleCount; index += 1) {+ let mixed = 0;+ let channelCount = 0;+ for (const channel of channels) {+ if (index >= channel.length) continue;+ mixed += channel[index];+ channelCount += 1;+ }+ this.inputBuffer.push(channelCount > 0 ? mixed / channelCount : 0);+ }++ this.resample(false);+ return this.takeFrames(false);+ }++ flush(): ArrayBuffer[] {+ this.resample(true);+ this.inputBuffer = [];+ this.sourcePosition = 0;+ return this.takeFrames(true);+ }++ resample(flush: boolean) {+ const ratio = this.inputSampleRate / this.outputSampleRate;+ const limit = flush ? this.inputBuffer.length : Math.max(0, this.inputBuffer.length - 1);++ while (this.sourcePosition < limit) {+ const leftIndex = Math.floor(this.sourcePosition);+ const rightIndex = Math.min(leftIndex + 1, this.inputBuffer.length - 1);+ const fraction = this.sourcePosition - leftIndex;+ const left = this.inputBuffer[leftIndex] ?? 0;+ const right = this.inputBuffer[rightIndex] ?? left;+ this.outputBuffer.push(left + (right - left) * fraction);+ this.sourcePosition += ratio;+ }++ if (!flush) {+ const consumed = Math.min(Math.floor(this.sourcePosition), this.inputBuffer.length - 1);+ if (consumed > 0) {+ this.inputBuffer = this.inputBuffer.slice(consumed);+ this.sourcePosition -= consumed;+ }+ }+ }++ takeFrames(padFinalFrame: boolean): ArrayBuffer[] {+ const frames: ArrayBuffer[] = [];+ while (this.outputBuffer.length >= this.frameSamples) {+ frames.push(this.toPcm16(this.outputBuffer.splice(0, this.frameSamples)));+ }++ if (padFinalFrame && this.outputBuffer.length > 0) {+ const finalSamples = this.outputBuffer.splice(0);+ while (finalSamples.length < this.frameSamples) finalSamples.push(0);+ frames.push(this.toPcm16(finalSamples));+ }++ return frames;+ }++ toPcm16(samples: number[]): ArrayBuffer {+ const buffer = new ArrayBuffer(samples.length * 2);+ const view = new DataView(buffer);+ for (let index = 0; index < samples.length; index += 1) {+ const sample = Math.max(-1, Math.min(1, samples[index]));+ const pcm = sample < 0 ? Math.round(sample * 0x8000) : Math.round(sample * 0x7fff);+ view.setInt16(index * 2, pcm, true);+ }+ return buffer;+ }+}++const createWorkletSource = () => `+const PcmFrameProcessor = ${PcmFrameProcessor.toString()};+class RealtimeAsrAudioProcessor extends AudioWorkletProcessor {+ constructor() {+ super();+ this.core = new PcmFrameProcessor(sampleRate, ${REALTIME_ASR_AUDIO.sampleRate}, ${REALTIME_ASR_AUDIO.frameBytes / 2});+ this.port.onmessage = (event) => {+ if (event.data?.type !== 'flush') return;+ for (const frame of this.core.flush()) {+ this.port.postMessage({ frame, type: 'frame' }, [frame]);+ }+ this.port.postMessage({ type: 'flushed' });+ };+ }+ process(inputs) {+ for (const frame of this.core.process(inputs[0] || [])) {+ this.port.postMessage({ frame, type: 'frame' }, [frame]);+ }+ return true;+ }+}+registerProcessor('${WORKLET_NAME}', RealtimeAsrAudioProcessor);+`;++interface WebkitWindow extends Window {+ webkitAudioContext?: typeof AudioContext;+}++export interface RealtimeAudioCapture {+ cancel: () => Promise<void>;+ start: (onFrame: (frame: ArrayBuffer) => void, onError: () => void) => Promise<void>;+ stop: () => Promise<void>;+}++const stopStream = (stream: MediaStream) => {+ for (const track of stream.getTracks()) track.stop();+};++export const requestDictationMicrophone = async (): Promise<MediaStream> => {+ if (typeof navigator === 'undefined' || !navigator.mediaDevices?.getUserMedia) {+ throw new Error('microphone_not_supported');+ }++ return navigator.mediaDevices.getUserMedia({+ audio: {+ channelCount: { ideal: 1 },+ echoCancellation: true,+ noiseSuppression: true,+ },+ });+};++export class BrowserAudioWorkletCapture implements RealtimeAudioCapture {+ readonly #context: AudioContext;+ readonly #gain: GainNode;+ readonly #node: AudioWorkletNode;+ readonly #source: MediaStreamAudioSourceNode;+ readonly #stream: MediaStream;+ #connected = false;+ #disposed = false;+ #flushResolve?: () => void;++ private constructor(options: {+ context: AudioContext;+ gain: GainNode;+ node: AudioWorkletNode;+ source: MediaStreamAudioSourceNode;+ stream: MediaStream;+ }) {+ this.#context = options.context;+ this.#gain = options.gain;+ this.#node = options.node;+ this.#source = options.source;+ this.#stream = options.stream;+ }++ static async create(stream: MediaStream): Promise<BrowserAudioWorkletCapture> {+ const AudioContextConstructor =+ window.AudioContext || (window as WebkitWindow).webkitAudioContext;+ if (!AudioContextConstructor || typeof AudioWorkletNode === 'undefined') {+ stopStream(stream);+ throw new Error('audio_worklet_not_supported');+ }++ const context = new AudioContextConstructor();+ const sourceUrl = URL.createObjectURL(+ new Blob([createWorkletSource()], { type: 'text/javascript' }),+ );+ try {+ await context.audioWorklet.addModule(sourceUrl);+ const node = new AudioWorkletNode(context, WORKLET_NAME, {+ numberOfInputs: 1,+ numberOfOutputs: 1,+ outputChannelCount: [1],+ });+ const source = context.createMediaStreamSource(stream);+ const gain = context.createGain();+ gain.gain.value = 0;+ return new BrowserAudioWorkletCapture({ context, gain, node, source, stream });+ } catch (error) {+ stopStream(stream);+ await context.close().catch(() => undefined);+ throw error;+ } finally {+ URL.revokeObjectURL(sourceUrl);+ }+ }++ async start(onFrame: (frame: ArrayBuffer) => void, onError: () => void) {+ if (this.#disposed) throw new Error('audio_capture_disposed');++ this.#node.port.onmessage = (event: MessageEvent) => {+ if (event.data?.type === 'frame' && event.data.frame instanceof ArrayBuffer) {+ onFrame(event.data.frame);+ } else if (event.data?.type === 'flushed') {+ this.#flushResolve?.();+ this.#flushResolve = undefined;+ }+ };+ this.#node.addEventListener('processorerror', onError, { once: true });+ this.#source.connect(this.#node);+ this.#node.connect(this.#gain);+ this.#gain.connect(this.#context.destination);+ this.#connected = true;+ if (this.#context.state === 'suspended') await this.#context.resume();+ }++ async stop() {+ if (this.#disposed) return;+ if (this.#connected) {+ this.#source.disconnect();+ this.#connected = false;+ }++ await new Promise<void>((resolve) => {+ const timeout = setTimeout(() => {+ this.#flushResolve = undefined;+ resolve();+ }, 1000);+ this.#flushResolve = () => {+ clearTimeout(timeout);+ resolve();+ };+ this.#node.port.postMessage({ type: 'flush' });+ });+ await this.cancel();+ }++ async cancel() {+ if (this.#disposed) return;+ this.#disposed = true;+ if (this.#connected) this.#source.disconnect();+ this.#connected = false;+ this.#node.disconnect();+ this.#gain.disconnect();+ stopStream(this.#stream);+ if (this.#context.state !== 'closed') await this.#context.close().catch(() => undefined);+ }+}diff --git a/src/features/ChatInput/Dictation/client.test.ts b/src/features/ChatInput/Dictation/client.test.tsnew file mode 100644index 00000000000..5c819b7168a--- /dev/null+++ b/src/features/ChatInput/Dictation/client.test.ts@@ -0,0 +1,418 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { RealtimeAudioCapture } from './audio';+import { type RealtimeAsrWebSocket, RealtimeDictationClient } from './client';+import {+ REALTIME_ASR_AUDIO,+ REALTIME_ASR_LIMITS,+ type RealtimeAsrServerEvent,+ type RealtimeAsrSessionResponse,+ RealtimeDictationError,+} from './contract';+import type { DictationEditorAdapter } from './editor';++class FakeSocket {+ binaryType: BinaryType = 'blob';+ bufferedAmount = 0;+ readyState = 0;+ sent: Array<ArrayBuffer | string> = [];+ readonly listeners = new Map<string, Set<(event?: MessageEvent) => void>>();++ addEventListener(type: string, listener: (event?: MessageEvent) => void) {+ const listeners = this.listeners.get(type) ?? new Set();+ listeners.add(listener);+ this.listeners.set(type, listeners);+ }++ removeEventListener(type: string, listener: (event?: MessageEvent) => void) {+ this.listeners.get(type)?.delete(listener);+ }++ send(data: ArrayBuffer | string) {+ this.sent.push(data);+ }++ close() {+ this.readyState = 3;+ }++ open() {+ this.readyState = 1;+ this.emit('open');+ }++ serverEvent(event: RealtimeAsrServerEvent) {+ this.emit('message', { data: JSON.stringify(event) } as MessageEvent);+ }++ disconnect() {+ this.readyState = 3;+ this.emit('close');+ }++ private emit(type: string, event?: MessageEvent) {+ for (const listener of this.listeners.get(type) ?? []) listener(event);+ }+}++const session = (): RealtimeAsrSessionResponse => ({+ audio: REALTIME_ASR_AUDIO,+ expiresAt: new Date(Date.now() + 30_000).toISOString(),+ limits: REALTIME_ASR_LIMITS,+ protocolVersion: 1,+ sessionId: 'session-1',+ token: 'a'.repeat(43),+ websocketUrl: 'wss://asr.example.test/v1/session',+});++const ready = (sequence = 1): RealtimeAsrServerEvent => ({+ audio: REALTIME_ASR_AUDIO,+ limits: REALTIME_ASR_LIMITS,+ protocolVersion: 1,+ sequence,+ sessionId: 'session-1',+ type: 'session.ready',+});++const createFixture = () => {+ const socket = new FakeSocket();+ let onFrame: ((frame: ArrayBuffer) => void) | undefined;+ const capture: RealtimeAudioCapture = {+ cancel: vi.fn().mockResolvedValue(undefined),+ start: vi.fn(async (frameHandler: (frame: ArrayBuffer) => void) => {+ onFrame = frameHandler;+ }),+ stop: vi.fn().mockResolvedValue(undefined),+ };+ let onUserEdit: (() => void) | undefined;+ const editor: DictationEditorAdapter = {+ begin: vi.fn((callback) => {+ onUserEdit = callback;+ return { anchor: 6, prefix: 'draft ', suffix: ' tail' };+ }),+ dispose: vi.fn(),+ finalize: vi.fn(),+ render: vi.fn(),+ };+ const track = { stop: vi.fn() };+ const stream = { getTracks: () => [track] } as unknown as MediaStream;+ const client = new RealtimeDictationClient({+ createCapture: vi.fn().mockResolvedValue(capture),+ createSession: vi.fn().mockResolvedValue(session()),+ createWebSocket: vi.fn(() => socket as unknown as RealtimeAsrWebSocket),+ editor,+ requestMicrophone: vi.fn().mockResolvedValue(stream),+ });++ const start = async () => {+ await client.start();+ expect(client.getSnapshot().status).toBe('connecting');+ socket.open();+ socket.serverEvent(ready());+ await vi.waitFor(() => expect(client.getSnapshot().status).toBe('listening'));+ };++ return {+ capture,+ client,+ editor,+ emitFrame: (frame: ArrayBuffer) => onFrame?.(frame),+ onUserEdit: () => onUserEdit?.(),+ socket,+ start,+ track,+ };+};++describe('RealtimeDictationClient', () => {+ afterEach(() => vi.useRealTimers());++ it('starts audio initialization and session admission together after permission', async () => {+ let resolveCapture!: (capture: RealtimeAudioCapture) => void;+ let resolveSession!: (session: RealtimeAsrSessionResponse) => void;+ const capture: RealtimeAudioCapture = {+ cancel: vi.fn().mockResolvedValue(undefined),+ start: vi.fn().mockResolvedValue(undefined),+ stop: vi.fn().mockResolvedValue(undefined),+ };+ const capturePromise = new Promise<RealtimeAudioCapture>((resolve) => {+ resolveCapture = resolve;+ });+ const sessionPromise = new Promise<RealtimeAsrSessionResponse>((resolve) => {+ resolveSession = resolve;+ });+ const createCapture = vi.fn(() => capturePromise);+ const createSession = vi.fn(() => sessionPromise);+ const createWebSocket = vi.fn(() => new FakeSocket() as unknown as RealtimeAsrWebSocket);+ const client = new RealtimeDictationClient({+ createCapture,+ createSession,+ createWebSocket,+ editor: {+ begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),+ dispose: vi.fn(),+ finalize: vi.fn(),+ render: vi.fn(),+ },+ requestMicrophone: vi+ .fn()+ .mockResolvedValue({ getTracks: () => [] } as unknown as MediaStream),+ });++ const startPromise = client.start();+ await vi.waitFor(() => {+ expect(createCapture).toHaveBeenCalledOnce();+ expect(createSession).toHaveBeenCalledOnce();+ });++ resolveCapture(capture);+ resolveSession(session());+ await startPromise;++ expect(createWebSocket).toHaveBeenCalledOnce();+ expect(client.getSnapshot().status).toBe('connecting');+ });++ it('releases a late audio capture when concurrent session admission fails', async () => {+ let resolveCapture!: (capture: RealtimeAudioCapture) => void;+ const capture: RealtimeAudioCapture = {+ cancel: vi.fn().mockResolvedValue(undefined),+ start: vi.fn().mockResolvedValue(undefined),+ stop: vi.fn().mockResolvedValue(undefined),+ };+ const client = new RealtimeDictationClient({+ createCapture: vi.fn(+ () =>+ new Promise<RealtimeAudioCapture>((resolve) => {+ resolveCapture = resolve;+ }),+ ),+ createSession: vi+ .fn()+ .mockRejectedValue(new RealtimeDictationError('SESSION_CREATE_FAILED', true)),+ createWebSocket: vi.fn(() => new FakeSocket() as unknown as RealtimeAsrWebSocket),+ editor: {+ begin: vi.fn(() => ({ anchor: 0, prefix: '', suffix: '' })),+ dispose: vi.fn(),+ finalize: vi.fn(),+ render: vi.fn(),+ },+ requestMicrophone: vi+ .fn()+ .mockResolvedValue({ getTracks: () => [] } as unknown as MediaStream),+ });++ await client.start();+ expect(client.getSnapshot()).toMatchObject({+ errorCode: 'SESSION_CREATE_FAILED',+ status: 'error',+ });++ resolveCapture(capture);+ await vi.waitFor(() => expect(capture.cancel).toHaveBeenCalledOnce());+ });++ it('authenticates, applies partial/final events, and waits for completion on stop', async () => {+ const fixture = createFixture();+ await fixture.start();++ expect(JSON.parse(fixture.socket.sent[0] as string)).toEqual({+ protocolVersion: 1,+ token: 'a'.repeat(43),+ type: 'session.auth',+ });+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'session-1',+ text: 'hel',+ type: 'transcript.partial',+ });+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 3,+ sessionId: 'session-1',+ text: 'hello',+ type: 'transcript.final',+ });+ expect(fixture.editor.render).toHaveBeenNthCalledWith(1, 'hel');+ expect(fixture.editor.render).toHaveBeenNthCalledWith(2, 'hello');++ await fixture.client.stop();+ expect(fixture.client.getSnapshot().status).toBe('finalizing');+ expect(JSON.parse(fixture.socket.sent.at(-1) as string)).toEqual({ type: 'session.end' });+ fixture.socket.serverEvent({+ forwardedAudioMs: 200,+ sequence: 4,+ sessionId: 'session-1',+ type: 'session.completed',+ });+ await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('idle'));+ expect(fixture.editor.finalize).toHaveBeenCalledOnce();+ expect(fixture.editor.finalize).toHaveBeenCalledWith('hello');+ });++ it('keeps final text and drops only partial text on cancel', async () => {+ const fixture = createFixture();+ await fixture.start();+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'session-1',+ text: 'confirmed',+ type: 'transcript.final',+ });+ fixture.socket.serverEvent({+ segmentId: 'segment-2',+ sequence: 3,+ sessionId: 'session-1',+ text: 'temporary',+ type: 'transcript.partial',+ });++ await fixture.client.cancel();++ expect(fixture.editor.finalize).toHaveBeenCalledWith('confirmed');+ expect(JSON.parse(fixture.socket.sent.at(-1) as string)).toEqual({+ reason: 'user_cancelled',+ type: 'session.cancel',+ });+ fixture.socket.serverEvent({+ forwardedAudioMs: 400,+ sequence: 4,+ sessionId: 'session-1',+ type: 'session.cancelled',+ });+ await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('idle'));+ });++ it('ignores old-session, duplicate, and out-of-order transcripts', async () => {+ const fixture = createFixture();+ await fixture.start();+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'old-session',+ text: 'old',+ type: 'transcript.partial',+ });+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 3,+ sessionId: 'session-1',+ text: 'new',+ type: 'transcript.partial',+ });+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 3,+ sessionId: 'session-1',+ text: 'duplicate',+ type: 'transcript.partial',+ });+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'session-1',+ text: 'out-of-order',+ type: 'transcript.final',+ });++ expect(fixture.editor.render).toHaveBeenCalledOnce();+ expect(fixture.editor.render).toHaveBeenCalledWith('new');+ });++ it('ends safely on user edit and preserves confirmed text', async () => {+ const fixture = createFixture();+ await fixture.start();+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'session-1',+ text: 'confirmed',+ type: 'transcript.final',+ });++ fixture.onUserEdit();+ await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('finalizing'));+ await vi.waitFor(() => expect(fixture.socket.sent).toHaveLength(2));++ expect(fixture.editor.finalize).toHaveBeenCalledWith('confirmed');+ expect(JSON.parse(fixture.socket.sent.at(-1) as string)).toEqual({+ reason: 'audio_interruption',+ type: 'session.cancel',+ });+ });++ it('keeps confirmed text and reports a network disconnect', async () => {+ const fixture = createFixture();+ await fixture.start();+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'session-1',+ text: 'confirmed',+ type: 'transcript.final',+ });+ fixture.socket.disconnect();++ await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('error'));+ expect(fixture.client.getSnapshot()).toMatchObject({+ errorCode: 'NETWORK_DISCONNECTED',+ retryable: true,+ });+ expect(fixture.editor.finalize).toHaveBeenCalledWith('confirmed');+ });++ it('surfaces stable gateway error events without keeping partial text', async () => {+ const fixture = createFixture();+ await fixture.start();+ fixture.socket.serverEvent({+ segmentId: 'segment-1',+ sequence: 2,+ sessionId: 'session-1',+ text: 'temporary',+ type: 'transcript.partial',+ });+ fixture.socket.serverEvent({+ code: 'PROVIDER_CAPACITY',+ retryable: true,+ sequence: 3,+ sessionId: 'session-1',+ type: 'session.error',+ });++ await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('error'));+ expect(fixture.client.getSnapshot()).toMatchObject({+ errorCode: 'PROVIDER_CAPACITY',+ retryable: true,+ });+ expect(fixture.editor.finalize).toHaveBeenCalledWith('');+ });++ it('fails deterministically when final completion exceeds the server timeout', async () => {+ vi.useFakeTimers();+ const fixture = createFixture();+ await fixture.start();+ await fixture.client.stop();++ await vi.advanceTimersByTimeAsync(REALTIME_ASR_LIMITS.finalTimeoutMs);++ expect(fixture.client.getSnapshot()).toMatchObject({+ errorCode: 'FINAL_TIMEOUT',+ retryable: true,+ status: 'error',+ });+ });++ it('fails instead of growing the send queue without bound', async () => {+ const fixture = createFixture();+ await fixture.start();+ fixture.socket.bufferedAmount = 64_000;++ for (let index = 0; index < 6; index += 1) fixture.emitFrame(new ArrayBuffer(6400));++ await vi.waitFor(() => expect(fixture.client.getSnapshot().status).toBe('error'));+ expect(fixture.client.getSnapshot().errorCode).toBe('BACKPRESSURE');+ });+});diff --git a/src/features/ChatInput/Dictation/client.ts b/src/features/ChatInput/Dictation/client.tsnew file mode 100644index 00000000000..f3463d576d4--- /dev/null+++ b/src/features/ChatInput/Dictation/client.ts@@ -0,0 +1,372 @@+import type { RealtimeAudioCapture } from './audio';+import {+ parseRealtimeAsrServerEvent,+ REALTIME_ASR_PROTOCOL_VERSION,+ type RealtimeAsrSessionResponse,+ RealtimeDictationError,+ type RealtimeDictationErrorCode,+ type RealtimeDictationSnapshot,+} from './contract';+import { type DictationEditorAdapter } from './editor';+import { BoundedWebSocketFrameQueue } from './frameQueue';+import { DictationTranscript } from './transcript';++export type DictationCancelReason = 'audio_interruption' | 'network_change' | 'user_cancelled';++export interface RealtimeAsrWebSocket {+ addEventListener: ((type: 'close' | 'error' | 'open', listener: () => void) => void) &+ ((type: 'message', listener: (event: MessageEvent) => void) => void);+ binaryType: BinaryType;+ readonly bufferedAmount: number;+ close: (code?: number, reason?: string) => void;+ readonly readyState: number;+ removeEventListener: ((type: 'close' | 'error' | 'open', listener: () => void) => void) &+ ((type: 'message', listener: (event: MessageEvent) => void) => void);+ send: (data: ArrayBuffer | string) => void;+}++export interface RealtimeDictationDependencies {+ createCapture: (stream: MediaStream) => Promise<RealtimeAudioCapture>;+ createSession: (signal: AbortSignal) => Promise<RealtimeAsrSessionResponse>;+ createWebSocket: (url: string) => RealtimeAsrWebSocket;+ editor: DictationEditorAdapter;+ requestMicrophone: () => Promise<MediaStream>;+}++const IDLE_SNAPSHOT: RealtimeDictationSnapshot = {+ retryable: false,+ status: 'idle',+};++const SOCKET_CONNECTING = 0;+const SOCKET_OPEN = 1;++const toClientError = (error: unknown): RealtimeDictationError => {+ if (error instanceof RealtimeDictationError) return error;+ if (error instanceof DOMException && error.name === 'NotAllowedError') {+ return new RealtimeDictationError('MICROPHONE_PERMISSION_DENIED', true);+ }+ if (+ error instanceof Error &&+ (error.message === 'microphone_not_supported' ||+ error.message === 'audio_worklet_not_supported')+ ) {+ return new RealtimeDictationError('MICROPHONE_NOT_SUPPORTED', false);+ }+ if (error instanceof Error && error.message === 'frame_queue_timeout') {+ return new RealtimeDictationError('BACKPRESSURE', true);+ }+ return new RealtimeDictationError('AUDIO_CAPTURE_FAILED', true);+};++export class RealtimeDictationClient {+ readonly #dependencies: RealtimeDictationDependencies;+ readonly #subscribers = new Set<() => void>();+ #acceptingAudio = false;+ #abortController?: AbortController;+ #capture?: RealtimeAudioCapture;+ #closingSocket = false;+ #connectTimer?: ReturnType<typeof setTimeout>;+ #editorFinalized = false;+ #finalTimer?: ReturnType<typeof setTimeout>;+ #lifecycleCleanup?: () => void;+ #queue?: BoundedWebSocketFrameQueue;+ #runId = 0;+ #session?: RealtimeAsrSessionResponse;+ #snapshot = IDLE_SNAPSHOT;+ #socket?: RealtimeAsrWebSocket;+ #terminalTransition = false;+ #transcript?: DictationTranscript;++ constructor(dependencies: RealtimeDictationDependencies) {+ this.#dependencies = dependencies;+ }++ getSnapshot = () => this.#snapshot;++ subscribe = (listener: () => void) => {+ this.#subscribers.add(listener);+ return () => this.#subscribers.delete(listener);+ };++ async start() {+ if (this.#snapshot.status !== 'idle' && this.#snapshot.status !== 'error') return;++ await this.#releaseResources();+ const runId = ++this.#runId;+ this.#editorFinalized = false;+ this.#terminalTransition = false;+ const anchor = this.#dependencies.editor.begin(() => {+ void this.cancel('audio_interruption');+ });+ if (!anchor) {+ this.#setError('AUDIO_CAPTURE_FAILED', true);+ return;+ }++ this.#setSnapshot({ retryable: false, status: 'requesting_permission' });+ const abortController = new AbortController();+ this.#abortController = abortController;++ try {+ const stream = await this.#dependencies.requestMicrophone();+ if (runId !== this.#runId) {+ for (const track of stream.getTracks()) track.stop();+ return;+ }++ this.#setSnapshot({ retryable: false, status: 'connecting' });+ const capturePromise = this.#dependencies.createCapture(stream).then(+ async (capture) => {+ if (runId === this.#runId) {+ this.#capture = capture;+ } else {+ await capture.cancel().catch(() => undefined);+ }+ return capture;+ },+ (error) => {+ abortController.abort();+ throw error;+ },+ );+ const [capture, session] = await Promise.all([+ capturePromise,+ this.#dependencies.createSession(abortController.signal),+ ]);+ if (runId !== this.#runId) {+ await capture.cancel().catch(() => undefined);+ return;+ }++ this.#session = session;+ this.#transcript = new DictationTranscript({ ...anchor, sessionId: session.sessionId });+ this.#socket = this.#dependencies.createWebSocket(session.websocketUrl);+ this.#socket.binaryType = 'arraybuffer';+ this.#socket.addEventListener('open', this.#handleOpen);+ this.#socket.addEventListener('message', this.#handleMessage);+ this.#socket.addEventListener('error', this.#handleSocketError);+ this.#socket.addEventListener('close', this.#handleClose);+ this.#connectTimer = setTimeout(+ () => void this.#fail('PROVIDER_TIMEOUT', true),+ session.limits.authTimeoutMs + session.limits.providerConnectTimeoutMs,+ );+ this.#attachLifecycleListeners();+ } catch (error) {+ if (runId !== this.#runId) return;+ const clientError = toClientError(error);+ await this.#fail(clientError.code, clientError.retryable);+ }+ }++ async stop() {+ if (this.#snapshot.status !== 'listening' || !this.#socket || !this.#session) return;++ this.#setSnapshot({ retryable: false, status: 'finalizing' });+ try {+ await this.#capture?.stop();+ this.#acceptingAudio = false;+ await this.#queue?.waitForEmpty(1000);+ if (this.#socket.readyState !== SOCKET_OPEN) {+ throw new RealtimeDictationError('NETWORK_DISCONNECTED', true);+ }+ this.#socket.send(JSON.stringify({ type: 'session.end' }));+ this.#startFinalTimer();+ } catch (error) {+ const clientError = toClientError(error);+ await this.#fail(clientError.code, clientError.retryable);+ }+ }++ async cancel(reason: DictationCancelReason = 'user_cancelled') {+ if (this.#snapshot.status === 'idle') return;++ this.#finalizeEditor();+ this.#acceptingAudio = false;+ this.#setSnapshot({ retryable: false, status: 'finalizing' });+ await this.#capture?.cancel().catch(() => undefined);+ this.#queue?.dispose();+ if (this.#socket?.readyState === SOCKET_OPEN) {+ this.#socket.send(JSON.stringify({ reason, type: 'session.cancel' }));+ this.#startFinalTimer();+ } else {+ await this.#complete();+ }+ }++ async dispose() {+ ++this.#runId;+ this.#finalizeEditor();+ await this.#releaseResources();+ this.#setSnapshot(IDLE_SNAPSHOT);+ }++ #handleOpen = () => {+ if (!this.#socket || !this.#session) return;+ this.#socket.send(+ JSON.stringify({+ protocolVersion: REALTIME_ASR_PROTOCOL_VERSION,+ token: this.#session.token,+ type: 'session.auth',+ }),+ );+ };++ #handleMessage = (message: MessageEvent) => {+ let event;+ try {+ event = parseRealtimeAsrServerEvent(message.data);+ } catch (error) {+ const clientError = toClientError(error);+ void this.#fail(clientError.code, clientError.retryable);+ return;+ }++ const result = this.#transcript?.accept(event);+ if (!result?.accepted) return;++ switch (event.type) {+ case 'session.ready': {+ if (this.#snapshot.status !== 'connecting' || !this.#socket || !this.#session) return;+ if (this.#connectTimer) clearTimeout(this.#connectTimer);+ this.#connectTimer = undefined;+ this.#queue = new BoundedWebSocketFrameQueue(this.#socket, {+ maxFrames: this.#session.limits.maxBufferedFrames,+ });+ this.#acceptingAudio = true;+ void this.#capture+ ?.start(this.#handleAudioFrame, () => {+ void this.#fail('AUDIO_CAPTURE_FAILED', true);+ })+ .then(() => {+ if (!this.#terminalTransition && this.#snapshot.status === 'connecting') {+ this.#setSnapshot({ retryable: false, status: 'listening' });+ }+ })+ .catch((error) => {+ const clientError = toClientError(error);+ void this.#fail(clientError.code, clientError.retryable);+ });+ break;+ }+ case 'transcript.partial':+ case 'transcript.final': {+ if (result.changed) this.#dependencies.editor.render(this.#transcript!.dictatedText);+ break;+ }+ case 'session.completed':+ case 'session.cancelled': {+ this.#finalizeEditor();+ void this.#complete();+ break;+ }+ case 'session.error': {+ void this.#fail(event.code, event.retryable);+ break;+ }+ }+ };++ #handleAudioFrame = (frame: ArrayBuffer) => {+ if (!this.#acceptingAudio) return;+ if (!this.#queue?.enqueue(frame)) void this.#fail('BACKPRESSURE', true);+ };++ #handleSocketError = () => {+ if (!this.#closingSocket) void this.#fail('NETWORK_DISCONNECTED', true);+ };++ #handleClose = () => {+ if (!this.#closingSocket && this.#snapshot.status !== 'idle') {+ void this.#fail('NETWORK_DISCONNECTED', true);+ }+ };++ #attachLifecycleListeners() {+ if (typeof window === 'undefined' || typeof document === 'undefined') return;++ const handleHidden = () => {+ if (document.visibilityState === 'hidden') void this.cancel('audio_interruption');+ };+ const handleDeviceChange = () => void this.cancel('audio_interruption');+ const handleOffline = () => void this.#fail('NETWORK_DISCONNECTED', true);+ document.addEventListener('visibilitychange', handleHidden);+ window.addEventListener('offline', handleOffline);+ navigator.mediaDevices?.addEventListener?.('devicechange', handleDeviceChange);+ this.#lifecycleCleanup = () => {+ document.removeEventListener('visibilitychange', handleHidden);+ window.removeEventListener('offline', handleOffline);+ navigator.mediaDevices?.removeEventListener?.('devicechange', handleDeviceChange);+ };+ }++ #startFinalTimer() {+ if (this.#finalTimer) clearTimeout(this.#finalTimer);+ const timeoutMs = this.#session?.limits.finalTimeoutMs ?? 5000;+ this.#finalTimer = setTimeout(() => void this.#fail('FINAL_TIMEOUT', true), timeoutMs);+ }++ async #fail(code: RealtimeDictationErrorCode, retryable: boolean) {+ if (this.#terminalTransition) return;+ this.#terminalTransition = true;+ this.#finalizeEditor();+ ++this.#runId;+ await this.#releaseResources();+ this.#setError(code, retryable);+ }++ async #complete() {+ if (this.#terminalTransition) return;+ this.#terminalTransition = true;+ ++this.#runId;+ await this.#releaseResources();+ this.#setSnapshot(IDLE_SNAPSHOT);+ }++ async #releaseResources() {+ this.#acceptingAudio = false;+ this.#abortController?.abort();+ this.#abortController = undefined;+ if (this.#connectTimer) clearTimeout(this.#connectTimer);+ this.#connectTimer = undefined;+ if (this.#finalTimer) clearTimeout(this.#finalTimer);+ this.#finalTimer = undefined;+ this.#lifecycleCleanup?.();+ this.#lifecycleCleanup = undefined;+ this.#queue?.dispose();+ this.#queue = undefined;+ await this.#capture?.cancel().catch(() => undefined);+ this.#capture = undefined;+ if (this.#socket) {+ const socket = this.#socket;+ this.#closingSocket = true;+ socket.removeEventListener('open', this.#handleOpen);+ socket.removeEventListener('message', this.#handleMessage);+ socket.removeEventListener('error', this.#handleSocketError);+ socket.removeEventListener('close', this.#handleClose);+ if (socket.readyState === SOCKET_CONNECTING || socket.readyState === SOCKET_OPEN) {+ socket.close(1000, 'dictation_finished');+ }+ this.#socket = undefined;+ this.#closingSocket = false;+ }+ this.#session = undefined;+ this.#transcript = undefined;+ }++ #setError(code: RealtimeDictationErrorCode, retryable: boolean) {+ this.#setSnapshot({ errorCode: code, retryable, status: 'error' });+ }++ #finalizeEditor() {+ if (this.#editorFinalized) return;+ this.#editorFinalized = true;+ this.#transcript?.discardPartial();+ this.#dependencies.editor.finalize(this.#transcript?.snapshot.committed ?? '');+ }++ #setSnapshot(snapshot: RealtimeDictationSnapshot) {+ this.#snapshot = snapshot;+ for (const subscriber of this.#subscribers) subscriber();+ }+}diff --git a/src/features/ChatInput/Dictation/contract.ts b/src/features/ChatInput/Dictation/contract.tsnew file mode 100644index 00000000000..8511d57279e--- /dev/null+++ b/src/features/ChatInput/Dictation/contract.ts@@ -0,0 +1,237 @@+export const REALTIME_ASR_PROTOCOL_VERSION = 1 as const;++export const REALTIME_ASR_AUDIO = {+ channels: 1,+ encoding: 'pcm_s16le',+ frameBytes: 6400,+ frameDurationMs: 200,+ sampleRate: 16_000,+} as const;++export const REALTIME_ASR_LIMITS = {+ audioIdleTimeoutMs: 5000,+ authTimeoutMs: 5000,+ finalTimeoutMs: 5000,+ maxBufferedFrames: 5,+ maxFrames: 300,+ maxSessionMs: 60_000,+ providerConnectTimeoutMs: 5000,+ tokenTtlMs: 30_000,+} as const;++export type RealtimeAsrErrorCode =+ | 'AUDIO_FORMAT_INVALID'+ | 'AUTH_FAILED'+ | 'BACKPRESSURE'+ | 'INTERNAL_ERROR'+ | 'PROTOCOL_ERROR'+ | 'PROVIDER_BILLING_BLOCKED'+ | 'PROVIDER_CAPACITY'+ | 'PROVIDER_DISCONNECTED'+ | 'PROVIDER_NOT_CONFIGURED'+ | 'PROVIDER_REGION_UNAVAILABLE'+ | 'PROVIDER_TIMEOUT'+ | 'PROVIDER_UNAVAILABLE'+ | 'SESSION_EXPIRED'+ | 'SESSION_LIMIT_EXCEEDED'+ | 'WORKER_RESTART';++export type RealtimeDictationClientErrorCode =+ | 'AUDIO_CAPTURE_FAILED'+ | 'FINAL_TIMEOUT'+ | 'MICROPHONE_NOT_SUPPORTED'+ | 'MICROPHONE_PERMISSION_DENIED'+ | 'NETWORK_DISCONNECTED'+ | 'SESSION_CREATE_FAILED';++export type RealtimeDictationErrorCode = RealtimeAsrErrorCode | RealtimeDictationClientErrorCode;++export interface RealtimeAsrSessionResponse {+ audio: typeof REALTIME_ASR_AUDIO;+ expiresAt: string;+ limits: typeof REALTIME_ASR_LIMITS;+ protocolVersion: typeof REALTIME_ASR_PROTOCOL_VERSION;+ sessionId: string;+ token: string;+ websocketUrl: string;+}++interface ServerEventBase {+ sequence: number;+ sessionId: string;+}++export interface RealtimeAsrReadyEvent extends ServerEventBase {+ audio: typeof REALTIME_ASR_AUDIO;+ limits: typeof REALTIME_ASR_LIMITS;+ protocolVersion: typeof REALTIME_ASR_PROTOCOL_VERSION;+ type: 'session.ready';+}++export interface RealtimeAsrTranscriptEvent extends ServerEventBase {+ segmentId: string;+ text: string;+ type: 'transcript.final' | 'transcript.partial';+}++export interface RealtimeAsrCompletedEvent extends ServerEventBase {+ forwardedAudioMs: number;+ type: 'session.completed';+}++export interface RealtimeAsrCancelledEvent extends ServerEventBase {+ forwardedAudioMs: number;+ type: 'session.cancelled';+}++export interface RealtimeAsrErrorEvent extends ServerEventBase {+ code: RealtimeAsrErrorCode;+ retryable: boolean;+ type: 'session.error';+}++export type RealtimeAsrServerEvent =+ | RealtimeAsrCancelledEvent+ | RealtimeAsrCompletedEvent+ | RealtimeAsrErrorEvent+ | RealtimeAsrReadyEvent+ | RealtimeAsrTranscriptEvent;++export type RealtimeDictationStatus =+ 'connecting' | 'error' | 'finalizing' | 'idle' | 'listening' | 'requesting_permission';++export interface RealtimeDictationSnapshot {+ errorCode?: RealtimeDictationErrorCode;+ retryable: boolean;+ status: RealtimeDictationStatus;+}++const OPAQUE_ID_PATTERN = /^[\w-]+$/;+const TOKEN_PATTERN = /^[\w-]{43}$/;+const ERROR_CODES = new Set<RealtimeAsrErrorCode>([+ 'AUDIO_FORMAT_INVALID',+ 'AUTH_FAILED',+ 'BACKPRESSURE',+ 'INTERNAL_ERROR',+ 'PROTOCOL_ERROR',+ 'PROVIDER_BILLING_BLOCKED',+ 'PROVIDER_CAPACITY',+ 'PROVIDER_DISCONNECTED',+ 'PROVIDER_NOT_CONFIGURED',+ 'PROVIDER_REGION_UNAVAILABLE',+ 'PROVIDER_TIMEOUT',+ 'PROVIDER_UNAVAILABLE',+ 'SESSION_EXPIRED',+ 'SESSION_LIMIT_EXCEEDED',+ 'WORKER_RESTART',+]);++const isRecord = (value: unknown): value is Record<string, unknown> =>+ Boolean(value) && typeof value === 'object' && !Array.isArray(value);++const isOpaqueId = (value: unknown): value is string =>+ typeof value === 'string' &&+ value.length > 0 &&+ value.length <= 128 &&+ OPAQUE_ID_PATTERN.test(value);++const isExactAudio = (value: unknown): value is typeof REALTIME_ASR_AUDIO =>+ isRecord(value) &&+ value.channels === REALTIME_ASR_AUDIO.channels &&+ value.encoding === REALTIME_ASR_AUDIO.encoding &&+ value.frameBytes === REALTIME_ASR_AUDIO.frameBytes &&+ value.frameDurationMs === REALTIME_ASR_AUDIO.frameDurationMs &&+ value.sampleRate === REALTIME_ASR_AUDIO.sampleRate;++const isExactLimits = (value: unknown): value is typeof REALTIME_ASR_LIMITS =>+ isRecord(value) &&+ Object.entries(REALTIME_ASR_LIMITS).every(([key, expected]) => value[key] === expected);++const hasValidEnvelope = (+ value: Record<string, unknown>,+): value is Record<string, unknown> & ServerEventBase =>+ isOpaqueId(value.sessionId) && Number.isSafeInteger(value.sequence) && Number(value.sequence) > 0;++export class RealtimeDictationError extends Error {+ constructor(+ readonly code: RealtimeDictationErrorCode,+ readonly retryable: boolean,+ ) {+ super(code);+ this.name = 'RealtimeDictationError';+ }+}++export const parseRealtimeAsrSessionResponse = (value: unknown): RealtimeAsrSessionResponse => {+ if (+ !isRecord(value) ||+ value.protocolVersion !== REALTIME_ASR_PROTOCOL_VERSION ||+ !isOpaqueId(value.sessionId) ||+ typeof value.token !== 'string' ||+ !TOKEN_PATTERN.test(value.token) ||+ typeof value.websocketUrl !== 'string' ||+ !value.websocketUrl.startsWith('wss://') ||+ typeof value.expiresAt !== 'string' ||+ !Number.isFinite(Date.parse(value.expiresAt)) ||+ !isExactAudio(value.audio) ||+ !isExactLimits(value.limits)+ ) {+ throw new RealtimeDictationError('PROTOCOL_ERROR', false);+ }++ return value as unknown as RealtimeAsrSessionResponse;+};++export const parseRealtimeAsrServerEvent = (raw: unknown): RealtimeAsrServerEvent => {+ let value: unknown = raw;+ if (typeof raw === 'string') {+ try {+ value = JSON.parse(raw);+ } catch {+ throw new RealtimeDictationError('PROTOCOL_ERROR', false);+ }+ }++ if (!isRecord(value) || !hasValidEnvelope(value) || typeof value.type !== 'string') {+ throw new RealtimeDictationError('PROTOCOL_ERROR', false);+ }++ switch (value.type) {+ case 'session.ready': {+ if (+ value.protocolVersion !== REALTIME_ASR_PROTOCOL_VERSION ||+ !isExactAudio(value.audio) ||+ !isExactLimits(value.limits)+ ) {+ break;+ }+ return value as unknown as RealtimeAsrReadyEvent;+ }+ case 'transcript.partial':+ case 'transcript.final': {+ if (isOpaqueId(value.segmentId) && typeof value.text === 'string') {+ return value as unknown as RealtimeAsrTranscriptEvent;+ }+ break;+ }+ case 'session.completed':+ case 'session.cancelled': {+ if (Number.isSafeInteger(value.forwardedAudioMs) && Number(value.forwardedAudioMs) >= 0) {+ return value as unknown as RealtimeAsrCompletedEvent | RealtimeAsrCancelledEvent;+ }+ break;+ }+ case 'session.error': {+ if (+ typeof value.code === 'string' &&+ ERROR_CODES.has(value.code as RealtimeAsrErrorCode) &&+ typeof value.retryable === 'boolean'+ ) {+ return value as unknown as RealtimeAsrErrorEvent;+ }+ break;+ }+ }++ throw new RealtimeDictationError('PROTOCOL_ERROR', false);+};diff --git a/src/features/ChatInput/Dictation/editor.test.ts b/src/features/ChatInput/Dictation/editor.test.tsnew file mode 100644index 00000000000..59d6122908c--- /dev/null+++ b/src/features/ChatInput/Dictation/editor.test.ts@@ -0,0 +1,119 @@+import type { IEditor } from '@lobehub/editor';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isElementNode,+ $isRangeSelection,+ $isTextNode,+ createEditor,+} from 'lexical';+import { describe, expect, it, vi } from 'vitest';++import { DICTATION_UPDATE_TAG, LexicalDictationEditor } from './editor';++const createFixture = () => {+ const lexicalEditor = createEditor({ namespace: 'dictation-test' });+ lexicalEditor.update(+ () => {+ const paragraph = $createParagraphNode();+ const text = $createTextNode('draft tail');+ paragraph.append(text);+ $getRoot().append(paragraph);+ text.select(6, 6);+ },+ { discrete: true },+ );+ const editor = {+ getLexicalEditor: () => lexicalEditor,+ } as unknown as IEditor;+ return { adapter: new LexicalDictationEditor(editor), lexicalEditor };+};++const readText = (editor: ReturnType<typeof createEditor>) =>+ editor.getEditorState().read(() => $getRoot().getTextContent());++describe('LexicalDictationEditor', () => {+ it('inserts at the cursor, replaces only the dictation segment, and preserves the draft suffix', () => {+ const { adapter, lexicalEditor } = createFixture();+ const attachmentDraft = [{ id: 'attachment-1', name: 'brief.pdf' }];+ const snapshot = adapter.begin(vi.fn());++ expect(snapshot).toEqual({ anchor: 6, prefix: 'draft ', suffix: 'tail' });+ adapter.render('hel');+ expect(readText(lexicalEditor)).toBe('draft heltail');+ adapter.render('hello ');+ expect(readText(lexicalEditor)).toBe('draft hello tail');+ adapter.finalize('hello ');++ expect(readText(lexicalEditor)).toBe('draft hello tail');+ expect(attachmentDraft).toEqual([{ id: 'attachment-1', name: 'brief.pdf' }]);+ lexicalEditor.getEditorState().read(() => {+ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ expect(selection?.isCollapsed()).toBe(true);+ });+ });++ it('does not replace a selected draft range when dictation begins', () => {+ const { adapter, lexicalEditor } = createFixture();+ lexicalEditor.update(+ () => {+ const text = $getRoot().getFirstDescendant();+ if ($isTextNode(text)) text.select(0, 5);+ },+ { discrete: true },+ );++ adapter.begin(vi.fn());+ adapter.render('spoken ');++ expect(readText(lexicalEditor)).toBe('draftspoken tail');+ });++ it('detects an untagged user edit but ignores dictation-tagged updates', () => {+ const { adapter, lexicalEditor } = createFixture();+ const onUserEdit = vi.fn();+ adapter.begin(onUserEdit);+ adapter.render('spoken');+ expect(onUserEdit).not.toHaveBeenCalled();++ lexicalEditor.update(+ () => {+ const paragraph = $getRoot().getFirstChild();+ if ($isElementNode(paragraph)) paragraph.append($createTextNode(' user edit'));+ },+ { discrete: true },+ );+ expect(onUserEdit).toHaveBeenCalledOnce();++ lexicalEditor.update(() => undefined, { discrete: true, tag: DICTATION_UPDATE_TAG });+ expect(onUserEdit).toHaveBeenCalledOnce();+ });++ it('does not steal a cursor that the user moved outside the dictation segment', () => {+ const { adapter, lexicalEditor } = createFixture();+ adapter.begin(vi.fn());+ adapter.render('spoken ');+ lexicalEditor.update(+ () => {+ const textNodes = $getRoot().getAllTextNodes();+ textNodes.at(-1)?.select(2, 2);+ },+ { discrete: true, tag: DICTATION_UPDATE_TAG },+ );++ adapter.render('confirmed ');+ adapter.finalize('confirmed ');+ lexicalEditor.update(+ () => {+ const selection = $getSelection();+ if ($isRangeSelection(selection)) selection.insertText('X');+ },+ { discrete: true },+ );++ expect(readText(lexicalEditor)).toBe('draft confirmed taXil');+ });+});diff --git a/src/features/ChatInput/Dictation/editor.ts b/src/features/ChatInput/Dictation/editor.tsnew file mode 100644index 00000000000..9e59a9d7eea--- /dev/null+++ b/src/features/ChatInput/Dictation/editor.ts@@ -0,0 +1,198 @@+import type { IEditor } from '@lobehub/editor';+import {+ $createTextNode,+ $getNodeByKey,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ $isTextNode,+ $setSelection,+ type RangeSelection,+} from 'lexical';++export const DICTATION_UPDATE_TAG = 'realtime-dictation';++export interface DictationAnchorSnapshot {+ anchor: number;+ prefix: string;+ suffix: string;+}++export interface DictationEditorAdapter {+ begin: (onUserEdit: () => void) => DictationAnchorSnapshot | undefined;+ dispose: () => void;+ finalize: (text: string) => void;+ render: (text: string) => void;+}++const collapseAtFocus = (selection: RangeSelection) => {+ if (selection.isCollapsed()) return selection;++ selection.anchor.set(selection.focus.key, selection.focus.offset, selection.focus.type);+ return selection;+};++const getTextAnchor = (selection: RangeSelection) => {+ const fromStart = selection.clone();+ const root = $getRoot();+ fromStart.anchor.set(root.getKey(), 0, 'element');+ return fromStart.getTextContent().length;+};++/**+ * Owns exactly one segmented Lexical text node while dictation is active.+ * Updating that node leaves the surrounding rich draft and external attachment+ * stores untouched.+ */+export class LexicalDictationEditor implements DictationEditorAdapter {+ readonly #editor: IEditor;+ #active = false;+ #nodeKey?: string;+ #savedSelection?: RangeSelection;+ #unregisterRoot?: () => void;+ #unregisterUpdate?: () => void;++ constructor(editor: IEditor) {+ this.#editor = editor;+ }++ begin(onUserEdit: () => void): DictationAnchorSnapshot | undefined {+ this.dispose();+ const lexicalEditor = this.#editor.getLexicalEditor();+ if (!lexicalEditor) return;++ let snapshot: DictationAnchorSnapshot | undefined;+ lexicalEditor.update(+ () => {+ let selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ $getRoot().selectEnd();+ selection = $getSelection();+ }+ if (!$isRangeSelection(selection)) return;++ const savedSelection = collapseAtFocus(selection.clone());+ const text = $getRoot().getTextContent();+ const anchor = Math.max(0, Math.min(text.length, getTextAnchor(savedSelection)));+ this.#savedSelection = savedSelection;+ snapshot = { anchor, prefix: text.slice(0, anchor), suffix: text.slice(anchor) };+ },+ { discrete: true, tag: DICTATION_UPDATE_TAG },+ );+ if (!snapshot) return;++ this.#active = true;+ const handleUserEdit = () => {+ if (!this.#active) return;+ this.#active = false;+ onUserEdit();+ };+ this.#unregisterRoot = lexicalEditor.registerRootListener((root, previousRoot) => {+ previousRoot?.removeEventListener('beforeinput', handleUserEdit);+ previousRoot?.removeEventListener('cut', handleUserEdit);+ previousRoot?.removeEventListener('drop', handleUserEdit);+ previousRoot?.removeEventListener('paste', handleUserEdit);+ root?.addEventListener('beforeinput', handleUserEdit);+ root?.addEventListener('cut', handleUserEdit);+ root?.addEventListener('drop', handleUserEdit);+ root?.addEventListener('paste', handleUserEdit);+ });+ this.#unregisterUpdate = lexicalEditor.registerUpdateListener(+ ({ dirtyElements, dirtyLeaves, tags }) => {+ if (+ this.#active &&+ !tags.has(DICTATION_UPDATE_TAG) &&+ (dirtyElements.size > 0 || dirtyLeaves.size > 0)+ ) {+ handleUserEdit();+ }+ },+ );++ return snapshot;+ }++ render(text: string) {+ if (!this.#active) return;+ const lexicalEditor = this.#editor.getLexicalEditor();+ if (!lexicalEditor) return;++ lexicalEditor.update(+ () => {+ const existingNode = this.#nodeKey ? $getNodeByKey(this.#nodeKey) : undefined;+ if ($isTextNode(existingNode)) {+ const selection = $getSelection();+ const preservedSelection =+ $isRangeSelection(selection) &&+ selection.anchor.key !== existingNode.getKey() &&+ selection.focus.key !== existingNode.getKey()+ ? selection.clone()+ : undefined;+ existingNode.setTextContent(text);+ if (preservedSelection) $setSelection(preservedSelection);+ else existingNode.selectEnd();+ return;+ }++ if (!text || !this.#savedSelection) return;+ $setSelection(this.#savedSelection.clone());+ const node = $createTextNode(text).setMode('segmented');+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return;+ selection.insertNodes([node]);+ node.selectEnd();+ this.#nodeKey = node.getKey();+ },+ { discrete: true, tag: DICTATION_UPDATE_TAG },+ );+ }++ finalize(text: string) {+ const lexicalEditor = this.#editor.getLexicalEditor();+ if (lexicalEditor) {+ lexicalEditor.update(+ () => {+ const existingNode = this.#nodeKey ? $getNodeByKey(this.#nodeKey) : undefined;+ if ($isTextNode(existingNode)) {+ const selection = $getSelection();+ const preservedSelection =+ $isRangeSelection(selection) &&+ selection.anchor.key !== existingNode.getKey() &&+ selection.focus.key !== existingNode.getKey()+ ? selection.clone()+ : undefined;+ if (text) {+ existingNode.setTextContent(text).setMode('normal');+ if (preservedSelection) $setSelection(preservedSelection);+ else existingNode.selectEnd();+ } else {+ existingNode.remove();+ if (preservedSelection) $setSelection(preservedSelection);+ }+ return;+ }++ if (!text || !this.#savedSelection) return;+ $setSelection(this.#savedSelection.clone());+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return;+ const node = $createTextNode(text);+ selection.insertNodes([node]);+ node.selectEnd();+ },+ { discrete: true, tag: DICTATION_UPDATE_TAG },+ );+ }+ this.dispose();+ }++ dispose() {+ this.#active = false;+ this.#unregisterRoot?.();+ this.#unregisterUpdate?.();+ this.#unregisterRoot = undefined;+ this.#unregisterUpdate = undefined;+ this.#nodeKey = undefined;+ this.#savedSelection = undefined;+ }+}diff --git a/src/features/ChatInput/Dictation/frameQueue.test.ts b/src/features/ChatInput/Dictation/frameQueue.test.tsnew file mode 100644index 00000000000..0a3312af496--- /dev/null+++ b/src/features/ChatInput/Dictation/frameQueue.test.ts@@ -0,0 +1,58 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { BoundedWebSocketFrameQueue, type FrameWebSocket } from './frameQueue';++const frame = () => new ArrayBuffer(6400);++describe('BoundedWebSocketFrameQueue', () => {+ afterEach(() => vi.useRealTimers());++ it('sends immediately when the socket has capacity', () => {+ const socket = { bufferedAmount: 0, readyState: 1, send: vi.fn() } satisfies FrameWebSocket;+ const queue = new BoundedWebSocketFrameQueue(socket);++ expect(queue.enqueue(frame())).toBe(true);+ expect(socket.send).toHaveBeenCalledTimes(1);+ expect(queue.pendingFrames).toBe(0);+ });++ it('never buffers more than five frames under backpressure', () => {+ vi.useFakeTimers();+ const socket = {+ bufferedAmount: 6400 * 6,+ readyState: 1,+ send: vi.fn(),+ } satisfies FrameWebSocket;+ const queue = new BoundedWebSocketFrameQueue(socket);++ expect(Array.from({ length: 5 }, () => queue.enqueue(frame()))).toEqual([+ true,+ true,+ true,+ true,+ true,+ ]);+ expect(queue.enqueue(frame())).toBe(false);+ expect(queue.pendingFrames).toBe(5);+ expect(socket.send).not.toHaveBeenCalled();++ queue.dispose();+ });++ it('drains queued frames after bufferedAmount falls below the high-water mark', async () => {+ vi.useFakeTimers();+ const socket = {+ bufferedAmount: 64_000,+ readyState: 1,+ send: vi.fn(),+ } satisfies FrameWebSocket;+ const queue = new BoundedWebSocketFrameQueue(socket);+ queue.enqueue(frame());+ const empty = queue.waitForEmpty();++ socket.bufferedAmount = 0;+ await vi.advanceTimersByTimeAsync(20);+ await expect(empty).resolves.toBeUndefined();+ expect(socket.send).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/ChatInput/Dictation/frameQueue.ts b/src/features/ChatInput/Dictation/frameQueue.tsnew file mode 100644index 00000000000..f32e0f279b3--- /dev/null+++ b/src/features/ChatInput/Dictation/frameQueue.ts@@ -0,0 +1,118 @@+import { REALTIME_ASR_AUDIO, REALTIME_ASR_LIMITS } from './contract';++export interface FrameWebSocket {+ readonly bufferedAmount: number;+ readonly readyState: number;+ send: (data: ArrayBuffer | string) => void;+}++interface QueueWaiter {+ reject: (reason: Error) => void;+ resolve: () => void;+ timeout: ReturnType<typeof setTimeout>;+}++export class BoundedWebSocketFrameQueue {+ readonly #frames: ArrayBuffer[] = [];+ readonly #maxBufferedBytes: number;+ readonly #maxFrames: number;+ readonly #socket: FrameWebSocket;+ readonly #waiters = new Set<QueueWaiter>();+ #disposed = false;+ #timer?: ReturnType<typeof setTimeout>;++ constructor(+ socket: FrameWebSocket,+ options: {+ maxBufferedBytes?: number;+ maxFrames?: number;+ } = {},+ ) {+ this.#socket = socket;+ this.#maxFrames = options.maxFrames ?? REALTIME_ASR_LIMITS.maxBufferedFrames;+ this.#maxBufferedBytes =+ options.maxBufferedBytes ?? REALTIME_ASR_AUDIO.frameBytes * this.#maxFrames;+ }++ get pendingFrames() {+ return this.#frames.length;+ }++ enqueue(frame: ArrayBuffer): boolean {+ if (+ this.#disposed ||+ frame.byteLength !== REALTIME_ASR_AUDIO.frameBytes ||+ this.#frames.length >= this.#maxFrames+ ) {+ return false;+ }++ this.#frames.push(frame);+ this.#drain();+ return true;+ }++ dispose() {+ this.#disposed = true;+ this.#frames.length = 0;+ if (this.#timer) clearTimeout(this.#timer);+ this.#timer = undefined;+ for (const waiter of this.#waiters) {+ clearTimeout(waiter.timeout);+ waiter.reject(new Error('frame_queue_disposed'));+ }+ this.#waiters.clear();+ }++ waitForEmpty(timeoutMs = 1000): Promise<void> {+ this.#drain();+ if (this.#frames.length === 0) return Promise.resolve();+ if (this.#disposed) return Promise.reject(new Error('frame_queue_disposed'));++ return new Promise((resolve, reject) => {+ const waiter: QueueWaiter = {+ reject,+ resolve,+ timeout: setTimeout(() => {+ this.#waiters.delete(waiter);+ reject(new Error('frame_queue_timeout'));+ }, timeoutMs),+ };+ this.#waiters.add(waiter);+ this.#scheduleDrain();+ });+ }++ #drain = () => {+ if (this.#disposed || this.#socket.readyState !== 1) {+ if (this.#frames.length > 0) this.#scheduleDrain();+ return;+ }++ while (+ this.#frames.length > 0 &&+ this.#socket.bufferedAmount + this.#frames[0].byteLength <= this.#maxBufferedBytes+ ) {+ this.#socket.send(this.#frames.shift()!);+ }++ if (this.#frames.length === 0) {+ for (const waiter of this.#waiters) {+ clearTimeout(waiter.timeout);+ waiter.resolve();+ }+ this.#waiters.clear();+ return;+ }++ this.#scheduleDrain();+ };++ #scheduleDrain() {+ if (this.#disposed || this.#timer) return;+ this.#timer = setTimeout(() => {+ this.#timer = undefined;+ this.#drain();+ }, 20);+ }+}diff --git a/src/features/ChatInput/Dictation/index.tsx b/src/features/ChatInput/Dictation/index.tsxnew file mode 100644index 00000000000..13905caaf5b--- /dev/null+++ b/src/features/ChatInput/Dictation/index.tsx@@ -0,0 +1,366 @@+'use client';++import { Icon, Tooltip } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { LoaderCircle, Mic, RotateCcw, X } from 'lucide-react';+import type { MouseEvent } from 'react';+import { memo, useCallback, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { useServerConfigStore } from '@/store/serverConfig';++import { ChatInputAction } from '../ActionBar/components/ChatInputAction';+import { useChatInputStore, useStoreApi } from '../store';+import { isOtherAudioInputModeActive } from './mutualExclusion';+import { getDictationControlMode } from './presentation';+import { useDictationControlFocus } from './useDictationControlFocus';+import { useRealtimeDictation } from './useRealtimeDictation';++const styles = createStaticStyles(({ css, cssVar }) => ({+ cancel: css`+ color: ${cssVar.colorTextSecondary};+ `,+ controlRow: css`+ display: flex;+ flex: none;+ gap: 4px;+ align-items: center;+ `,+ controls: css`+ display: flex;+ flex: none;+ gap: 4px;+ align-items: center;++ padding: 2px;+ border-radius: 9999px;++ background: ${cssVar.colorFillSecondary};+ `,+ listening: css`+ color: ${cssVar.colorWhite};++ background: ${cssVar.colorSuccess};+ box-shadow: 0 0 0 3px ${cssVar.colorSuccessBg};++ transition:+ color 160ms ease,+ background 160ms ease,+ box-shadow 160ms ease,+ transform 120ms ease;+ animation: dictation-halo-breathe 1.6s ease-in-out infinite;++ &:hover {+ color: ${cssVar.colorWhite};+ background: ${cssVar.colorSuccessHover};+ box-shadow: 0 0 0 4px ${cssVar.colorSuccessBgHover};+ }++ &:active {+ transform: scale(0.94);+ background: ${cssVar.colorSuccessActive};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorSuccess};+ outline-offset: 3px;+ }++ @keyframes dictation-halo-breathe {+ 0%,+ 100% {+ box-shadow: 0 0 0 3px ${cssVar.colorSuccessBg};+ }++ 50% {+ box-shadow: 0 0 0 6px ${cssVar.colorSuccessBgHover};+ }+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ animation: none;+ }+ `,+ listeningStatus: css`+ position: absolute;++ overflow: hidden;++ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ border: 0;++ white-space: nowrap;++ clip: rect(0, 0, 0, 0);+ `,+ spin: css`+ animation: dictation-spin 1s linear infinite;++ @keyframes dictation-spin {+ to {+ transform: rotate(360deg);+ }+ }++ @media (prefers-reduced-motion: reduce) {+ animation: none;+ }+ `,+ status: css`+ overflow: hidden;++ max-width: 160px;+ padding-inline: 6px 2px;++ font-size: ${cssVar.fontSizeSM};+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++const Dictation = memo(() => {+ const { t } = useTranslation('chat');+ const enabled = useServerConfigStore((s) => s.featureFlags.enableVoiceDictation === true);+ const storeApi = useStoreApi();+ const [activeAudioInputMode, editor, mobile, generating, setActiveAudioInputMode] =+ useChatInputStore((s) => [+ s.activeAudioInputMode,+ s.editor,+ s.mobile,+ Boolean(s.sendButtonProps?.generating),+ s.setActiveAudioInputMode,+ ]);+ const { client, errorCode, retryable, status } = useRealtimeDictation(editor);+ const active = status !== 'idle' || activeAudioInputMode === 'dictation';+ const controlMode = getDictationControlMode(status);+ const otherAudioModeActive = isOtherAudioInputModeActive(activeAudioInputMode, 'dictation');+ const {+ actionRef,+ cancelRef,+ handleKeyboardActivation,+ preserveFocusOnActivation,+ retryRef,+ stopRef,+ } = useDictationControlFocus({ active, retryable, status });++ useEffect(() => {+ if (!client) return;+ if (status !== 'idle' && activeAudioInputMode !== 'dictation') {+ setActiveAudioInputMode('dictation');+ } else if (status === 'idle' && activeAudioInputMode === 'dictation') {+ setActiveAudioInputMode(undefined);+ }+ }, [activeAudioInputMode, client, setActiveAudioInputMode, status]);++ useEffect(+ () => () => {+ if (storeApi.getState().activeAudioInputMode === 'dictation') {+ storeApi.getState().setActiveAudioInputMode(undefined);+ }+ },+ [storeApi],+ );++ useEffect(() => {+ if (generating && active) void client?.cancel('audio_interruption');+ }, [active, client, generating]);++ useEffect(() => {+ if ((!enabled || mobile) && activeAudioInputMode === 'dictation') {+ void client?.dispose();+ setActiveAudioInputMode(undefined);+ }+ }, [activeAudioInputMode, client, enabled, mobile, setActiveAudioInputMode]);++ const start = useCallback(() => {+ if (!client || generating || otherAudioModeActive) return;+ setActiveAudioInputMode('dictation');+ void client.start();+ }, [client, generating, otherAudioModeActive, setActiveAudioInputMode]);++ const dismiss = useCallback(() => {+ void client?.dispose();+ setActiveAudioInputMode(undefined);+ }, [client, setActiveAudioInputMode]);++ const handleStart = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ preserveFocusOnActivation(event);+ start();+ },+ [preserveFocusOnActivation, start],+ );++ const handleStop = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ preserveFocusOnActivation(event);+ void client?.stop();+ },+ [client, preserveFocusOnActivation],+ );++ const handleCancel = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ preserveFocusOnActivation(event);+ void client?.cancel();+ },+ [client, preserveFocusOnActivation],+ );++ const handleDismiss = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ preserveFocusOnActivation(event);+ dismiss();+ },+ [dismiss, preserveFocusOnActivation],+ );++ if (!enabled || mobile || !client) return null;++ if (!active) {+ const disabled = generating || otherAudioModeActive;+ const title = generating+ ? t('voiceDictation.replyInProgress')+ : otherAudioModeActive+ ? t('voiceDictation.otherAudioModeActive')+ : t('voiceDictation.action');++ return disabled ? (+ <Tooltip title={title}>+ <ChatInputAction+ disabled+ aria-label={t('voiceDictation.action')}+ data-testid="voice-dictation-action"+ icon={Mic}+ ref={actionRef}+ showTooltip={false}+ title={title}+ />+ </Tooltip>+ ) : (+ <ChatInputAction+ aria-label={t('voiceDictation.action')}+ data-testid="voice-dictation-action"+ icon={Mic}+ ref={actionRef}+ title={t('voiceDictation.action')}+ onClick={handleStart}+ onKeyDown={(event) => handleKeyboardActivation(event, start)}+ />+ );+ }++ const errorText = errorCode ? t(`voiceDictation.error.${errorCode}`) : undefined;+ const statusText =+ status === 'requesting_permission'+ ? t('voiceDictation.requestingPermission')+ : status === 'connecting'+ ? t('voiceDictation.connecting')+ : status === 'listening'+ ? t('voiceDictation.listening')+ : status === 'finalizing'+ ? t('voiceDictation.finalizing')+ : errorText;++ if (controlMode === 'listening') {+ return (+ <div+ aria-label={t('voiceDictation.statusLabel')}+ className={styles.controlRow}+ data-status="listening"+ data-testid="voice-dictation-controls"+ role="group"+ >+ <span aria-live="polite" className={styles.listeningStatus} role="status">+ {statusText}+ </span>+ <ChatInputAction+ aria-label={t('voiceDictation.stop')}+ className={styles.listening}+ data-testid="voice-dictation-stop"+ icon={Mic}+ ref={stopRef}+ style={{ borderRadius: '50%' }}+ title={t('voiceDictation.stop')}+ onClick={handleStop}+ onKeyDown={(event) =>+ handleKeyboardActivation(event, () => {+ void client?.stop();+ })+ }+ />+ <ChatInputAction+ aria-label={t('voiceDictation.cancel')}+ className={styles.cancel}+ data-testid="voice-dictation-cancel"+ icon={X}+ ref={cancelRef}+ title={t('voiceDictation.cancel')}+ onClick={handleCancel}+ onKeyDown={(event) =>+ handleKeyboardActivation(event, () => {+ void client?.cancel();+ })+ }+ />+ </div>+ );+ }++ return (+ <div+ aria-label={t('voiceDictation.statusLabel')}+ className={styles.controlRow}+ data-status={status}+ data-testid="voice-dictation-controls"+ role="group"+ >+ <div className={styles.controls}>+ <span aria-live="polite" className={styles.status} role="status">+ {statusText}+ </span>+ {status === 'error' && retryable ? (+ <ChatInputAction+ aria-label={t('voiceDictation.retry')}+ data-testid="voice-dictation-retry"+ icon={RotateCcw}+ ref={retryRef}+ title={t('voiceDictation.retry')}+ onClick={handleStart}+ onKeyDown={(event) => handleKeyboardActivation(event, start)}+ />+ ) : status !== 'error' ? (+ <Icon aria-hidden className={styles.spin} icon={LoaderCircle} size={18} />+ ) : null}+ </div>+ <ChatInputAction+ aria-label={status === 'error' ? t('voiceDictation.dismiss') : t('voiceDictation.cancel')}+ className={styles.cancel}+ data-testid="voice-dictation-cancel"+ icon={X}+ ref={cancelRef}+ title={status === 'error' ? t('voiceDictation.dismiss') : t('voiceDictation.cancel')}+ onClick={status === 'error' ? handleDismiss : handleCancel}+ onKeyDown={(event) =>+ handleKeyboardActivation(event, () => {+ if (status === 'error') {+ dismiss();+ return;+ }++ void client?.cancel();+ })+ }+ />+ </div>+ );+});++Dictation.displayName = 'Dictation';++export default Dictation;diff --git a/src/features/ChatInput/Dictation/mutualExclusion.test.ts b/src/features/ChatInput/Dictation/mutualExclusion.test.tsnew file mode 100644index 00000000000..0c47a49ef0a--- /dev/null+++ b/src/features/ChatInput/Dictation/mutualExclusion.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { isOtherAudioInputModeActive } from './mutualExclusion';++describe('audio input mutual exclusion', () => {+ it('blocks dictation while a voice message is active', () => {+ expect(isOtherAudioInputModeActive('voiceMessage', 'dictation')).toBe(true);+ });++ it('blocks voice messages while dictation is active', () => {+ expect(isOtherAudioInputModeActive('dictation', 'voiceMessage')).toBe(true);+ });++ it('allows an idle or same-mode control', () => {+ expect(isOtherAudioInputModeActive(undefined, 'dictation')).toBe(false);+ expect(isOtherAudioInputModeActive('dictation', 'dictation')).toBe(false);+ });+});diff --git a/src/features/ChatInput/Dictation/mutualExclusion.ts b/src/features/ChatInput/Dictation/mutualExclusion.tsnew file mode 100644index 00000000000..293ddb1019f--- /dev/null+++ b/src/features/ChatInput/Dictation/mutualExclusion.ts@@ -0,0 +1,6 @@+import type { State } from '../store/initialState';++export const isOtherAudioInputModeActive = (+ activeMode: State['activeAudioInputMode'],+ ownMode: NonNullable<State['activeAudioInputMode']>,+) => activeMode !== undefined && activeMode !== ownMode;diff --git a/src/features/ChatInput/Dictation/presentation.test.ts b/src/features/ChatInput/Dictation/presentation.test.tsnew file mode 100644index 00000000000..b42f335c7d6--- /dev/null+++ b/src/features/ChatInput/Dictation/presentation.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';++import { getDictationControlMode } from './presentation';++describe('getDictationControlMode', () => {+ it('reserves the active microphone presentation for live listening', () => {+ expect(getDictationControlMode('idle')).toBe('idle');+ expect(getDictationControlMode('requesting_permission')).toBe('busy');+ expect(getDictationControlMode('connecting')).toBe('busy');+ expect(getDictationControlMode('listening')).toBe('listening');+ expect(getDictationControlMode('finalizing')).toBe('busy');+ expect(getDictationControlMode('error')).toBe('error');+ });+});diff --git a/src/features/ChatInput/Dictation/presentation.ts b/src/features/ChatInput/Dictation/presentation.tsnew file mode 100644index 00000000000..98776b44e7e--- /dev/null+++ b/src/features/ChatInput/Dictation/presentation.ts@@ -0,0 +1,11 @@+import type { RealtimeDictationStatus } from './contract';++export type DictationControlMode = 'busy' | 'error' | 'idle' | 'listening';++export const getDictationControlMode = (status: RealtimeDictationStatus): DictationControlMode => {+ if (status === 'listening') return 'listening';+ if (status === 'error') return 'error';+ if (status === 'idle') return 'idle';++ return 'busy';+};diff --git a/src/features/ChatInput/Dictation/service.test.ts b/src/features/ChatInput/Dictation/service.test.tsnew file mode 100644index 00000000000..2d62599a5cd--- /dev/null+++ b/src/features/ChatInput/Dictation/service.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { REALTIME_ASR_AUDIO, REALTIME_ASR_LIMITS } from './contract';+import { createRealtimeAsrSession } from './service';++vi.mock('@/business/client/trpc-headers', () => ({+ getBusinessTrpcHeaders: vi.fn().mockResolvedValue({ 'X-Test-Scope': 'scope-1' }),+}));++const responseBody = {+ audio: REALTIME_ASR_AUDIO,+ expiresAt: '2026-08-10T04:00:00.000Z',+ limits: REALTIME_ASR_LIMITS,+ protocolVersion: 1,+ sessionId: 'session-1',+ token: 'a'.repeat(43),+ websocketUrl: 'wss://asr.example.test/v1/session',+};++describe('createRealtimeAsrSession', () => {+ beforeEach(() => vi.clearAllMocks());++ it('uses the provider-neutral Lobe Session API and validates its frozen contract', async () => {+ const fetcher = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(responseBody), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ }),+ );+ const controller = new AbortController();++ await expect(createRealtimeAsrSession(controller.signal, fetcher)).resolves.toEqual(+ responseBody,+ );+ expect(fetcher).toHaveBeenCalledOnce();+ const [url, init] = fetcher.mock.calls[0];+ expect(url).toBe('/api/asr/realtime/session');+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({ platform: 'web' });+ expect(init.headers.get('X-Test-Scope')).toBe('scope-1');+ });++ it('rejects a session with a non-secure WebSocket URL', async () => {+ const fetcher = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({ ...responseBody, websocketUrl: 'ws://provider.example.test' }),+ {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ },+ ),+ );++ await expect(+ createRealtimeAsrSession(new AbortController().signal, fetcher),+ ).rejects.toMatchObject({ code: 'PROTOCOL_ERROR', retryable: false });+ });++ it.each([+ [401, 'AUTH_FAILED', false],+ [402, 'PROVIDER_BILLING_BLOCKED', false],+ [429, 'SESSION_LIMIT_EXCEEDED', true],+ [503, 'PROVIDER_UNAVAILABLE', true],+ ])('maps HTTP %i to stable error %s', async (status, code, retryable) => {+ const fetcher = vi.fn().mockResolvedValue(new Response(null, { status }));++ await expect(+ createRealtimeAsrSession(new AbortController().signal, fetcher),+ ).rejects.toMatchObject({ code, retryable });+ });+});diff --git a/src/features/ChatInput/Dictation/service.ts b/src/features/ChatInput/Dictation/service.tsnew file mode 100644index 00000000000..abd3c0eefa4--- /dev/null+++ b/src/features/ChatInput/Dictation/service.ts@@ -0,0 +1,47 @@+import { getBusinessTrpcHeaders } from '@/business/client/trpc-headers';++import {+ parseRealtimeAsrSessionResponse,+ type RealtimeAsrSessionResponse,+ RealtimeDictationError,+} from './contract';++const mapSessionError = (status: number) => {+ if (status === 401 || status === 403) return new RealtimeDictationError('AUTH_FAILED', false);+ if (status === 402) return new RealtimeDictationError('PROVIDER_BILLING_BLOCKED', false);+ if (status === 429) return new RealtimeDictationError('SESSION_LIMIT_EXCEEDED', true);+ if (status === 404) return new RealtimeDictationError('PROVIDER_NOT_CONFIGURED', false);+ if (status >= 500) return new RealtimeDictationError('PROVIDER_UNAVAILABLE', true);+ return new RealtimeDictationError('SESSION_CREATE_FAILED', false);+};++export const createRealtimeAsrSession = async (+ signal: AbortSignal,+ fetcher: typeof fetch = fetch,+): Promise<RealtimeAsrSessionResponse> => {+ const headers = new Headers({ 'Content-Type': 'application/json' });+ const businessHeaders = await getBusinessTrpcHeaders();+ for (const [key, value] of Object.entries(businessHeaders)) headers.set(key, value);++ let response: Response;+ try {+ response = await fetcher('/api/asr/realtime/session', {+ body: JSON.stringify({ platform: 'web' }),+ headers,+ method: 'POST',+ signal,+ });+ } catch (error) {+ if (signal.aborted) throw error;+ throw new RealtimeDictationError('NETWORK_DISCONNECTED', true);+ }++ if (!response.ok) throw mapSessionError(response.status);++ try {+ return parseRealtimeAsrSessionResponse(await response.json());+ } catch (error) {+ if (error instanceof RealtimeDictationError) throw error;+ throw new RealtimeDictationError('PROTOCOL_ERROR', false);+ }+};diff --git a/src/features/ChatInput/Dictation/transcript.test.ts b/src/features/ChatInput/Dictation/transcript.test.tsnew file mode 100644index 00000000000..deef1c677e1--- /dev/null+++ b/src/features/ChatInput/Dictation/transcript.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest';++import type { RealtimeAsrTranscriptEvent } from './contract';+import { DictationTranscript } from './transcript';++const event = (+ sequence: number,+ type: RealtimeAsrTranscriptEvent['type'],+ text: string,+ segmentId = 'segment-1',+ sessionId = 'session-1',+): RealtimeAsrTranscriptEvent => ({ segmentId, sequence, sessionId, text, type });++describe('DictationTranscript', () => {+ it('replaces partial text and commits final text without touching prefix or suffix', () => {+ const transcript = new DictationTranscript({+ anchor: 6,+ prefix: 'hello ',+ sessionId: 'session-1',+ suffix: ' world',+ });++ transcript.accept(event(1, 'transcript.partial', '你'));+ transcript.accept(event(2, 'transcript.partial', '你好'));+ transcript.accept(event(3, 'transcript.final', '你好'));++ expect(transcript.snapshot).toMatchObject({+ committed: '你好',+ partial: '',+ prefix: 'hello ',+ suffix: ' world',+ text: 'hello 你好 world',+ });+ });++ it('ignores old sessions, duplicate sequence numbers, and out-of-order events', () => {+ const transcript = new DictationTranscript({+ anchor: 0,+ prefix: '',+ sessionId: 'session-1',+ suffix: '',+ });++ expect(+ transcript.accept(event(1, 'transcript.partial', 'old', 'segment-1', 'session-old')),+ ).toMatchObject({ accepted: false });+ expect(transcript.accept(event(2, 'transcript.partial', 'new'))).toMatchObject({+ accepted: true,+ });+ expect(transcript.accept(event(2, 'transcript.partial', 'duplicate'))).toMatchObject({+ accepted: false,+ });+ expect(transcript.accept(event(1, 'transcript.final', 'out-of-order'))).toMatchObject({+ accepted: false,+ });+ expect(transcript.dictatedText).toBe('new');+ });++ it('rejects a new segment until the active segment is finalized and deduplicates finals', () => {+ const transcript = new DictationTranscript({+ anchor: 0,+ prefix: '',+ sessionId: 'session-1',+ suffix: '',+ });++ transcript.accept(event(1, 'transcript.partial', 'one'));+ expect(transcript.accept(event(2, 'transcript.partial', 'two', 'segment-2'))).toMatchObject({+ accepted: false,+ });+ transcript.accept(event(3, 'transcript.final', 'one'));+ expect(transcript.accept(event(4, 'transcript.final', 'one again'))).toMatchObject({+ accepted: false,+ });+ transcript.accept(event(5, 'transcript.final', 'two', 'segment-2'));+ expect(transcript.dictatedText).toBe('onetwo');+ });++ it('drops only the unconfirmed partial on cancel', () => {+ const transcript = new DictationTranscript({+ anchor: 0,+ prefix: '',+ sessionId: 'session-1',+ suffix: '',+ });+ transcript.accept(event(1, 'transcript.final', 'confirmed'));+ transcript.accept(event(2, 'transcript.partial', 'temporary', 'segment-2'));++ transcript.discardPartial();++ expect(transcript.snapshot).toMatchObject({ committed: 'confirmed', partial: '' });+ });+});diff --git a/src/features/ChatInput/Dictation/transcript.ts b/src/features/ChatInput/Dictation/transcript.tsnew file mode 100644index 00000000000..a41ec0a38d9--- /dev/null+++ b/src/features/ChatInput/Dictation/transcript.ts@@ -0,0 +1,94 @@+import { type RealtimeAsrServerEvent } from './contract';++export interface DictationTextSnapshot {+ anchor: number;+ committed: string;+ partial: string;+ prefix: string;+ sessionId: string;+ suffix: string;+ text: string;+}++export interface DictationEventResult {+ accepted: boolean;+ changed: boolean;+}++export class DictationTranscript {+ readonly #anchor: number;+ readonly #committedSegmentIds = new Set<string>();+ readonly #prefix: string;+ readonly #sessionId: string;+ readonly #suffix: string;+ #committed = '';+ #currentSegmentId?: string;+ #lastSequence = 0;+ #partial = '';++ constructor(options: { anchor: number; prefix: string; sessionId: string; suffix: string }) {+ this.#anchor = options.anchor;+ this.#prefix = options.prefix;+ this.#sessionId = options.sessionId;+ this.#suffix = options.suffix;+ }++ get dictatedText() {+ return this.#committed + this.#partial;+ }++ get snapshot(): DictationTextSnapshot {+ return {+ anchor: this.#anchor,+ committed: this.#committed,+ partial: this.#partial,+ prefix: this.#prefix,+ sessionId: this.#sessionId,+ suffix: this.#suffix,+ text: this.#prefix + this.dictatedText + this.#suffix,+ };+ }++ accept(event: RealtimeAsrServerEvent): DictationEventResult {+ if (event.sessionId !== this.#sessionId || event.sequence <= this.#lastSequence) {+ return { accepted: false, changed: false };+ }++ this.#lastSequence = event.sequence;+ if (event.type !== 'transcript.partial' && event.type !== 'transcript.final') {+ return { accepted: true, changed: false };+ }++ if (this.#committedSegmentIds.has(event.segmentId)) {+ return { accepted: false, changed: false };+ }++ if (event.type === 'transcript.partial') {+ if (this.#currentSegmentId && this.#currentSegmentId !== event.segmentId) {+ return { accepted: false, changed: false };+ }++ const changed = this.#partial !== event.text;+ this.#currentSegmentId = event.segmentId;+ this.#partial = event.text;+ return { accepted: true, changed };+ }++ if (this.#currentSegmentId && this.#currentSegmentId !== event.segmentId) {+ return { accepted: false, changed: false };+ }++ this.#committed += event.text;+ this.#partial = '';+ this.#currentSegmentId = undefined;+ this.#committedSegmentIds.add(event.segmentId);+ return { accepted: true, changed: true };+ }++ discardPartial() {+ const changed = this.#partial.length > 0;+ this.#partial = '';+ this.#currentSegmentId = undefined;+ return changed;+ }+}diff --git a/src/features/ChatInput/Dictation/useDictationControlFocus.test.ts b/src/features/ChatInput/Dictation/useDictationControlFocus.test.tsnew file mode 100644index 00000000000..b4121978dd0--- /dev/null+++ b/src/features/ChatInput/Dictation/useDictationControlFocus.test.ts@@ -0,0 +1,207 @@+import { act, renderHook } from '@testing-library/react';+import type { RefObject } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { RealtimeDictationStatus } from './contract';+import { useDictationControlFocus } from './useDictationControlFocus';++const mountControl = (ref: RefObject<HTMLDivElement | null>) => {+ const control = document.createElement('div');+ control.tabIndex = 0;+ document.body.append(control);+ ref.current = control;++ return control;+};++const unmountControl = (ref: RefObject<HTMLDivElement | null>) => {+ ref.current?.remove();+ ref.current = null;+};++afterEach(() => {+ document.body.innerHTML = '';+});++describe('useDictationControlFocus', () => {+ it('activates controls with Enter and Space while rejecting repeats and unrelated keys', () => {+ const { result } = renderHook(() =>+ useDictationControlFocus({ active: false, retryable: false, status: 'idle' }),+ );+ const activate = vi.fn();+ const preventDefault = vi.fn();++ act(() =>+ result.current.handleKeyboardActivation(+ { key: 'Enter', preventDefault, repeat: false },+ activate,+ ),+ );+ act(() =>+ result.current.handleKeyboardActivation(+ { key: ' ', preventDefault, repeat: false },+ activate,+ ),+ );+ act(() =>+ result.current.handleKeyboardActivation(+ { key: 'Escape', preventDefault, repeat: false },+ activate,+ ),+ );+ act(() =>+ result.current.handleKeyboardActivation(+ { key: 'Enter', preventDefault, repeat: true },+ activate,+ ),+ );++ expect(activate).toHaveBeenCalledTimes(2);+ expect(preventDefault).toHaveBeenCalledTimes(2);+ });++ it('keeps keyboard focus within the controls across the dictation lifecycle', () => {+ const { rerender, result } = renderHook(+ ({+ active,+ retryable,+ status,+ }: {+ active: boolean;+ retryable: boolean;+ status: RealtimeDictationStatus;+ }) => useDictationControlFocus({ active, retryable, status }),+ {+ initialProps: {+ active: false,+ retryable: false,+ status: 'idle' as RealtimeDictationStatus,+ },+ },+ );+ const action = mountControl(result.current.actionRef);+ action.focus();++ act(() => result.current.preserveFocusOnActivation({ detail: 0 }));+ unmountControl(result.current.actionRef);+ const connectingCancel = mountControl(result.current.cancelRef);+ rerender({ active: true, retryable: false, status: 'requesting_permission' });+ expect(document.activeElement).toBe(connectingCancel);++ unmountControl(result.current.cancelRef);+ const stop = mountControl(result.current.stopRef);+ mountControl(result.current.cancelRef);+ rerender({ active: true, retryable: false, status: 'listening' });+ expect(document.activeElement).toBe(stop);++ unmountControl(result.current.stopRef);+ rerender({ active: true, retryable: false, status: 'finalizing' });+ expect(document.activeElement).toBe(result.current.cancelRef.current);++ unmountControl(result.current.cancelRef);+ const restoredAction = mountControl(result.current.actionRef);+ rerender({ active: false, retryable: false, status: 'idle' });+ expect(document.activeElement).toBe(restoredAction);+ });++ it('does not force focus transfer for pointer activation', () => {+ const { rerender, result } = renderHook(+ ({ active, status }: { active: boolean; status: RealtimeDictationStatus }) =>+ useDictationControlFocus({ active, retryable: false, status }),+ { initialProps: { active: false, status: 'idle' as RealtimeDictationStatus } },+ );+ const action = mountControl(result.current.actionRef);+ action.focus();++ act(() => result.current.preserveFocusOnActivation({ detail: 1 }));+ unmountControl(result.current.actionRef);+ const cancel = mountControl(result.current.cancelRef);+ rerender({ active: true, status: 'connecting' });++ expect(document.activeElement).not.toBe(cancel);+ });++ it('does not steal focus after the user moves outside the dictation controls', () => {+ const { rerender, result } = renderHook(+ ({ active, status }: { active: boolean; status: RealtimeDictationStatus }) =>+ useDictationControlFocus({ active, retryable: false, status }),+ { initialProps: { active: false, status: 'idle' as RealtimeDictationStatus } },+ );+ const action = mountControl(result.current.actionRef);+ action.focus();++ act(() => result.current.preserveFocusOnActivation({ detail: 0 }));+ unmountControl(result.current.actionRef);+ mountControl(result.current.cancelRef);+ rerender({ active: true, status: 'connecting' });++ const outside = document.createElement('button');+ document.body.append(outside);+ outside.focus();+ unmountControl(result.current.cancelRef);+ const stop = mountControl(result.current.stopRef);+ mountControl(result.current.cancelRef);+ rerender({ active: true, status: 'listening' });++ expect(document.activeElement).toBe(outside);+ expect(document.activeElement).not.toBe(stop);+ });++ it('keeps focus managed while idle status exits the active control row', () => {+ const { rerender, result } = renderHook(+ ({ active }: { active: boolean }) =>+ useDictationControlFocus({ active, retryable: false, status: 'idle' }),+ { initialProps: { active: true } },+ );+ const cancel = mountControl(result.current.cancelRef);+ cancel.focus();++ act(() =>+ result.current.handleKeyboardActivation(+ { key: 'Enter', preventDefault: vi.fn(), repeat: false },+ vi.fn(),+ ),+ );+ rerender({ active: true });+ expect(document.activeElement).toBe(cancel);++ unmountControl(result.current.cancelRef);+ const action = mountControl(result.current.actionRef);+ rerender({ active: false });++ expect(document.activeElement).toBe(action);+ });++ it('preserves keyboard focus across the idle transition before permission is requested', () => {+ const { rerender, result } = renderHook(+ ({ active, status }: { active: boolean; status: RealtimeDictationStatus }) =>+ useDictationControlFocus({ active, retryable: false, status }),+ { initialProps: { active: false, status: 'idle' as RealtimeDictationStatus } },+ );+ const action = mountControl(result.current.actionRef);+ action.focus();++ act(() =>+ result.current.handleKeyboardActivation(+ { key: 'Enter', preventDefault: vi.fn(), repeat: false },+ vi.fn(),+ ),+ );++ unmountControl(result.current.actionRef);+ const pendingCancel = mountControl(result.current.cancelRef);+ rerender({ active: true, status: 'idle' });+ expect(document.activeElement).toBe(pendingCancel);++ unmountControl(result.current.cancelRef);+ const pendingAction = mountControl(result.current.actionRef);+ rerender({ active: false, status: 'idle' });+ expect(document.activeElement).toBe(pendingAction);++ unmountControl(result.current.actionRef);+ const permissionCancel = mountControl(result.current.cancelRef);+ rerender({ active: true, status: 'requesting_permission' });++ expect(document.activeElement).toBe(permissionCancel);+ });+});diff --git a/src/features/ChatInput/Dictation/useDictationControlFocus.ts b/src/features/ChatInput/Dictation/useDictationControlFocus.tsnew file mode 100644index 00000000000..a1f13f49568--- /dev/null+++ b/src/features/ChatInput/Dictation/useDictationControlFocus.ts@@ -0,0 +1,102 @@+'use client';++import type { KeyboardEvent, MouseEvent, RefObject } from 'react';+import { useCallback, useEffect, useRef } from 'react';++import type { RealtimeDictationStatus } from './contract';++interface DictationControlFocusOptions {+ active: boolean;+ retryable: boolean;+ status: RealtimeDictationStatus;+}++interface DictationControlRefs {+ actionRef: RefObject<HTMLDivElement | null>;+ cancelRef: RefObject<HTMLDivElement | null>;+ retryRef: RefObject<HTMLDivElement | null>;+ stopRef: RefObject<HTMLDivElement | null>;+}++const getFocusTarget = (+ refs: DictationControlRefs,+ status: RealtimeDictationStatus,+ retryable: boolean,+ active: boolean,+) => {+ if (!active) return refs.actionRef.current;+ if (status === 'listening') return refs.stopRef.current;+ if (status === 'error' && retryable) return refs.retryRef.current;++ return refs.cancelRef.current;+};++export const useDictationControlFocus = ({+ active,+ retryable,+ status,+}: DictationControlFocusOptions) => {+ const actionRef = useRef<HTMLDivElement>(null);+ const cancelRef = useRef<HTMLDivElement>(null);+ const retryRef = useRef<HTMLDivElement>(null);+ const stopRef = useRef<HTMLDivElement>(null);+ const awaitingSessionRef = useRef(false);+ const manageFocusRef = useRef(false);++ const preserveFocusOnActivation = useCallback(+ (event: Pick<MouseEvent, 'detail'>) => {+ manageFocusRef.current = event.detail === 0;+ awaitingSessionRef.current = event.detail === 0 && !active;+ },+ [active],+ );++ const handleKeyboardActivation = useCallback(+ (+ event: Pick<KeyboardEvent<HTMLDivElement>, 'key' | 'preventDefault' | 'repeat'>,+ activate: () => void,+ ) => {+ if ((event.key !== 'Enter' && event.key !== ' ') || event.repeat) return;++ event.preventDefault();+ manageFocusRef.current = true;+ awaitingSessionRef.current = !active;+ activate();+ },+ [active],+ );++ useEffect(() => {+ if (!manageFocusRef.current) return;++ if (status !== 'idle') awaitingSessionRef.current = false;++ const refs = { actionRef, cancelRef, retryRef, stopRef };+ const controls = Object.values(refs)+ .map((ref) => ref.current)+ .filter((control): control is HTMLDivElement => Boolean(control));+ const activeElement = document.activeElement;++ if (+ activeElement &&+ activeElement !== document.body &&+ !controls.includes(activeElement as HTMLDivElement)+ ) {+ manageFocusRef.current = false;+ return;+ }++ getFocusTarget(refs, status, retryable, active)?.focus({ preventScroll: true });++ if (!active && !awaitingSessionRef.current) manageFocusRef.current = false;+ }, [active, retryable, status]);++ return {+ actionRef,+ cancelRef,+ handleKeyboardActivation,+ preserveFocusOnActivation,+ retryRef,+ stopRef,+ };+};diff --git a/src/features/ChatInput/Dictation/useRealtimeDictation.ts b/src/features/ChatInput/Dictation/useRealtimeDictation.tsnew file mode 100644index 00000000000..ab31a619d04--- /dev/null+++ b/src/features/ChatInput/Dictation/useRealtimeDictation.ts@@ -0,0 +1,45 @@+'use client';++import type { IEditor } from '@lobehub/editor';+import { useEffect, useMemo, useSyncExternalStore } from 'react';++import { BrowserAudioWorkletCapture, requestDictationMicrophone } from './audio';+import { RealtimeDictationClient } from './client';+import { LexicalDictationEditor } from './editor';+import { createRealtimeAsrSession } from './service';++const createSocket = (url: string) => new WebSocket(url);+const FALLBACK_SNAPSHOT = { retryable: false, status: 'idle' as const };+const getFallbackSnapshot = () => FALLBACK_SNAPSHOT;+const subscribeFallback = () => () => undefined;++export const useRealtimeDictation = (editor?: IEditor) => {+ const client = useMemo(+ () =>+ editor+ ? new RealtimeDictationClient({+ createCapture: BrowserAudioWorkletCapture.create,+ createSession: createRealtimeAsrSession,+ createWebSocket: createSocket,+ editor: new LexicalDictationEditor(editor),+ requestMicrophone: requestDictationMicrophone,+ })+ : undefined,+ [editor],+ );++ const snapshot = useSyncExternalStore(+ client?.subscribe ?? subscribeFallback,+ client?.getSnapshot ?? getFallbackSnapshot,+ client?.getSnapshot ?? getFallbackSnapshot,+ );++ useEffect(+ () => () => {+ void client?.dispose();+ },+ [client],+ );++ return { client, ...snapshot };+};diff --git a/src/features/ChatInput/SendArea/index.tsx b/src/features/ChatInput/SendArea/index.tsxindex 7e938f04e13..258fadac6e9 100644--- a/src/features/ChatInput/SendArea/index.tsx+++ b/src/features/ChatInput/SendArea/index.tsx@@ -29,25 +29,28 @@ const SendArea = memo<SendAreaProps>(({ hideContextWindow = true }) => {const { canShowControls } = useChatInputResourceAccess();const allowExpand = useChatInputStore((s) => s.allowExpand);const rightActions = useChatInputStore((s) => s.rightActions, isEqual);- const voiceMessageActive = useChatInputStore((s) => s.activeAudioInputMode === 'voiceMessage');+ const activeAudioInputMode = useChatInputStore((s) => s.activeAudioInputMode);+ const audioInputActive = activeAudioInputMode !== undefined;const items = useMemo(() =>canShowControls? mapActionsToItems(- voiceMessageActive- ? (['voiceMessage'] as ActionKey[])+ audioInputActive+ ? ([+ activeAudioInputMode === 'dictation' ? 'voiceDictation' : 'voiceMessage',+ ] as ActionKey[]): resolveSendAreaActionKeys(rightActions as ActionKey[], hideContextWindow),): [],- [canShowControls, hideContextWindow, rightActions, voiceMessageActive],+ [activeAudioInputMode, audioInputActive, canShowControls, hideContextWindow, rightActions],);return (<Flexbox horizontal align={'center'} flex={'none'} gap={12}>- {canShowControls && allowExpand && !voiceMessageActive && <ExpandButton />}+ {canShowControls && allowExpand && !audioInputActive && <ExpandButton />}{items}- {!voiceMessageActive && <SendButton />}+ {!audioInputActive && <SendButton />}</Flexbox>);});diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsxindex 60241e1ba38..5ce6680d6bc 100644--- a/src/features/Portal/Thread/Chat/index.tsx+++ b/src/features/Portal/Thread/Chat/index.tsx@@ -98,7 +98,10 @@ const ThreadChatContent = memo<ThreadChatContentProps>(</Suspense>{composerWritable && inputMode === 'heterogeneous' && <HeterogeneousChatInput />}{composerWritable && inputMode === 'default' && (- <ChatInput leftActions={['typo']} rightActions={['voiceMessage', 'contextWindow']} />+ <ChatInput+ leftActions={['typo']}+ rightActions={['voiceDictation', 'voiceMessage', 'contextWindow']}+ />)}</>);diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsxindex 0e33ac653ac..24f84cdfd6a 100644--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx@@ -15,9 +15,10 @@ import { userGeneralSettingsSelectors } from '@/store/user/selectors';import AgentConfigError from './AgentConfigError';import { useSendMenuItems } from './useSendMenuItems';-const contextWindowRightActions: ActionKeys[] = ['voiceMessage', 'contextWindow'];+const contextWindowRightActions: ActionKeys[] = ['voiceDictation', 'voiceMessage', 'contextWindow'];const promptTransformRightActions: ActionKeys[] = ['promptTransform',+ 'voiceDictation','voiceMessage','contextWindow',];diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsxindex b5e37bae76b..d296c0ef1c7 100644--- a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx@@ -19,7 +19,7 @@ const leftActions: ActionKeys[] = [['typo', 'params', 'clear'],];-const rightActions: ActionKeys[] = ['voiceMessage', 'contextWindow'];+const rightActions: ActionKeys[] = ['voiceDictation', 'voiceMessage', 'contextWindow'];/*** MainChatInput