Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复自定义实时语音服务路由与凭证 (#470)
DavidShenXDd4357e19021d
diff --git a/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts b/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.tsindex ab681c55b8..69590bc841 100644--- a/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts+++ b/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts@@ -40,4 +40,19 @@ describe('safe storage Codex restart invariants', () => {expect(prepare).toBeLessThan(unlink);expect(unlink).toBeLessThan(finalize);});++ it('gates generic store, read, and remove through the Renderer key allowlist', () => {+ const src = source();+ for (const [channel, nextChannel] of [+ ["'safe-storage-store'", "'safe-storage-read'"],+ ["'safe-storage-read'", "'safe-storage-remove'"],+ ["'safe-storage-remove'", '// ── Auth IPC handlers'],+ ] as const) {+ const start = src.indexOf(channel);+ const end = src.indexOf(nextChannel, start + channel.length);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ expect(src.slice(start, end)).toContain('isValidRendererKey(key)');+ }+ });});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex ad8f9de7f5..8a388ce4a1 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -412,6 +412,7 @@ import {writeSilentEncryptedRetryEnabled,} from './maker-host/silent-encrypted-retry-store.js';import { resolveOwnerScopedSecretStorageKey } from './secrets/providerSecretStore.js';+import { isRendererAccessibleSafeStorageKey } from '../shared/providerSecrets.js';import {readCompactionPct,readCompactionState,@@ -3106,6 +3107,8 @@ const registerIpcHandlers = () => {// safeStorage IPC handlersconst isValidKey = (key: string): boolean => /^[a-zA-Z0-9_-]+$/.test(key);+ const isValidRendererKey = (key: string): boolean =>+ isValidKey(key) && isRendererAccessibleSafeStorageKey(key);const resolveSafeStorageFilepath = (key: string): string | null => {const scopedKey = resolveOwnerScopedSecretStorageKey(key);return scopedKey@@ -3167,9 +3170,10 @@ const registerIpcHandlers = () => {ipcMain.handle('safe-storage-store',- async (_event: Electron.IpcMainInvokeEvent, key: string, value: string): Promise<boolean> => {+ async (event: Electron.IpcMainInvokeEvent, key: string, value: string): Promise<boolean> => {try {- if (!isValidKey(key)) return false;+ assertTrustedAppRendererEvent(event);+ if (!isValidRendererKey(key)) return false;const filepath = resolveSafeStorageFilepath(key);if (!filepath) return false;if (!safeStorage.isEncryptionAvailable()) return false;@@ -3215,9 +3219,10 @@ const registerIpcHandlers = () => {ipcMain.handle('safe-storage-read',- async (_event: Electron.IpcMainInvokeEvent, key: string): Promise<string | null> => {+ async (event: Electron.IpcMainInvokeEvent, key: string): Promise<string | null> => {try {- if (!isValidKey(key)) return null;+ assertTrustedAppRendererEvent(event);+ if (!isValidRendererKey(key)) return null;const filepath = resolveSafeStorageFilepath(key);if (!filepath) return null;if (!safeStorage.isEncryptionAvailable()) return null;@@ -3235,11 +3240,12 @@ const registerIpcHandlers = () => {ipcMain.handle('safe-storage-remove',async (- _event: Electron.IpcMainInvokeEvent,+ event: Electron.IpcMainInvokeEvent,key: string,): Promise<{ success: boolean; error?: string }> => {try {- if (!isValidKey(key)) {+ assertTrustedAppRendererEvent(event);+ if (!isValidRendererKey(key)) {return { success: false, error: 'invalid key' };}const filepath = resolveSafeStorageFilepath(key);diff --git a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.tsindex 396969182e..63e086267e 100644--- a/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts+++ b/apps/desktop/src/main/secrets/__tests__/providerSecretStore.test.ts@@ -47,6 +47,7 @@ import {ghostSecretHintStorageKey,deriveGhostSecretTail,GHOST_SECRET_TAIL_MIN_VALUE_CHARS,+ isRendererAccessibleSafeStorageKey,PROVIDER_SECRET_IDS,} from '../../../shared/providerSecrets';@@ -75,14 +76,22 @@ describe('providerSecrets registry', () => {expect(providerSecretStorageKey('mivo')).toBe('mivo_api_key');expect(providerSecretStorageKey('brave')).toBe('brave_search_api_key');expect(providerSecretStorageKey('tavily')).toBe('tavily_api_key');+ expect(providerSecretStorageKey('voice-asr')).toBe('voice_input_asr_api_key');});it('lists all registered provider ids', () => {expect(PROVIDER_SECRET_IDS).toEqual(- expect.arrayContaining(['xd', 'mivo', 'brave', 'tavily']),+ expect.arrayContaining(['xd', 'mivo', 'brave', 'tavily', 'voice-asr']),);});+ it('keeps the voice ASR key behind its dedicated main-only IPC boundary', () => {+ expect(isRendererAccessibleSafeStorageKey(providerSecretStorageKey('voice-asr'))).toBe(false);+ expect(isRendererAccessibleSafeStorageKey('VOICE_INPUT_ASR_API_KEY')).toBe(false);+ expect(isRendererAccessibleSafeStorageKey(providerSecretStorageKey('xd'))).toBe(true);+ expect(isRendererAccessibleSafeStorageKey(customMcpSecretStorageKey('example'))).toBe(true);+ });+it('动态键名构造前校验片段字符集,路径逃逸类 id 直接抛错', () => {expect(providerOAuthStorageKey('acme-1')).toBe('provider_oauth_acme-1');expect(customProviderSecretStorageKey('my_or', 'claude-code')).toBe('provider_key_my_or_claude-code');diff --git a/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts b/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.tsindex 8a68bc6d9a..3d8e7e44a1 100644--- a/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts+++ b/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts@@ -62,6 +62,8 @@ export class ElevenLabsScribeProvider implements AsrProvider {private stableResolvers: Array<(text: string | undefined) => void> = [];private recoveryPromise?: Promise<void>;private stopRequested = false;+ private startResolve?: () => void;+ private startReject?: (error: Error) => void;constructor(options: ElevenLabsScribeProviderOptions) {this.apiKey = options.apiKey;@@ -121,6 +123,8 @@ export class ElevenLabsScribeProvider implements AsrProvider {socket.off('error', onError);socket.off('close', onClose);socket.off('unexpected-response', onUnexpectedResponse);+ this.startResolve = undefined;+ this.startReject = undefined;};const fail = (error: Error, terminateSocket: boolean): void => {if (settled) return;@@ -146,16 +150,9 @@ export class ElevenLabsScribeProvider implements AsrProvider {}, this.connectTimeoutMs);const onOpen = (): void => {if (settled) return;- settled = true;- cleanup();if (this.stopRequested) {- socket.close();- reject(new Error('ElevenLabs Scribe connection opened after stop.'));- return;+ fail(new Error('ElevenLabs Scribe connection opened after stop.'), true);}- this.connected = true;- this.callback({ type: 'connected', at: Date.now() });- resolve();};const onError = (error: Error): void => {fail(error, false);@@ -169,6 +166,15 @@ export class ElevenLabsScribeProvider implements AsrProvider {const statusMessage = response.statusMessage ? ` ${response.statusMessage}` : '';fail(new Error(`ElevenLabs Scribe handshake failed: HTTP ${statusCode}${statusMessage}`), true);};+ this.startResolve = () => {+ if (settled) return;+ settled = true;+ cleanup();+ resolve();+ };+ this.startReject = (error) => {+ fail(error, true);+ };socket.once('open', onOpen);socket.once('error', onError);socket.once('close', onClose);@@ -238,6 +244,7 @@ export class ElevenLabsScribeProvider implements AsrProvider {async stop(): Promise<void> {this.stopRequested = true;this.connected = false;+ this.startReject?.(new Error('ElevenLabs Scribe stopped before the session was ready.'));this.recoveryPartialPrefix = '';this.clearUncommittedAudio();this.resolveStableWaiters(undefined);@@ -354,6 +361,7 @@ export class ElevenLabsScribeProvider implements AsrProvider {this.connected = true;this.callback({ type: 'connected', at: Date.now() });}+ this.startResolve?.();break;case 'partial_transcript':if (typeof message.text === 'string') {@@ -380,11 +388,15 @@ export class ElevenLabsScribeProvider implements AsrProvider {case 'input_error':case 'chunk_size_exceeded':case 'transcriber_error':- this.callback({- type: 'error',- message: typeof message.error === 'string' ? message.error : String(message.message_type),- at: Date.now(),- });+ {+ const eventMessage = typeof message.error === 'string' ? message.error : String(message.message_type);+ this.callback({+ type: 'error',+ message: eventMessage,+ at: Date.now(),+ });+ this.startReject?.(new Error(eventMessage));+ }this.resolveStableWaiters(undefined);break;}@@ -458,6 +470,8 @@ export class ElevenLabsScribeProvider implements AsrProvider {this.recoveryPartialPrefix = '';this.lastStable = undefined;this.sentAudioMs = 0;+ this.startResolve = undefined;+ this.startReject = undefined;this.clearUncommittedAudio();this.resolveStableWaiters(undefined);}diff --git a/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts b/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.tsindex 1ec3cbca2d..89cf153c59 100644--- a/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts+++ b/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts@@ -18,12 +18,16 @@ export type RealtimeAsrWebSocketProviderOptions = {model?: string;realtimeUrl?: string;extraHeaders?: Record<string, string>;+ /** Non-secret identity used to prevent warm-socket reuse across credentials. */+ credentialCacheKey?: string;pcmSampleRate?: number;protocolProfile?: VoiceInputRealtimeProtocolProfile;providerKind?: string;connectTimeoutMs?: number;missingCredentialMessage?: string;errorFallbackMessage?: string;+ /** Replace upstream application error text with errorFallbackMessage. */+ redactUpstreamErrors?: boolean;};const OPENAI_REALTIME_TRANSCRIPTION_URL = 'wss://api.openai.com/v1/realtime?intent=transcription';@@ -69,6 +73,7 @@ const log = createLogger('voice-input:realtime-asr-websocket');type WarmRealtimeSession = {socket: WebSocket;connectionKey: string;+ credentialCacheKey: string;model: string;languageCode: string | undefined;pcmSampleRate: number;@@ -93,6 +98,7 @@ type TakenWarmRealtimeSession = {};let warmRealtimeSession: WarmRealtimeSession | null = null;+let warmRealtimeSessionGeneration = 0;// Same-key in-flight dedup: a second prewarm for the SAME (model, language)// returned the same in-flight promise immediately. Kept for callers that// want fast same-config short-circuit before the chain serializer below.@@ -105,6 +111,13 @@ const inFlightWarmPrewarms = new Map<string, Promise<void>>();// matching warm session, the later link returns without creating another.let warmPrewarmChain: Promise<void> = Promise.resolve();+export function invalidatePrewarmedRealtimeAsrWebSocketSession(): void {+ warmRealtimeSessionGeneration += 1;+ inFlightWarmPrewarms.clear();+ warmRealtimeSession?.close();+ warmRealtimeSession = null;+}+type RealtimeConnectionConfig = {realtimeUrl: string;extraHeaders: Record<string, string>;@@ -150,17 +163,19 @@ function realtimeHeaders(accessToken: string, extraHeaders: Record<string, strinfunction warmConfigKey(connectionKey: string,+ credentialCacheKey: string,model: string,languageCode: string | undefined,pcmSampleRate: number,protocolProfile: VoiceInputRealtimeProtocolProfile,): string {- return `${connectionKey}::${model}::${languageCode ?? ''}::pcm-${pcmSampleRate}::${protocolProfile}`;+ return `${connectionKey}::credential-${credentialCacheKey}::${model}::${languageCode ?? ''}::pcm-${pcmSampleRate}::${protocolProfile}`;}function isExistingWarmMatch(existing: WarmRealtimeSession | null,connectionKey: string,+ credentialCacheKey: string,model: string,languageCode: string | undefined,pcmSampleRate: number,@@ -168,6 +183,7 @@ function isExistingWarmMatch(): boolean {if (!existing) return false;if (existing.connectionKey !== connectionKey) return false;+ if (existing.credentialCacheKey !== credentialCacheKey) return false;if (existing.model !== model) return false;if (existing.languageCode !== languageCode) return false;if (existing.pcmSampleRate !== pcmSampleRate) return false;@@ -178,18 +194,28 @@ function isExistingWarmMatch(}export function prewarmRealtimeAsrWebSocketSession(options: RealtimeAsrWebSocketProviderOptions): Promise<void> {+ const generation = warmRealtimeSessionGeneration;const model = options.model ?? OPENAI_REALTIME_WHISPER_MODEL;const sourceLanguage = options.sourceLanguage ?? 'auto';const languageCode = openAiLanguageCode(sourceLanguage);const pcmSampleRate = options.pcmSampleRate ?? DEFAULT_REALTIME_PCM_SAMPLE_RATE;const protocolProfile = options.protocolProfile ?? 'openai-transcription-manual';+ const credentialCacheKey = options.credentialCacheKey ?? '';const connection = resolveRealtimeConnectionConfig(options);- const configKey = warmConfigKey(connection.connectionKey, model, languageCode, pcmSampleRate, protocolProfile);+ const configKey = warmConfigKey(+ connection.connectionKey,+ credentialCacheKey,+ model,+ languageCode,+ pcmSampleRate,+ protocolProfile,+ );// Fast-path 1: an existing warm session already matches.if (isExistingWarmMatch(warmRealtimeSession,connection.connectionKey,+ credentialCacheKey,model,languageCode,pcmSampleRate,@@ -208,11 +234,13 @@ export function prewarmRealtimeAsrWebSocketSession(options: RealtimeAsrWebSocket// Queue on the global chain so any different-key prewarm finishes (and// potentially supersedes our need) before we create another socket.const next = warmPrewarmChain.then(async () => {+ if (generation !== warmRealtimeSessionGeneration) return;// Re-check after the wait — a prior queued prewarm may have created// exactly the warm session we wanted, in which case we're done.if (isExistingWarmMatch(warmRealtimeSession,connection.connectionKey,+ credentialCacheKey,model,languageCode,pcmSampleRate,@@ -224,7 +252,17 @@ export function prewarmRealtimeAsrWebSocketSession(options: RealtimeAsrWebSocket// ours. createWarmRealtimeSession returns a promise that settles when// session.updated arrives; awaiting here keeps the chain serialized.warmRealtimeSession?.close();- await createWarmRealtimeSession(options, connection, model, sourceLanguage, languageCode, pcmSampleRate, protocolProfile);+ await createWarmRealtimeSession(+ options,+ connection,+ generation,+ credentialCacheKey,+ model,+ sourceLanguage,+ languageCode,+ pcmSampleRate,+ protocolProfile,+ );});warmPrewarmChain = next.catch(() => undefined);inFlightWarmPrewarms.set(configKey, next);@@ -238,6 +276,7 @@ export function prewarmRealtimeAsrWebSocketSession(options: RealtimeAsrWebSocketfunction takeWarmRealtimeSession(connectionKey: string,+ credentialCacheKey: string,model: string,sourceLanguage: string,pcmSampleRate: number,@@ -250,6 +289,10 @@ function takeWarmRealtimeSession(warm.close();return null;}+ if (warm.credentialCacheKey !== credentialCacheKey) {+ warm.close();+ return null;+ }if (warm.model !== model) {warm.close();return null;@@ -275,6 +318,8 @@ function takeWarmRealtimeSession(function createWarmRealtimeSession(options: RealtimeAsrWebSocketProviderOptions,connection: RealtimeConnectionConfig,+ generation: number,+ credentialCacheKey: string,model: string,sourceLanguage: string,languageCode: string | undefined,@@ -289,6 +334,7 @@ function createWarmRealtimeSession(const readyPromise: Promise<void> = (async (): Promise<void> => {const accessToken = await options.accessTokenProvider();if (!accessToken) return;+ if (generation !== warmRealtimeSessionGeneration) return;await new Promise<void>((resolve, reject) => {const socket = new WebSocket(connection.realtimeUrl, {@@ -321,9 +367,23 @@ function createWarmRealtimeSession(cleanup();};const close = (): void => {- cleanup();+ if (!settled) {+ settled = true;+ if (warmRealtimeSession?.socket === socket) warmRealtimeSession = null;+ clearKeepAlive();+ clearTimeout(timer);+ socket.off('open', onOpen);+ socket.off('message', onMessage);+ socket.off('pong', onPong);+ reject(new Error('prewarm realtime session invalidated'));+ } else {+ clearKeepAlive();+ clearTimeout(timer);+ }if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {socket.close();+ } else {+ cleanup();}};const rejectOnce = (error: Error): void => {@@ -331,6 +391,12 @@ function createWarmRealtimeSession(settled = true;if (warmRealtimeSession?.socket === socket) warmRealtimeSession = null;cleanup();+ // A readiness failure can happen after the upgrade succeeds. Do not+ // leave that unauthenticated/idle socket alive after its promise has+ // rejected; it can otherwise linger until the upstream closes it.+ if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {+ socket.terminate();+ }reject(error);};const resolveOnce = (): void => {@@ -392,6 +458,7 @@ function createWarmRealtimeSession(rejectOnce(new Error(realtimeErrorMessage(event,options.errorFallbackMessage ?? 'OpenAI realtime transcription failed.',+ options.redactUpstreamErrors,)));}};@@ -410,9 +477,20 @@ function createWarmRealtimeSession(rejectOnce(error);};- warmRealtimeSession = {+ if (generation !== warmRealtimeSessionGeneration) {+ settled = true;+ cleanup();+ socket.on('error', () => undefined);+ if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {+ socket.close();+ }+ resolve();+ return;+ }+ const nextWarmSession: WarmRealtimeSession = {socket,connectionKey: connection.connectionKey,+ credentialCacheKey,model,languageCode,pcmSampleRate,@@ -428,6 +506,11 @@ function createWarmRealtimeSession(socket.on('pong', onPong);socket.on('close', onClose);socket.on('error', onError);+ if (generation !== warmRealtimeSessionGeneration) {+ close();+ return;+ }+ warmRealtimeSession = nextWarmSession;});})().catch((error) => {log.debug('prewarm realtime session unavailable', {@@ -528,12 +611,14 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {private activeRealtimeUrl: string;private readonly extraHeaders: Record<string, string>;private readonly connectionKey: string;+ private readonly credentialCacheKey: string;private readonly pcmSampleRate: number;private readonly protocolProfile: VoiceInputRealtimeProtocolProfile;private readonly providerKind: string;private readonly connectTimeoutMs: number;private readonly missingCredentialMessage: string;private readonly errorFallbackMessage: string;+ private readonly redactUpstreamErrors: boolean;private socket?: WebSocket;private callback: (event: AsrEvent) => void = () => {};private connected = false;@@ -602,10 +687,12 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {this.activeRealtimeUrl = connection.realtimeUrl;this.extraHeaders = connection.extraHeaders;this.connectionKey = connection.connectionKey;+ this.credentialCacheKey = options.credentialCacheKey ?? '';this.providerKind = options.providerKind ?? 'openai-realtime-whisper';this.missingCredentialMessage =options.missingCredentialMessage ?? 'Codex ChatGPT login is required for realtime voice input.';this.errorFallbackMessage = options.errorFallbackMessage ?? 'OpenAI realtime transcription failed.';+ this.redactUpstreamErrors = options.redactUpstreamErrors === true;this.recorder = isVoiceInputRecordingEnabled()? new VoiceInputSessionRecorder(makeRecorderSessionId()): null;@@ -615,6 +702,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {model: this.model,sourceLanguage: this.sourceLanguage,startedAtIso: new Date().toISOString(),+ redactSensitiveWs: this.redactUpstreamErrors,});log.info('voice input session recording enabled', {sessionId: this.recorder.sessionId,@@ -640,6 +728,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {const warm = dynamicConnection ? null : takeWarmRealtimeSession(this.connectionKey,+ this.credentialCacheKey,this.model,this.sourceLanguage,this.pcmSampleRate,@@ -781,6 +870,11 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {const onUnexpectedResponse = (_request: ClientRequest, response: IncomingMessage): void => {response.resume();const statusCode = response.statusCode ?? 'unknown';+ if (this.redactUpstreamErrors) {+ const statusSuffix = typeof statusCode === 'number' ? ` (HTTP ${statusCode})` : '';+ fail(new Error(`${this.errorFallbackMessage}${statusSuffix}`), true);+ return;+ }const statusMessage = response.statusMessage ? ` ${response.statusMessage}` : '';// Include the dialed host/path + gateway trace id: a handshake 404// against a gateway missing the ASR passthrough route is otherwise@@ -798,7 +892,7 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {resolve();};this.startReject = (error) => {- fail(error, false);+ fail(error, true);};socket.once('error', onError);socket.once('unexpected-response', onUnexpectedResponse);@@ -1088,22 +1182,29 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {break;case 'conversation.item.input_audio_transcription.failed':{- const message = realtimeErrorMessage(event, this.errorFallbackMessage);+ const message = realtimeErrorMessage(+ event,+ this.errorFallbackMessage,+ this.redactUpstreamErrors,+ );this.callback({ type: 'error', message, at: Date.now() });this.resolveFlushWaiters();}break;case 'error':{- const message = realtimeErrorMessage(event, this.errorFallbackMessage);- if (this.isNonFatalServerVadFinishError(message)) {+ const upstreamMessage = realtimeErrorMessage(event, this.errorFallbackMessage);+ if (this.isNonFatalServerVadFinishError(upstreamMessage)) {log.debug('ignore non-fatal server-vad finish error', {- message,+ message: this.redactUpstreamErrors ? this.errorFallbackMessage : upstreamMessage,aggregateChars: this.aggregateTranscript().length,});this.resolveFlushWaiters();break;}+ const message = this.redactUpstreamErrors+ ? this.errorFallbackMessage+ : upstreamMessage;if (!this.sessionReady && this.startReject) {this.startReject(new Error(message));} else {@@ -1449,7 +1550,12 @@ function clampPcm16(value: number): number {return value;}-export function realtimeErrorMessage(event: Record<string, unknown>, fallbackMessage: string): string {+export function realtimeErrorMessage(+ event: Record<string, unknown>,+ fallbackMessage: string,+ redactUpstreamErrors = false,+): string {+ if (redactUpstreamErrors) return fallbackMessage;const error = event.error;if (isRecord(error) && typeof error.message === 'string') return error.message;return fallbackMessage;diff --git a/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts b/apps/desktop/src/main/voice-input/VoiceInputModelSelection.tsindex 9eccef367b..c4db0d4468 100644--- a/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts+++ b/apps/desktop/src/main/voice-input/VoiceInputModelSelection.ts@@ -15,6 +15,16 @@ import {resolveVoiceInputRefinerProviderKindAlias,type VoiceInputRefinerProviderKind,} from '../../shared/voiceInputRefinerProfiles.js';+import {+ validateVoiceInputCustomAsrConfig,+ type VoiceInputCustomAsrConfig,+} from '../../shared/voiceInputCustomAsr.js';++export {+ validateVoiceInputCustomAsrConfig,+ type VoiceInputCustomAsrConfig,+ type VoiceInputCustomAsrProtocol,+} from '../../shared/voiceInputCustomAsr.js';const EMPTY_REFINER_DEFAULT_CHAIN: readonly VoiceInputRefinerProviderKind[] = [];@@ -47,6 +57,17 @@ export function effectiveVoiceInputServiceMode(return canUseCindyAccountServices ? configuredMode : 'byok';}+export function voiceInputAsrChainForServiceMode(+ selection: Pick<+ VoiceInputModelSelectionValues,+ 'serviceMode' | 'asrProvider' | 'asrProviderChain' | 'asrProviderChainSource'+ >,+): VoiceInputProviderKind[] {+ return selection.serviceMode === 'byok' && selection.asrProviderChainSource === 'default'+ ? [selection.asrProvider]+ : [...selection.asrProviderChain];+}+export type VoiceInputModelSelectionValues = {serviceMode: VoiceInputServiceMode;/** True when serviceMode came from an explicit file/env override (vs the product default). */@@ -61,6 +82,9 @@ export type VoiceInputModelSelectionValues = {* comma separated) when present, otherwise from the built-in default chain.*/asrProviderChain: VoiceInputProviderKind[];+ asrProviderChainSource: VoiceInputProviderChainSource;+ /** User-owned realtime ASR transport metadata. The API key is never stored here. */+ customAsr?: VoiceInputCustomAsrConfig;/** Effective refiner fallback chain; same resolution rules as asrProviderChain. */refinerProviderChain: VoiceInputRefinerProviderKind[];refinerProviderChainSource: VoiceInputProviderChainSource;@@ -73,6 +97,7 @@ export type VoiceInputModelSelection = VoiceInputModelSelectionValues & {export type VoiceInputModelSelectionPatch = {serviceMode?: VoiceInputServiceMode | null;asrProvider?: VoiceInputProviderKind | null;+ customAsr?: VoiceInputCustomAsrConfig | null;refinerProvider?: VoiceInputRefinerProviderKind | null;refinerModel?: string | null;/**@@ -84,7 +109,7 @@ export type VoiceInputModelSelectionPatch = {};export type VoiceInputModelSelectionWarning = {- field: 'serviceMode' | 'asrProvider' | 'refinerProvider' | 'asrProviderChain' | 'refinerProviderChain';+ field: 'serviceMode' | 'asrProvider' | 'refinerProvider' | 'asrProviderChain' | 'refinerProviderChain' | 'customAsr';value: string;fallback: string;};@@ -104,6 +129,7 @@ type RawVoiceInputModelSelectionFile = {refinerModel?: unknown;asrProviderChain?: unknown;refinerProviderChain?: unknown;+ customAsr?: unknown;};let cachedConfig: VoiceInputModelSelection | null = null;@@ -144,6 +170,7 @@ export function resolveVoiceInputModelSelectionValues(defaultChain: DEFAULT_VOICE_INPUT_ASR_PROVIDER_CHAIN,resolveAlias: resolveVoiceInputProviderKindAlias,});+ const customAsr = resolveVoiceInputCustomAsrConfig(raw?.customAsr);const refinerChain = resolveProviderChain({field: 'refinerProviderChain',rawEntries: readConfigStringList(raw, 'utilityModelProviderChain')@@ -166,6 +193,8 @@ export function resolveVoiceInputModelSelectionValues(refinerProvider: refinerProvider.value,refinerModel,asrProviderChain: asrChain.value,+ asrProviderChainSource: asrChain.source,+ ...(customAsr.value ? { customAsr: customAsr.value } : {}),refinerProviderChain: refinerChain.value,refinerProviderChainSource: refinerChain.source,},@@ -174,6 +203,7 @@ export function resolveVoiceInputModelSelectionValues(...(asrProvider.warning ? [asrProvider.warning] : []),...(refinerProvider.warning ? [refinerProvider.warning] : []),...asrChain.warnings,+ ...(customAsr.warning ? [customAsr.warning] : []),...refinerChain.warnings,],};@@ -254,6 +284,7 @@ export function setVoiceInputModelSelection(patch: VoiceInputModelSelectionPatchconst next: RawVoiceInputModelSelectionFile = { ...current };if ('serviceMode' in patch) next.serviceMode = patch.serviceMode ?? '';if ('asrProvider' in patch) next.asrProvider = patch.asrProvider ?? '';+ if ('customAsr' in patch) next.customAsr = patch.customAsr ?? undefined;if ('refinerProvider' in patch) next.refinerProvider = patch.refinerProvider ?? '';if ('refinerModel' in patch) next.refinerModel = patch.refinerModel?.trim() ?? '';if ('refinerProviderChain' in patch) next.refinerProviderChain = patch.refinerProviderChain ?? [];@@ -262,6 +293,7 @@ export function setVoiceInputModelSelection(patch: VoiceInputModelSelectionPatchpath: configPath,serviceMode: next.serviceMode,asrProvider: next.asrProvider,+ customAsrConfigured: Boolean(next.customAsr),refinerProvider: next.refinerProvider,refinerModel: next.refinerModel,refinerProviderChain: next.refinerProviderChain,@@ -276,6 +308,8 @@ export function voiceInputModelSelectionSignature(config: VoiceInputModelSelectirefinerProvider: config.refinerProvider,refinerModel: config.refinerModel ?? '',asrProviderChain: config.asrProviderChain,+ asrProviderChainSource: config.asrProviderChainSource,+ customAsr: config.customAsr ?? null,refinerProviderChain: config.refinerProviderChain,refinerProviderChainSource: config.refinerProviderChainSource,});@@ -418,6 +452,21 @@ function defaultRuntimeConfigFile(): RawVoiceInputModelSelectionFile {};}+function resolveVoiceInputCustomAsrConfig(+ value: unknown,+): { value?: VoiceInputCustomAsrConfig; warning?: VoiceInputModelSelectionWarning } {+ if (value === undefined || value === null) return {};+ const validated = validateVoiceInputCustomAsrConfig(value);+ if (validated.ok) return { value: validated.value };+ return {+ warning: {+ field: 'customAsr',+ value: '<invalid>',+ fallback: '<unset>',+ },+ };+}+function readConfigString(raw: RawVoiceInputModelSelectionFile | null | undefined, key: keyof RawVoiceInputModelSelectionFile): string | undefined {if (!raw || !(key in raw)) return undefined;const value = raw[key];diff --git a/apps/desktop/src/main/voice-input/VoiceInputSessionRecorder.ts b/apps/desktop/src/main/voice-input/VoiceInputSessionRecorder.tsindex 669983c658..3ac8e4c89b 100644--- a/apps/desktop/src/main/voice-input/VoiceInputSessionRecorder.ts+++ b/apps/desktop/src/main/voice-input/VoiceInputSessionRecorder.ts@@ -30,6 +30,7 @@ export type RecorderInitMeta = {sourceLanguage?: string;inputSampleRate?: number;startedAtIso: string;+ redactSensitiveWs?: boolean;};export type RecorderWsDirection = 'outbound' | 'inbound';@@ -110,7 +111,7 @@ export class VoiceInputSessionRecorder {const entry = {t: Date.now(),dir: direction,- ...summarizeWsMessage(message),+ ...summarizeWsMessage(message, this.meta?.redactSensitiveWs === true),};try {this.wsStream.write(`${JSON.stringify(entry)}\n`);@@ -201,23 +202,29 @@ function closeStream(stream: fs.WriteStream): Promise<void> {// Strip noisy/large fields from WS messages before logging. Audio appends// can be hundreds of KB of base64 — useless to keep verbatim, but the type// and cadence are exactly what we need for stall diagnosis.-function summarizeWsMessage(message: unknown): Record<string, unknown> {+export function summarizeWsMessage(message: unknown, redactSensitive = false): Record<string, unknown> {if (typeof message === 'string') {let parsed: unknown;try {parsed = JSON.parse(message);} catch {- return { raw: truncateString(message, WS_FIELD_INLINE_MAX_BYTES) };+ return redactSensitive+ ? { redacted: true }+ : { raw: truncateString(message, WS_FIELD_INLINE_MAX_BYTES) };}- return summarizeWsMessage(parsed);+ return summarizeWsMessage(parsed, redactSensitive);}if (Buffer.isBuffer(message)) {return { binary: true, bytes: message.length };}if (!message || typeof message !== 'object') {- return { value: message };+ return redactSensitive ? { redacted: true } : { value: message };}const obj = message as Record<string, unknown>;+ if (redactSensitive) {+ const type = typeof obj.type === 'string' ? obj.type : undefined;+ return type ? { redacted: true, type } : { redacted: true };+ }const summary: Record<string, unknown> = {};for (const [key, value] of Object.entries(obj)) {if (key === 'audio' && typeof value === 'string') {diff --git a/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts b/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.tsindex be92c5325a..e19cfbd44c 100644--- a/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts+++ b/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts@@ -101,6 +101,8 @@ export class VolcengineSaucAsrProvider implements AsrProvider {private pongTimeoutTimer?: ReturnType<typeof setTimeout>;private recoveryPromise?: Promise<void>;private stopRequested = false;+ private startResolve?: () => void;+ private startReject?: (error: Error) => void;constructor(options: VolcengineSaucAsrProviderOptions) {this.proxyApiKey = options.proxyApiKey;@@ -151,6 +153,8 @@ export class VolcengineSaucAsrProvider implements AsrProvider {socket.off('error', onError);socket.off('close', onClose);socket.off('unexpected-response', onUnexpectedResponse);+ this.startResolve = undefined;+ this.startReject = undefined;};const fail = (error: Error, terminateSocket: boolean): void => {if (settled) return;@@ -178,19 +182,12 @@ export class VolcengineSaucAsrProvider implements AsrProvider {}, this.connectTimeoutMs);const onOpen = (): void => {if (settled) return;- settled = true;- cleanup();if (this.stopRequested) {- socket.close();- reject(new Error('Volcengine SAUC ASR connection opened after stop.'));+ fail(new Error('Volcengine SAUC ASR connection opened after stop.'), true);return;}- this.connected = true;- this.started = true;this.startKeepAlive();this.sendInitialRequest();- this.callback({ type: 'connected', at: Date.now() });- resolve();};const onError = (error: Error): void => {fail(error, false);@@ -211,6 +208,18 @@ export class VolcengineSaucAsrProvider implements AsrProvider {`Volcengine SAUC ASR handshake failed: HTTP ${statusCode}${statusMessage} (${target}${traceId ? `, ${traceId}` : ''})`,), true);};+ this.startResolve = () => {+ if (settled) return;+ settled = true;+ cleanup();+ this.connected = true;+ this.started = true;+ this.callback({ type: 'connected', at: Date.now() });+ resolve();+ };+ this.startReject = (error) => {+ fail(error, true);+ };socket.once('open', onOpen);socket.once('error', onError);socket.once('close', onClose);@@ -286,6 +295,7 @@ export class VolcengineSaucAsrProvider implements AsrProvider {this.stopRequested = true;this.started = false;this.connected = false;+ this.startReject?.(new Error('Volcengine SAUC stopped before the protocol was ready.'));this.pendingFinalAudioChunk = undefined;this.clearUnconfirmedAudio();this.sessionTranscriptPrefix = '';@@ -313,6 +323,8 @@ export class VolcengineSaucAsrProvider implements AsrProvider {this.clearUnconfirmedAudio();this.finalRequested = false;this.stableEmitted = false;+ this.startResolve = undefined;+ this.startReject = undefined;this.resolveFlushWaiters();}@@ -446,18 +458,21 @@ export class VolcengineSaucAsrProvider implements AsrProvider {const messageText = error instanceof Error ? error.message : String(error);log.warn('failed to decode volcengine sauc message', { error: messageText });this.callback({ type: 'error', message: this.errorFallbackMessage, at: Date.now() });+ this.startReject?.(new Error(this.errorFallbackMessage));this.resolveFlushWaiters();return;}if (message.messageType === MESSAGE_TYPE_SERVER_ERROR) {const errorMessage = extractErrorMessage(message.payload) ?? message.payloadText ?? this.errorFallbackMessage;this.callback({ type: 'error', message: errorMessage, at: Date.now() });+ this.startReject?.(new Error(errorMessage));this.resolveFlushWaiters();return;}if (message.messageType !== MESSAGE_TYPE_FULL_SERVER_RESPONSE && message.messageType !== MESSAGE_TYPE_SERVER_ACK) {return;}+ this.startResolve?.();const rawTranscript = extractTranscript(message.payload);const transcript = mergeRecoveredTranscript(this.sessionTranscriptPrefix, rawTranscript);diff --git a/apps/desktop/src/main/voice-input/__tests__/ElevenLabsScribeProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/ElevenLabsScribeProvider.test.tsindex b97656a4b2..26dd63d1d2 100644--- a/apps/desktop/src/main/voice-input/__tests__/ElevenLabsScribeProvider.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/ElevenLabsScribeProvider.test.ts@@ -38,6 +38,7 @@ describe('ElevenLabsScribeProvider helpers', () => {const index = sockets.length;sockets.push(socket);messageCounts[index] = 0;+ socket.send(JSON.stringify({ message_type: 'session_started' }));socket.on('message', () => {messageCounts[index] += 1;});@@ -95,6 +96,7 @@ describe('ElevenLabsScribeProvider helpers', () => {let provider: ElevenLabsScribeProvider | undefined;server.on('connection', (socket) => {sockets.push(socket);+ socket.send(JSON.stringify({ message_type: 'session_started' }));});try {@@ -191,6 +193,35 @@ describe('ElevenLabsScribeProvider helpers', () => {await new Promise<void>((resolve) => server.close(() => resolve()));}});++ it('waits for application authentication and rejects an auth error after the websocket opens', async () => {+ const server = new WebSocketServer({ port: 0 });+ let provider: ElevenLabsScribeProvider | undefined;+ server.on('connection', (socket) => {+ socket.send(JSON.stringify({ message_type: 'auth_error', error: 'Invalid API key' }));+ });++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ const events: Array<{ type: string }> = [];+ provider = new ElevenLabsScribeProvider({+ proxyApiKey: 'invalid-key',+ baseUrl: `http://127.0.0.1:${address.port}`,+ connectTimeoutMs: 2_000,+ });+ provider.onEvent((event) => events.push(event));++ await expect(provider.start()).rejects.toThrow('Invalid API key');+ expect(events.some((event) => event.type === 'connected')).toBe(false);+ expect(events.some((event) => event.type === 'error')).toBe(true);+ } finally {+ await provider?.stop();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });});function makePcmChunk(): ArrayBuffer {diff --git a/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.tsindex a0c827401d..78bd8ea687 100644--- a/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/RealtimeAsrWebSocketProvider.test.ts@@ -1,4 +1,4 @@-import { WebSocketServer, type WebSocket } from 'ws';+import { WebSocket, WebSocketServer } from 'ws';import { describe, expect, it, vi } from 'vitest';vi.mock('electron', () => ({@@ -10,6 +10,8 @@ vi.mock('electron', () => ({import {buildSessionUpdateMessage,+ invalidatePrewarmedRealtimeAsrWebSocketSession,+ prewarmRealtimeAsrWebSocketSession,realtimeErrorMessage,RealtimeAsrWebSocketProvider,resamplePcm16,@@ -152,6 +154,48 @@ describe('RealtimeAsrWebSocketProvider helpers', () => {.toBe('XD LiteLLM realtime transcription failed.');expect(realtimeErrorMessage({ type: 'error', error: { message: 'upstream rejected session' } }, 'fallback')).toBe('upstream rejected session');+ expect(realtimeErrorMessage(+ { type: 'error', error: { message: 'signed_url=https://example.test?token=secret' } },+ 'Custom realtime ASR failed.',+ true,+ )).toBe('Custom realtime ASR failed.');+ });++ it('redacts upstream application errors before custom startup rejects', async () => {+ const server = new WebSocketServer({ port: 0 });+ let provider: RealtimeAsrWebSocketProvider | undefined;+ server.on('connection', (socket) => {+ socket.on('message', (data) => {+ const message = JSON.parse(data.toString()) as { type?: string };+ if (message.type === 'session.update') {+ socket.send(JSON.stringify({+ type: 'error',+ error: { message: 'signed_url=https://example.test?token=secret' },+ }));+ }+ });+ });++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ provider = new RealtimeAsrWebSocketProvider({+ accessTokenProvider: async () => 'test-key',+ realtimeUrl: `ws://127.0.0.1:${address.port}/v1/realtime`,+ model: 'gpt-realtime-whisper',+ providerKind: 'custom-realtime-asr',+ errorFallbackMessage: 'Custom realtime ASR failed.',+ redactUpstreamErrors: true,+ });+ provider.onEvent(() => {});++ await expect(provider.start()).rejects.toThrow('Custom realtime ASR failed.');+ } finally {+ await provider?.stop();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }});it('builds provider-specific session update payloads', () => {@@ -266,6 +310,200 @@ describe('RealtimeAsrWebSocketProvider helpers', () => {}});+ it('redacts custom handshake details while preserving the HTTP status for classification', async () => {+ const server = new WebSocketServer({+ port: 0,+ verifyClient(_info, done) {+ done(false, 401, 'token=upstream-secret');+ },+ });+ let provider: RealtimeAsrWebSocketProvider | undefined;++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ provider = new RealtimeAsrWebSocketProvider({+ accessTokenProvider: async () => 'test-key',+ realtimeUrl: `ws://127.0.0.1:${address.port}/v1/realtime`,+ model: 'gpt-realtime-whisper',+ providerKind: 'custom-realtime-asr',+ errorFallbackMessage: 'Custom realtime ASR failed.',+ redactUpstreamErrors: true,+ });+ provider.onEvent(() => {});++ const error = await provider.start().then(+ () => null,+ (startError: unknown) => startError,+ );+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe('Custom realtime ASR failed. (HTTP 401)');+ expect((error as Error).message).not.toContain('upstream-secret');+ } finally {+ await provider?.stop();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });++ it('does not reuse a prewarmed socket across credential cache identities', async () => {+ const server = new WebSocketServer({ port: 0 });+ const authorizations: Array<string | undefined> = [];+ const sockets: WebSocket[] = [];+ let provider: RealtimeAsrWebSocketProvider | undefined;+ server.on('connection', (socket, request) => {+ sockets.push(socket);+ authorizations.push(request.headers.authorization);+ socket.on('message', (data) => {+ const message = JSON.parse(data.toString()) as { type?: string };+ if (message.type === 'session.update') {+ socket.send(JSON.stringify({ type: 'session.updated' }));+ }+ });+ });++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');+ const realtimeUrl = `ws://127.0.0.1:${address.port}/v1/realtime`;++ await prewarmRealtimeAsrWebSocketSession({+ accessTokenProvider: async () => 'old-key',+ credentialCacheKey: 'old-key-hash',+ realtimeUrl,+ model: 'gpt-realtime-whisper',+ });+ await waitFor(() => authorizations.length === 1);++ provider = new RealtimeAsrWebSocketProvider({+ accessTokenProvider: async () => 'new-key',+ credentialCacheKey: 'new-key-hash',+ realtimeUrl,+ model: 'gpt-realtime-whisper',+ });+ provider.onEvent(() => {});+ await provider.start();++ expect(authorizations).toEqual(['Bearer old-key', 'Bearer new-key']);+ } finally {+ await provider?.stop();+ for (const socket of sockets) socket.terminate();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });++ it('immediately closes a prewarmed socket when credentials are invalidated', async () => {+ const server = new WebSocketServer({ port: 0 });+ let serverSocket: WebSocket | undefined;+ server.on('connection', (socket) => {+ serverSocket = socket;+ socket.on('message', (data) => {+ const message = JSON.parse(data.toString()) as { type?: string };+ if (message.type === 'session.update') {+ socket.send(JSON.stringify({ type: 'session.updated' }));+ }+ });+ });++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ await prewarmRealtimeAsrWebSocketSession({+ accessTokenProvider: async () => 'old-key',+ credentialCacheKey: 'old-key-hash',+ realtimeUrl: `ws://127.0.0.1:${address.port}/v1/realtime`,+ model: 'gpt-realtime-whisper',+ });+ await waitFor(() => serverSocket?.readyState === WebSocket.OPEN);++ invalidatePrewarmedRealtimeAsrWebSocketSession();++ await waitFor(() => serverSocket?.readyState === WebSocket.CLOSED);+ } finally {+ serverSocket?.terminate();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });++ it('closes a prewarmed socket when readiness fails after upgrade', async () => {+ const server = new WebSocketServer({ port: 0 });+ let serverSocket: WebSocket | undefined;+ server.on('connection', (socket) => {+ serverSocket = socket;+ socket.on('message', (data) => {+ const message = JSON.parse(data.toString()) as { type?: string };+ if (message.type === 'session.update') {+ socket.send(JSON.stringify({+ type: 'error',+ error: { message: 'session rejected' },+ }));+ }+ });+ });++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ await prewarmRealtimeAsrWebSocketSession({+ accessTokenProvider: async () => 'test-key',+ credentialCacheKey: 'test-key-revision',+ realtimeUrl: `ws://127.0.0.1:${address.port}/v1/realtime`,+ model: 'gpt-realtime-whisper',+ errorFallbackMessage: 'Custom realtime ASR failed.',+ redactUpstreamErrors: true,+ });++ await waitFor(() => serverSocket?.readyState === WebSocket.CLOSED);+ } finally {+ serverSocket?.terminate();+ invalidatePrewarmedRealtimeAsrWebSocketSession();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });++ it('does not install a prewarm whose credential lookup finishes after invalidation', async () => {+ const server = new WebSocketServer({ port: 0 });+ let connectionCount = 0;+ server.on('connection', () => {+ connectionCount += 1;+ });+ let resolveAccessToken: ((value: string) => void) | undefined;+ const accessTokenProvider = vi.fn(() => new Promise<string>((resolve) => {+ resolveAccessToken = resolve;+ }));++ try {+ invalidatePrewarmedRealtimeAsrWebSocketSession();+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ const prewarm = prewarmRealtimeAsrWebSocketSession({+ accessTokenProvider,+ credentialCacheKey: 'old-credential-revision',+ realtimeUrl: `ws://127.0.0.1:${address.port}/v1/realtime`,+ model: 'gpt-realtime-whisper',+ });+ await waitFor(() => accessTokenProvider.mock.calls.length === 1);++ invalidatePrewarmedRealtimeAsrWebSocketSession();+ resolveAccessToken?.('old-key');+ await prewarm;+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(connectionCount).toBe(0);+ } finally {+ resolveAccessToken?.('old-key');+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+it('does not reopen a socket after stop while recovery is connecting', async () => {let handshakeCount = 0;const server = new WebSocketServer({diff --git a/apps/desktop/src/main/voice-input/__tests__/VoiceInputModelSelection.test.ts b/apps/desktop/src/main/voice-input/__tests__/VoiceInputModelSelection.test.tsindex 18752799cc..be0256881f 100644--- a/apps/desktop/src/main/voice-input/__tests__/VoiceInputModelSelection.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/VoiceInputModelSelection.test.ts@@ -10,8 +10,14 @@ vi.mock('electron', () => ({import {effectiveVoiceInputServiceMode,resolveVoiceInputModelSelectionValues,+ validateVoiceInputCustomAsrConfig,+ voiceInputAsrChainForServiceMode,voiceInputModelSelectionSignature,} from '../VoiceInputModelSelection.js';+import {+ canReuseVoiceInputCustomAsrCredential,+ resolveVoiceInputCustomAsrWebsocketUrl,+} from '../../../shared/voiceInputCustomAsr.js';describe('VoiceInputModelSelection', () => {describe('serviceMode', () => {@@ -92,6 +98,7 @@ describe('VoiceInputModelSelection', () => {'litellm-volcengine-sauc-asr','litellm-qwen3-asr-flash-realtime',],+ asrProviderChainSource: 'default',// BYOK refiner fallback is explicit opt-in: no configured chain means// the selected primary runs alone.refinerProviderChain: ['litellm-qwen3.6-plus'],@@ -143,6 +150,7 @@ describe('VoiceInputModelSelection', () => {'litellm-qwen3-asr-flash-realtime','litellm-gpt-realtime-whisper',],+ asrProviderChainSource: 'default',refinerProviderChain: ['codex-gpt-5.4-mini'],refinerProviderChainSource: 'default',});@@ -203,6 +211,111 @@ describe('VoiceInputModelSelection', () => {expect(result.values.refinerProviderChain).toEqual(['codex-gpt-5.4-mini']);});+ it('keeps managed ASR failover but makes BYOK fallback explicit opt-in', () => {+ const managed = resolveVoiceInputModelSelectionValues({ serviceMode: 'cindy' }).values;+ const byok = resolveVoiceInputModelSelectionValues({ serviceMode: 'byok' }).values;+ expect(voiceInputAsrChainForServiceMode(managed)).toEqual([+ 'litellm-volcengine-sauc-asr',+ 'litellm-qwen3-asr-flash-realtime',+ 'litellm-gpt-realtime-whisper',+ ]);+ expect(voiceInputAsrChainForServiceMode(byok)).toEqual([+ 'litellm-volcengine-sauc-asr',+ ]);++ const explicitByok = resolveVoiceInputModelSelectionValues({+ serviceMode: 'byok',+ asrProvider: 'custom-realtime-asr',+ asrProviderChain: ['litellm-qwen3-asr-flash-realtime'],+ }).values;+ expect(voiceInputAsrChainForServiceMode(explicitByok)).toEqual([+ 'custom-realtime-asr',+ 'litellm-qwen3-asr-flash-realtime',+ ]);+ });++ it('validates custom realtime ASR metadata without accepting insecure remote ws URLs', () => {+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'openai-realtime',+ websocketUrl: 'wss://asr.example.com/v1/realtime?intent=transcription',+ model: 'gpt-realtime-whisper',+ })).toEqual({+ ok: true,+ value: {+ protocol: 'openai-realtime',+ websocketUrl: 'wss://asr.example.com/v1/realtime?intent=transcription',+ model: 'gpt-realtime-whisper',+ },+ });+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'qwen-realtime',+ websocketUrl: 'ws://127.0.0.1:8080/asr',+ model: 'qwen3-asr-flash-realtime',+ }).ok).toBe(true);+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'openai-realtime',+ websocketUrl: 'ws://[::1]:8080/asr',+ model: 'gpt-realtime-whisper',+ }).ok).toBe(true);+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'openai-realtime',+ websocketUrl: 'ws://asr.example.com/realtime',+ model: 'gpt-realtime-whisper',+ })).toEqual({+ ok: false,+ error: 'customAsr.websocketUrl must use wss, or ws on a loopback host',+ });+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'openai-realtime',+ websocketUrl: 'wss://[email protected]/realtime',+ model: 'gpt-realtime-whisper',+ })).toEqual({+ ok: false,+ error: 'customAsr.websocketUrl must not contain credentials',+ });+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'openai-realtime',+ websocketUrl: 'wss://asr.example.com/realtime?api_key=secret',+ model: 'gpt-realtime-whisper',+ })).toEqual({+ ok: false,+ error: 'customAsr.websocketUrl contains unsupported query parameters; only documented routing parameters are allowed',+ });+ expect(validateVoiceInputCustomAsrConfig({+ protocol: 'openai-realtime',+ websocketUrl: 'wss://asr.example.com/realtime?token=secret',+ model: 'gpt-realtime-whisper',+ }).ok).toBe(false);+ });++ it('binds saved credentials to an endpoint origin and routes Qwen models in the URL', () => {+ expect(canReuseVoiceInputCustomAsrCredential(+ 'wss://asr.example.com/v1/realtime',+ 'wss://asr.example.com/v2/realtime?intent=transcription',+ )).toBe(true);+ expect(canReuseVoiceInputCustomAsrCredential(+ 'wss://asr.example.com/v1/realtime',+ 'wss://other.example.com/v1/realtime',+ )).toBe(false);+ expect(canReuseVoiceInputCustomAsrCredential(+ undefined,+ 'wss://asr.example.com/v1/realtime',+ )).toBe(false);++ expect(resolveVoiceInputCustomAsrWebsocketUrl({+ protocol: 'qwen-realtime',+ websocketUrl: 'wss://asr.example.com/realtime?tenant=one&model=stale',+ model: 'qwen3-asr-flash-realtime',+ })).toBe(+ 'wss://asr.example.com/realtime?tenant=one&model=qwen3-asr-flash-realtime',+ );+ expect(resolveVoiceInputCustomAsrWebsocketUrl({+ protocol: 'openai-realtime',+ websocketUrl: 'wss://asr.example.com/realtime?intent=transcription',+ model: 'gpt-realtime-whisper',+ })).toBe('wss://asr.example.com/realtime?intent=transcription');+ });+it('uses explicit chain config as the fallback tail, keeping the selected primary as head', () => {const result = resolveVoiceInputModelSelectionValues({asrProvider: 'litellm-qwen3-asr-flash-realtime',diff --git a/apps/desktop/src/main/voice-input/__tests__/VoiceInputSessionRecorder.test.ts b/apps/desktop/src/main/voice-input/__tests__/VoiceInputSessionRecorder.test.tsnew file mode 100644index 0000000000..43b05920ef--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/VoiceInputSessionRecorder.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('electron', () => ({+ app: {+ getPath: vi.fn(() => '/tmp/xdt-maker-test'),+ isPackaged: false,+ },+}));++import { summarizeWsMessage } from '../VoiceInputSessionRecorder.js';++describe('VoiceInputSessionRecorder message summaries', () => {+ it('redacts custom ASR payload fields while retaining the event type', () => {+ expect(summarizeWsMessage({+ type: 'error',+ error: {+ message: 'wss://asr.example.test?token=upstream-secret',+ },+ }, true)).toEqual({+ redacted: true,+ type: 'error',+ });+ });++ it('preserves the existing compact summary for non-custom sessions', () => {+ expect(summarizeWsMessage({+ type: 'session.updated',+ model: 'gpt-realtime-whisper',+ })).toEqual({+ type: 'session.updated',+ model: 'gpt-realtime-whisper',+ });+ });+});diff --git a/apps/desktop/src/main/voice-input/__tests__/VolcengineSaucAsrProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/VolcengineSaucAsrProvider.test.tsindex 192c335627..727b6edb12 100644--- a/apps/desktop/src/main/voice-input/__tests__/VolcengineSaucAsrProvider.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/VolcengineSaucAsrProvider.test.ts@@ -108,6 +108,7 @@ describe('VolcengineSaucAsrProvider protocol helpers', () => {const index = sockets.length;sockets.push(socket);messageCounts[index] = 0;+ socket.send(serverAckPacket());socket.on('message', () => {messageCounts[index] += 1;});@@ -164,6 +165,7 @@ describe('VolcengineSaucAsrProvider protocol helpers', () => {server.on('connection', (socket, request) => {sockets.push(socket);authorizations.push(request.headers.authorization);+ socket.send(serverAckPacket());});try {@@ -196,10 +198,54 @@ describe('VolcengineSaucAsrProvider protocol helpers', () => {}});+ it('waits for a provider protocol response before reporting connected', async () => {+ const server = new WebSocketServer({ port: 0 });+ const sockets: WebSocket[] = [];+ let provider: VolcengineSaucAsrProvider | undefined;+ server.on('connection', (socket) => {+ sockets.push(socket);+ });++ try {+ await waitFor(() => server.address() !== null);+ const address = server.address();+ if (!address || typeof address === 'string') throw new Error('Expected local test server address.');++ const events: string[] = [];+ provider = new VolcengineSaucAsrProvider({+ proxyApiKey: 'test-key',+ baseUrl: `http://127.0.0.1:${address.port}`,+ endpointPath: '/volcengine/api/v3/sauc/bigmodel_async',+ resourceId: 'volc.test',+ connectTimeoutMs: 1_000,+ });+ provider.onEvent((event) => events.push(event.type));++ const started = provider.start();+ await waitFor(() => sockets.length === 1);+ await expect(Promise.race([+ started.then(() => 'resolved'),+ sleep(30).then(() => 'pending'),+ ])).resolves.toBe('pending');+ expect(events).not.toContain('connected');++ sockets[0].send(serverAckPacket());+ await expect(started).resolves.toBeUndefined();+ expect(events).toContain('connected');+ } finally {+ await provider?.stop();+ for (const socket of sockets) socket.terminate();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ });+it('does not open a managed socket when stopped during session allocation', async () => {const server = new WebSocketServer({ port: 0 });const sockets: WebSocket[] = [];- server.on('connection', (socket) => sockets.push(socket));+ server.on('connection', (socket) => {+ sockets.push(socket);+ socket.send(serverAckPacket());+ });let allocationStarted = false;let releaseAllocation: ((value: { websocketUrl: string; authorizationToken: string }) => void) | undefined;const connectionProvider = vi.fn(() => new Promise<{ websocketUrl: string; authorizationToken: string }>((resolve) => {@@ -240,6 +286,7 @@ describe('VolcengineSaucAsrProvider protocol helpers', () => {let provider: VolcengineSaucAsrProvider | undefined;server.on('connection', (socket) => {sockets.push(socket);+ socket.send(serverAckPacket());});try {@@ -293,6 +340,7 @@ describe('VolcengineSaucAsrProvider protocol helpers', () => {let provider: VolcengineSaucAsrProvider | undefined;server.on('connection', (socket) => {sockets.push(socket);+ socket.send(serverAckPacket());});try {@@ -344,6 +392,7 @@ describe('VolcengineSaucAsrProvider protocol helpers', () => {let provider: VolcengineSaucAsrProvider | undefined;server.on('connection', (socket) => {sockets.push(socket);+ socket.send(serverAckPacket());});try {@@ -433,6 +482,10 @@ function serverTranscriptPacket(text: string, isFinal: boolean, flags = 0x0): Bu]);}+function serverAckPacket(): Buffer {+ return Buffer.from([0x11, 0xb0, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00]);+}+function makePcmChunk(): ArrayBuffer {const buffer = new ArrayBuffer(320);new Int16Array(buffer).fill(256);diff --git a/apps/desktop/src/main/voice-input/__tests__/voiceInputConnectionTest.test.ts b/apps/desktop/src/main/voice-input/__tests__/voiceInputConnectionTest.test.tsnew file mode 100644index 0000000000..8a9f1791a8--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/voiceInputConnectionTest.test.ts@@ -0,0 +1,165 @@+import type { AsrProvider } from '@cindy/voice-input-core';+import { describe, expect, it, vi } from 'vitest';++import {+ classifyVoiceInputConnectionTestError,+ runVoiceInputConnectionTest,+ runSerializedVoiceInputConnectionTest,+} from '../voiceInputConnectionTest.js';++function providerWith(options?: {+ start?: () => Promise<void>;+ stop?: () => Promise<void>;+ dispose?: () => Promise<void>;+}): AsrProvider {+ return {+ start: options?.start ?? vi.fn(async () => undefined),+ stop: options?.stop ?? vi.fn(async () => undefined),+ dispose: options?.dispose,+ } as unknown as AsrProvider;+}++describe('voice input connection test', () => {+ it.each([+ ['HTTP 401 Unauthorized', 'authentication-failed'],+ ['API key is required for LiteLLM realtime voice input.', 'credentials-missing'],+ ['Realtime ASR handshake failed: HTTP 404 Not Found', 'route-unavailable'],+ ['Realtime ASR connection timed out after 5000ms', 'timeout'],+ ['connect ECONNREFUSED 127.0.0.1:443', 'network'],+ ['upstream rejected the session', 'service-error'],+ ] as const)('classifies %s', (message, expected) => {+ expect(classifyVoiceInputConnectionTestError(new Error(message))).toBe(expected);+ });++ it('starts and closes the selected provider without sending audio', async () => {+ const start = vi.fn(async () => undefined);+ const stop = vi.fn(async () => undefined);+ const dispose = vi.fn(async () => undefined);+ const createProvider = vi.fn(async () => providerWith({ start, stop, dispose }));++ await expect(runVoiceInputConnectionTest({+ provider: 'litellm-qwen3-asr-flash-realtime',+ providerModel: 'qwen3-asr-flash-realtime',+ createProvider,+ })).resolves.toEqual({+ ok: true,+ provider: 'litellm-qwen3-asr-flash-realtime',+ providerModel: 'qwen3-asr-flash-realtime',+ });+ expect(createProvider).toHaveBeenCalledOnce();+ expect(start).toHaveBeenCalledOnce();+ expect(stop).toHaveBeenCalledOnce();+ expect(dispose).toHaveBeenCalledOnce();+ });++ it('returns a sanitized failure and still closes the provider', async () => {+ const stop = vi.fn(async () => undefined);+ const onError = vi.fn();+ const upstreamError = new Error('Realtime ASR handshake failed: HTTP 403 Forbidden, secret detail');++ await expect(runVoiceInputConnectionTest({+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ createProvider: async () => providerWith({+ start: async () => {+ throw upstreamError;+ },+ stop,+ }),+ onError,+ })).resolves.toEqual({+ ok: false,+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ reason: 'authentication-failed',+ });+ expect(onError).toHaveBeenCalledWith(upstreamError);+ expect(stop).toHaveBeenCalledOnce();+ });++ it('coalesces concurrent connection probes in Main', async () => {+ let releaseFirst!: () => void;+ const firstStarted = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const firstStart = vi.fn(async () => {+ await firstStarted;+ });+ const secondStart = vi.fn(async () => undefined);+ const firstCreate = vi.fn(async () => providerWith({ start: firstStart }));+ const secondCreate = vi.fn(async () => providerWith({ start: secondStart }));++ const first = runSerializedVoiceInputConnectionTest({+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ createProvider: firstCreate,+ });+ await vi.waitFor(() => expect(firstStart).toHaveBeenCalledOnce());+ const second = runSerializedVoiceInputConnectionTest({+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ createProvider: secondCreate,+ });++ await Promise.resolve();+ expect(secondCreate).not.toHaveBeenCalled();+ releaseFirst();+ await expect(first).resolves.toEqual({+ ok: true,+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ });+ await expect(second).resolves.toEqual({+ ok: true,+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ });+ expect(secondCreate).not.toHaveBeenCalled();+ });++ it('rejects a concurrent probe for a different active configuration', async () => {+ let releaseFirst!: () => void;+ const firstStarted = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const firstCreate = vi.fn(async () => {+ await firstStarted;+ return {+ start: vi.fn(async () => undefined),+ stop: vi.fn(async () => undefined),+ } as unknown as AsrProvider;+ });+ const secondCreate = vi.fn(async () => ({+ start: vi.fn(async () => undefined),+ stop: vi.fn(async () => undefined),+ } as unknown as AsrProvider));++ const first = runSerializedVoiceInputConnectionTest({+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ configurationKey: 'selection-a',+ createProvider: firstCreate,+ });+ await Promise.resolve();++ await expect(runSerializedVoiceInputConnectionTest({+ provider: 'elevenlabs-scribe-realtime',+ providerModel: 'scribe_v2_realtime',+ configurationKey: 'selection-b',+ createProvider: secondCreate,+ })).resolves.toEqual({+ ok: false,+ provider: 'elevenlabs-scribe-realtime',+ providerModel: 'scribe_v2_realtime',+ reason: 'service-error',+ });+ expect(secondCreate).not.toHaveBeenCalled();++ releaseFirst();+ await expect(first).resolves.toEqual({+ ok: true,+ provider: 'litellm-gpt-realtime-whisper',+ providerModel: 'gpt-realtime-whisper',+ });+ });+});diff --git a/apps/desktop/src/main/voice-input/__tests__/voiceInputCustomAsrPersistence.test.ts b/apps/desktop/src/main/voice-input/__tests__/voiceInputCustomAsrPersistence.test.tsnew file mode 100644index 0000000000..7655a67c52--- /dev/null+++ b/apps/desktop/src/main/voice-input/__tests__/voiceInputCustomAsrPersistence.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it, vi } from 'vitest';++import {+ persistVoiceInputSelectionWithCustomAsrSecret,+ type CustomAsrSecretStore,+} from '../voiceInputCustomAsrPersistence.js';++function createSecretStore(initial: string | null): CustomAsrSecretStore & {+ value: string | null;+} {+ return {+ value: initial,+ get: vi.fn(function (this: { value: string | null }) {+ return this.value;+ }),+ set: vi.fn(function (this: { value: string | null }, _id, value) {+ this.value = value;+ return true;+ }),+ remove: vi.fn(function (this: { value: string | null }) {+ this.value = null;+ return { success: true };+ }),+ };+}++describe('custom ASR model-selection persistence', () => {+ it('does not write config when safeStorage rejects the new key', () => {+ const store = createSecretStore('old-key');+ vi.mocked(store.set).mockReturnValueOnce(false);+ const persistSelection = vi.fn(() => 'saved');++ expect(() => persistVoiceInputSelectionWithCustomAsrSecret(+ persistSelection,+ store,+ { action: 'set', value: 'new-key' },+ )).toThrow('Failed to store');+ expect(persistSelection).not.toHaveBeenCalled();+ expect(store.value).toBe('old-key');+ });++ it('restores the previous key when config persistence fails', () => {+ const store = createSecretStore('old-key');+ const persistSelection = vi.fn(() => {+ throw new Error('config write failed');+ });++ expect(() => persistVoiceInputSelectionWithCustomAsrSecret(+ persistSelection,+ store,+ { action: 'set', value: 'new-key' },+ )).toThrow('config write failed');+ expect(store.value).toBe('old-key');+ expect(store.set).toHaveBeenNthCalledWith(1, 'voice-asr', 'new-key');+ expect(store.set).toHaveBeenNthCalledWith(2, 'voice-asr', 'old-key');+ });++ it('restores a removed key when config persistence fails', () => {+ const store = createSecretStore('old-key');+ const persistSelection = vi.fn(() => {+ throw new Error('config write failed');+ });++ expect(() => persistVoiceInputSelectionWithCustomAsrSecret(+ persistSelection,+ store,+ { action: 'clear' },+ )).toThrow('config write failed');+ expect(store.value).toBe('old-key');+ expect(store.remove).toHaveBeenCalledWith('voice-asr');+ expect(store.set).toHaveBeenCalledWith('voice-asr', 'old-key');+ });++ it('preserves the config write error when restoring the previous key also fails', () => {+ const store = createSecretStore('old-key');+ vi.mocked(store.set)+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false);+ vi.mocked(store.remove).mockReturnValue({ success: false });+ const configError = new Error('config write failed');++ let thrown: unknown;+ try {+ persistVoiceInputSelectionWithCustomAsrSecret(+ () => {+ throw configError;+ },+ store,+ { action: 'set', value: 'new-key' },+ );+ } catch (error) {+ thrown = error;+ }++ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as Error).message).toContain('restore the previous ASR key');+ expect((thrown as Error & { cause?: unknown }).cause).toBe(configError);+ });++ it('clears the uncertain key when restore fails but quarantine succeeds', () => {+ const store = createSecretStore('old-key');+ vi.mocked(store.set)+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false);+ const configError = new Error('config write failed');++ expect(() => persistVoiceInputSelectionWithCustomAsrSecret(+ () => {+ throw configError;+ },+ store,+ { action: 'set', value: 'new-key' },+ )).toThrow('the ASR key was cleared');+ expect(store.value).toBeNull();+ expect(store.remove).toHaveBeenCalledWith('voice-asr');+ });++ it('commits both key and selection when both writes succeed', () => {+ const store = createSecretStore(null);+ const persistSelection = vi.fn(() => ({ ok: true }));++ expect(persistVoiceInputSelectionWithCustomAsrSecret(+ persistSelection,+ store,+ { action: 'set', value: 'new-key' },+ )).toEqual({ ok: true });+ expect(store.value).toBe('new-key');+ });+});diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.tsindex 321f79827a..be78ef1b92 100644--- a/apps/desktop/src/main/voice-input/index.ts+++ b/apps/desktop/src/main/voice-input/index.ts@@ -20,10 +20,13 @@ import {} from '@cindy/voice-input-core';import { createLogger } from '../logger.js';import { getAppCapabilities } from '../appCapabilities.js';+import { getProviderSecretStore } from '../secrets/providerSecretStore.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import {desktopCodexAuthAdapter,readOwnerScopedXdGatewayKey,} from '../maker-host/auth-adapters.js';+import { getActiveAppSession } from '../appSessionState.js';import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs.js';import { throwIpcError } from '../utils/ipcValidate.js';import {@@ -46,6 +49,7 @@ import {prewarmLiteLlmRefinerEndpoint,} from './LiteLlmTextModelClient.js';import {+ invalidatePrewarmedRealtimeAsrWebSocketSession,RealtimeAsrWebSocketProvider,prewarmRealtimeAsrWebSocketSession,type RealtimeAsrWebSocketProviderOptions,@@ -102,7 +106,10 @@ import {effectiveVoiceInputServiceMode,reloadVoiceInputModelSelection,setVoiceInputModelSelection,+ validateVoiceInputCustomAsrConfig,+ voiceInputAsrChainForServiceMode,voiceInputModelSelectionSignature,+ type VoiceInputCustomAsrConfig,type VoiceInputModelSelection,type VoiceInputModelSelectionPatch,type VoiceInputServiceMode,@@ -115,8 +122,23 @@ import {type VoiceInputRefinerProfile,type VoiceInputRefinerProviderKind,} from '../../shared/voiceInputRefinerProfiles.js';+import {+ canReuseVoiceInputCustomAsrCredential,+ MAX_CUSTOM_ASR_API_KEY_CHARS,+ resolveVoiceInputCustomAsrWebsocketUrl,+} from '../../shared/voiceInputCustomAsr.js';+import {+ persistVoiceInputSelectionWithCustomAsrSecret,+ type CustomAsrSecretUpdate,+} from './voiceInputCustomAsrPersistence.js';+import {+ VOICE_INPUT_TEST_CONNECTION_CHANNEL,+ type VoiceInputConnectionTestResult,+} from '../../shared/voiceInputConnectionTest.js';+import { runSerializedVoiceInputConnectionTest } from './voiceInputConnectionTest.js';const log = createLogger('voice-input');+let customAsrCredentialRevision = 0;// The built-in realtime voice path is a Cindy service, not a hidden BYOK// consumer. A voice-server outage must never spend the user's general model@@ -180,12 +202,14 @@ type ActiveVoiceInput = {type VoiceInputReadiness = {ok: boolean;+ serviceMode: VoiceInputServiceMode;provider: VoiceInputProviderKind;providerModel: string;auth: 'api-key' | 'codex';settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;authErrorReason?: string;+ failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';};type VoiceInputRefinerReadiness = {@@ -219,6 +243,7 @@ type VoiceInputModelSelectionIpcResult = {auth: VoiceInputRefinerProfile['auth'];}>;readiness: VoiceInputReadiness;+ customAsrApiKeyConfigured: boolean;};type VoiceInputSystemPermissions = {@@ -638,11 +663,39 @@ function resolveVoiceInputProviderKind(): VoiceInputProviderKind {return readActiveVoiceInputModelSelection('resolve-asr-provider').asrProvider;}+function resolveVoiceInputProviderModel(provider: VoiceInputProviderKind): string {+ return provider === 'custom-realtime-asr'+ ? (readActiveVoiceInputModelSelection('resolve-custom-asr-model').customAsr?.model+ ?? getVoiceInputAsrProfile(provider).model)+ : getVoiceInputAsrProfile(provider).model;+}++function voiceInputConnectionTestConfigurationKey(+ selection: VoiceInputModelSelection,+): string {+ return JSON.stringify({+ ownerIdentity: getActiveAppSession().dataOwnerId ?? 'local',+ serviceMode: selection.serviceMode,+ asrProvider: selection.asrProvider,+ asrProviderChain: selection.asrProviderChain,+ customAsr: selection.customAsr ?? null,+ customAsrCredentialRevision,+ });+}+// Configured ASR fallback chain (primary first), reordered so providers in// sticky-failover cooldown sort behind healthy ones.function resolveVoiceInputAsrChain(): VoiceInputProviderKind[] {const selection = readActiveVoiceInputModelSelection('resolve-asr-chain');- return orderVoiceInputProvidersByHealth('asr', selection.asrProviderChain);+ // Managed Cindy voice keeps the product-owned provider failover chain.+ // BYOK must not infer that unrelated providers share credentials or routes:+ // unless the user explicitly configured a chain, dial only the selected+ // primary provider.+ const chain = voiceInputAsrChainForServiceMode({+ ...selection,+ serviceMode: isVoiceInputByokMode() ? 'byok' : 'cindy',+ });+ return orderVoiceInputProvidersByHealth('asr', chain);}function resolveVoiceInputRefinerProfile(): VoiceInputRefinerProfile {@@ -951,6 +1004,31 @@ function buildRealtimeAsrProviderOptions(return options;}+function buildCustomRealtimeAsrProviderOptions(+ config: VoiceInputCustomAsrConfig,+ sourceLanguage: string | undefined,+): RealtimeAsrWebSocketProviderOptions {+ const profile = getVoiceInputAsrProfile('custom-realtime-asr');+ const openAiProtocol = config.protocol === 'openai-realtime';+ const apiKey = getProviderSecretStore().get('voice-asr');+ const ownerIdentity = getActiveAppSession().dataOwnerId ?? 'local';+ return {+ accessTokenProvider: () => Promise.resolve(apiKey),+ credentialCacheKey: apiKey+ ? `custom-asr-${ownerIdentity}-${customAsrCredentialRevision}`+ : '',+ model: config.model,+ realtimeUrl: resolveVoiceInputCustomAsrWebsocketUrl(config),+ sourceLanguage,+ pcmSampleRate: openAiProtocol ? 24_000 : 16_000,+ protocolProfile: openAiProtocol ? 'openai-transcription-manual' : 'qwen-asr-server-vad',+ providerKind: 'custom-realtime-asr',+ missingCredentialMessage: profile.missingCredentialMessage,+ errorFallbackMessage: profile.errorFallbackMessage,+ redactUpstreamErrors: true,+ };+}+/*** Best-effort warm-up for the configured voice-input provider.*@@ -1040,7 +1118,16 @@ export async function prewarmVoiceInputProvider(options?: { sourceLanguage?: str// preconnect so the first audio frame does not wait behind TLS +// session.update.if (byokMode && profile.mode === 'realtime-websocket' && profile.realtime?.prewarmable && !disableRealtimePreconnect) {- if (profile.auth === 'codex') {+ if (provider === 'custom-realtime-asr') {+ const customAsr = readActiveVoiceInputModelSelection('custom-asr-prewarm').customAsr;+ const customAsrKey = getProviderSecretStore().get('voice-asr');+ if (customAsr && customAsrKey) {+ await prewarmRealtimeAsrWebSocketSession(buildCustomRealtimeAsrProviderOptions(+ customAsr,+ asrLanguageHint,+ ));+ }+ } else if (profile.auth === 'codex') {const token = await desktopCodexAuthAdapter.getAccessToken();if (token) {await prewarmRealtimeAsrWebSocketSession(buildRealtimeAsrProviderOptions(@@ -1088,6 +1175,7 @@ type AsrCredentialReadiness = {ok: boolean;error?: string;authErrorReason?: string;+ failureReason?: VoiceInputReadiness['failureReason'];};async function getAsrProfileCredentialReadiness(profile: VoiceInputAsrProfile): Promise<AsrCredentialReadiness> {@@ -1106,6 +1194,30 @@ async function getAsrProfileCredentialReadiness(profile: VoiceInputAsrProfile):// Mirror the pre-managed-migration readiness checks per auth kind. The// managed voice service is deliberately not consulted here — no cross-mode// fallback in either direction.+ if (profile.id === 'custom-realtime-asr') {+ const customAsr = readActiveVoiceInputModelSelection('custom-asr-readiness').customAsr;+ if (!customAsr) {+ return {+ ok: false,+ error: profile.missingCredentialMessage,+ failureReason: 'custom-asr-config-missing',+ };+ }+ const hasCustomAsrKey = getProviderSecretStore().has('voice-asr');+ return {+ ok: hasCustomAsrKey,+ error: hasCustomAsrKey ? undefined : profile.missingCredentialMessage,+ failureReason: hasCustomAsrKey ? undefined : 'custom-asr-key-missing',+ };+ }+ if (profile.id === 'openai-realtime-whisper') {+ return {+ ok: false,+ error: 'Codex sign-in cannot be used as an OpenAI API Realtime credential.',+ failureReason: 'codex-realtime-unsupported',+ };+ }+if (profile.auth === 'codex') {const codexAuthState = await desktopCodexAuthAdapter.getState();return {@@ -1135,15 +1247,18 @@ function toVoiceInputReadiness(provider: VoiceInputProviderKind,profile: VoiceInputAsrProfile,credential: AsrCredentialReadiness,+ serviceMode: VoiceInputServiceMode,): VoiceInputReadiness {return {ok: credential.ok,+ serviceMode,provider,- providerModel: profile.model,+ providerModel: resolveVoiceInputProviderModel(provider),auth: profile.auth,settingsTab: profile.settingsTab,error: credential.error,authErrorReason: credential.authErrorReason,+ failureReason: credential.failureReason,};}@@ -1152,14 +1267,20 @@ function toVoiceInputReadiness(// new dictation will try first. When nothing on the chain is ready, report// the user-selected primary's failure so settings deep-links stay accurate.async function getVoiceInputReadiness(): Promise<VoiceInputReadiness> {+ const serviceMode: VoiceInputServiceMode = isVoiceInputByokMode() ? 'byok' : 'cindy';for (const kind of resolveVoiceInputAsrChain()) {const profile = getVoiceInputAsrProfile(kind);const credential = await getAsrProfileCredentialReadiness(profile);- if (credential.ok) return toVoiceInputReadiness(kind, profile, credential);+ if (credential.ok) return toVoiceInputReadiness(kind, profile, credential, serviceMode);}const primary = resolveVoiceInputProviderKind();const primaryProfile = getVoiceInputAsrProfile(primary);- return toVoiceInputReadiness(primary, primaryProfile, await getAsrProfileCredentialReadiness(primaryProfile));+ return toVoiceInputReadiness(+ primary,+ primaryProfile,+ await getAsrProfileCredentialReadiness(primaryProfile),+ serviceMode,+ );}// The startable chain for one dictation session: credential-ready candidates@@ -1284,6 +1405,15 @@ function voiceInputModelSelectionPatchFromIpc(payload: unknown): VoiceInputModelif (Object.prototype.hasOwnProperty.call(source, 'asrProvider')) {patch.asrProvider = resolveAsrProviderFromIpc(source.asrProvider);}+ if (Object.prototype.hasOwnProperty.call(source, 'customAsr')) {+ if (source.customAsr === null || source.customAsr === undefined) {+ patch.customAsr = null;+ } else {+ const validated = validateVoiceInputCustomAsrConfig(source.customAsr);+ if (!validated.ok) throwIpcError('INVALID_PARAMS', validated.error);+ patch.customAsr = validated.value;+ }+ }if (Object.prototype.hasOwnProperty.call(source, 'refinerProvider')) {patch.refinerProvider = resolveRefinerProviderFromIpc(source.refinerProvider);}@@ -1296,6 +1426,41 @@ function voiceInputModelSelectionPatchFromIpc(payload: unknown): VoiceInputModelreturn patch;}+function customAsrSecretUpdateFromIpc(payload: unknown): CustomAsrSecretUpdate {+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return { action: 'none' };+ const source = payload as Record<string, unknown>;+ if (!Object.prototype.hasOwnProperty.call(source, 'customAsrApiKey')) return { action: 'none' };+ if (source.customAsrApiKey === null) return { action: 'clear' };+ if (typeof source.customAsrApiKey !== 'string') {+ throwIpcError('INVALID_PARAMS', 'customAsrApiKey must be a string or null');+ }+ const value = source.customAsrApiKey.trim();+ if (!value || value.length > MAX_CUSTOM_ASR_API_KEY_CHARS) {+ throwIpcError('INVALID_PARAMS', 'customAsrApiKey must contain 1 to 8192 characters');+ }+ return { action: 'set', value };+}++function assertCustomAsrCredentialScope(+ currentSelection: VoiceInputModelSelection,+ patch: VoiceInputModelSelectionPatch,+ secretUpdate: CustomAsrSecretUpdate,+): void {+ if (!Object.prototype.hasOwnProperty.call(patch, 'customAsr')) return;+ if (!patch.customAsr || secretUpdate.action !== 'none') return;+ if (!getProviderSecretStore().has('voice-asr')) return;++ if (!canReuseVoiceInputCustomAsrCredential(+ currentSelection.customAsr?.websocketUrl,+ patch.customAsr.websocketUrl,+ )) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'customAsrApiKey must be set or cleared when the custom ASR endpoint origin changes',+ );+ }+}+function resolveRefinerProviderChainFromIpc(value: unknown): VoiceInputRefinerProviderKind[] | null {if (value === null || value === undefined) return null;if (!Array.isArray(value)) {@@ -1378,6 +1543,7 @@ async function buildVoiceInputModelSelectionIpcResult(auth: profile.auth,})),readiness,+ customAsrApiKeyConfigured: getProviderSecretStore().has('voice-asr'),};}@@ -1390,6 +1556,18 @@ async function createVoiceInputProvider(if (voiceContext && !isManagedVoiceAsrProfile(profile)) {throw new Error(CINDY_VOICE_SERVICE_UNAVAILABLE_MESSAGE);}+ if (provider === 'custom-realtime-asr') {+ if (!isVoiceInputByokMode()) {+ throw new Error(CINDY_VOICE_SERVICE_UNAVAILABLE_MESSAGE);+ }+ const customAsr = readActiveVoiceInputModelSelection('custom-asr-create').customAsr;+ if (!customAsr) throw new Error(profile.missingCredentialMessage);+ if (!getProviderSecretStore().has('voice-asr')) throw new Error(profile.missingCredentialMessage);+ return new RealtimeAsrWebSocketProvider(buildCustomRealtimeAsrProviderOptions(+ customAsr,+ sourceLanguage,+ ));+ }if (profile.mode === 'realtime-websocket') {const realtimeConfig = profile.realtime;if (!realtimeConfig) throw new Error(`Voice input provider ${provider} is missing realtime config.`);@@ -1612,27 +1790,81 @@ export function registerVoiceInputIpc(): void {}});- ipcMain.handle('voice-input:get-readiness', async (): Promise<VoiceInputReadiness> =>- refreshVoiceInputReadinessCache('ipc'),- );+ ipcMain.handle('voice-input:get-readiness', async (event): Promise<VoiceInputReadiness> => {+ assertTrustedAppRendererEvent(event);+ return refreshVoiceInputReadinessCache('ipc');+ });- ipcMain.handle('voice-input:model-selection:get', async (): Promise<VoiceInputModelSelectionIpcResult> =>- buildVoiceInputModelSelectionIpcResult('get'),+ ipcMain.handle(+ VOICE_INPUT_TEST_CONNECTION_CHANNEL,+ async (event): Promise<VoiceInputConnectionTestResult> => {+ assertTrustedAppRendererEvent(event);+ const selection = readActiveVoiceInputModelSelection('connection-test');+ const provider = selection.asrProvider;+ const profile = getVoiceInputAsrProfile(provider);+ const providerModel = resolveVoiceInputProviderModel(provider);++ if (+ !isVoiceInputByokMode()+ || profile.mode === 'batch-http'+ || provider === 'openai-realtime-whisper'+ ) {+ return {+ ok: false,+ provider,+ providerModel,+ reason: 'unsupported-provider',+ };+ }++ return runSerializedVoiceInputConnectionTest({+ provider,+ providerModel,+ configurationKey: voiceInputConnectionTestConfigurationKey(selection),+ createProvider: () => {+ invalidatePrewarmedRealtimeAsrWebSocketSession();+ return createVoiceInputProvider(provider, undefined);+ },+ onError: (error) => {+ log.warn('voice input connection test failed', {+ provider,+ errorType: error instanceof Error ? error.name : typeof error,+ });+ },+ });+ },);+ ipcMain.handle('voice-input:model-selection:get', async (event): Promise<VoiceInputModelSelectionIpcResult> => {+ assertTrustedAppRendererEvent(event);+ return buildVoiceInputModelSelectionIpcResult('get');+ });+ipcMain.handle('voice-input:model-selection:set',- async (_event, payload: unknown): Promise<VoiceInputModelSelectionIpcResult> => {+ async (event, payload: unknown): Promise<VoiceInputModelSelectionIpcResult> => {+ assertTrustedAppRendererEvent(event);const patch = voiceInputModelSelectionPatchFromIpc(payload);+ const customAsrSecretUpdate = customAsrSecretUpdateFromIpc(payload);+ const currentSelection = readActiveVoiceInputModelSelection('ipc-set-before-write');+ assertCustomAsrCredentialScope(currentSelection, patch, customAsrSecretUpdate);let selection: VoiceInputModelSelection;try {- selection = setVoiceInputModelSelection(patch);+ selection = persistVoiceInputSelectionWithCustomAsrSecret(+ () => setVoiceInputModelSelection(patch),+ getProviderSecretStore(),+ customAsrSecretUpdate,+ );} catch (error) {log.warn('voice input model selection write failed', {error: error instanceof Error ? error.message : String(error),});throwIpcError('INTERNAL', 'Failed to save voice input model selection.');}+ if (customAsrSecretUpdate.action !== 'none') {+ customAsrCredentialRevision += 1;+ invalidatePrewarmedRealtimeAsrWebSocketSession();+ }markVoiceInputModelSelectionApplied('ipc-set', selection);const result = await buildVoiceInputModelSelectionIpcResult('set');void prewarmVoiceInputProvider();@@ -1640,7 +1872,8 @@ export function registerVoiceInputIpc(): void {},);- ipcMain.handle('voice-input:model-selection:reload', async (): Promise<VoiceInputModelSelectionIpcResult> => {+ ipcMain.handle('voice-input:model-selection:reload', async (event): Promise<VoiceInputModelSelectionIpcResult> => {+ assertTrustedAppRendererEvent(event);const selection = reloadVoiceInputModelSelection();markVoiceInputModelSelectionApplied('ipc-reload', selection);const result = await buildVoiceInputModelSelectionIpcResult('reload');@@ -1963,7 +2196,7 @@ export function registerVoiceInputIpc(): void {refineSourceLanguage,provider: provider.activeProviderKind ?? readiness.provider,providerModel: provider.activeProviderKind- ? getVoiceInputAsrProfile(provider.activeProviderKind).model+ ? resolveVoiceInputProviderModel(provider.activeProviderKind): readiness.providerModel,asrChain: startableAsrChain,refiner: refiner ? effectiveRefinerProfile?.model : undefined,diff --git a/apps/desktop/src/main/voice-input/voiceInputConnectionTest.ts b/apps/desktop/src/main/voice-input/voiceInputConnectionTest.tsnew file mode 100644index 0000000000..d138556d4c--- /dev/null+++ b/apps/desktop/src/main/voice-input/voiceInputConnectionTest.ts@@ -0,0 +1,132 @@+import type { AsrProvider } from '@cindy/voice-input-core';++import type {+ VoiceInputConnectionTestFailureReason,+ VoiceInputConnectionTestResult,+} from '../../shared/voiceInputConnectionTest.js';+import type { VoiceInputProviderKind } from '../../shared/voiceInputAsrProfiles.js';++export type VoiceInputConnectionTestOptions = {+ provider: VoiceInputProviderKind;+ providerModel: string;+ /** Stable, non-secret identity of the configuration being probed. */+ configurationKey?: string;+ createProvider: () => Promise<AsrProvider>;+ onError?: (error: unknown) => void;+};++let activeConnectionTest: {+ key: string;+ promise: Promise<VoiceInputConnectionTestResult>;+} | null = null;++/**+ * Coalesce connection probes in Main so a compromised renderer cannot create+ * an unbounded queue or simultaneous outbound WebSocket handshakes.+ */+export function runSerializedVoiceInputConnectionTest(+ options: VoiceInputConnectionTestOptions,+): Promise<VoiceInputConnectionTestResult> {+ const key = options.configurationKey ?? `${options.provider}:${options.providerModel}`;+ if (activeConnectionTest) {+ if (activeConnectionTest.key === key) return activeConnectionTest.promise;+ return Promise.resolve({+ ok: false,+ provider: options.provider,+ providerModel: options.providerModel,+ reason: 'service-error',+ });+ }+ const current = runVoiceInputConnectionTest(options).finally(() => {+ if (activeConnectionTest?.promise === current) activeConnectionTest = null;+ });+ activeConnectionTest = { key, promise: current };+ return current;+}++export function classifyVoiceInputConnectionTestError(+ error: unknown,+): VoiceInputConnectionTestFailureReason {+ const message = error instanceof Error ? error.message : String(error);+ const normalized = message.toLowerCase();++ if (+ /\b(?:401|403)\b/.test(normalized)+ || normalized.includes('unauthorized')+ || normalized.includes('forbidden')+ || normalized.includes('authentication failed')+ || normalized.includes('invalid api key')+ || normalized.includes('invalid token')+ ) {+ return 'authentication-failed';+ }+ if (+ normalized.includes('api key is required')+ || normalized.includes('missing api key')+ || normalized.includes('missing credential')+ || normalized.includes('sign-in is required')+ || normalized.includes('login is required')+ || normalized.includes('configure the realtime asr websocket url')+ ) {+ return 'credentials-missing';+ }+ if (+ /\b(?:404|405|501)\b/.test(normalized)+ || normalized.includes('route not found')+ || normalized.includes('unknown route')+ || normalized.includes('unsupported route')+ ) {+ return 'route-unavailable';+ }+ if (normalized.includes('timed out') || normalized.includes('timeout')) {+ return 'timeout';+ }+ if (+ normalized.includes('econnrefused')+ || normalized.includes('econnreset')+ || normalized.includes('enotfound')+ || normalized.includes('eai_again')+ || normalized.includes('socket hang up')+ || normalized.includes('network')+ || normalized.includes('certificate')+ || normalized.includes('tls')+ ) {+ return 'network';+ }+ return 'service-error';+}++export async function runVoiceInputConnectionTest(+ options: VoiceInputConnectionTestOptions,+): Promise<VoiceInputConnectionTestResult> {+ let provider: AsrProvider | undefined;+ try {+ provider = await options.createProvider();+ await provider.start();+ return {+ ok: true,+ provider: options.provider,+ providerModel: options.providerModel,+ };+ } catch (error) {+ options.onError?.(error);+ return {+ ok: false,+ provider: options.provider,+ providerModel: options.providerModel,+ reason: classifyVoiceInputConnectionTestError(error),+ };+ } finally {+ try {+ await provider?.stop();+ } catch {+ // Connection-test cleanup is best effort; the classified probe result+ // remains more useful than replacing it with a close-time failure.+ }+ try {+ await provider?.dispose?.();+ } catch {+ // Debug recorder finalization must not change the probe result either.+ }+ }+}diff --git a/apps/desktop/src/main/voice-input/voiceInputCustomAsrPersistence.ts b/apps/desktop/src/main/voice-input/voiceInputCustomAsrPersistence.tsnew file mode 100644index 0000000000..046a8656d7--- /dev/null+++ b/apps/desktop/src/main/voice-input/voiceInputCustomAsrPersistence.ts@@ -0,0 +1,80 @@+export type CustomAsrSecretUpdate =+ | { action: 'none' }+ | { action: 'set'; value: string }+ | { action: 'clear' };++export type CustomAsrSecretStore = {+ get(id: 'voice-asr'): string | null;+ set(id: 'voice-asr', value: string): boolean;+ remove(id: 'voice-asr'): { success: boolean; error?: string };+};++/**+ * Persist a custom ASR secret and model-selection patch as one best-effort+ * transaction. The secret is applied first so config is never committed after+ * a rejected safeStorage write; a config failure restores the previous secret.+ */+export function persistVoiceInputSelectionWithCustomAsrSecret<T>(+ persistSelection: () => T,+ secretStore: CustomAsrSecretStore,+ secretUpdate: CustomAsrSecretUpdate,+): T {+ if (secretUpdate.action === 'none') return persistSelection();++ const previousSecret = secretStore.get('voice-asr');+ applySecretUpdate(secretStore, secretUpdate);+ try {+ return persistSelection();+ } catch (error) {+ if (!restoreSecret(secretStore, previousSecret)) {+ const quarantined = quarantineSecret(secretStore);+ throw new Error(+ quarantined+ ? 'Failed to save voice input model selection; the ASR key was cleared because restoring it failed.'+ : 'Failed to save voice input model selection and restore the previous ASR key.',+ { cause: error },+ );+ }+ throw error;+ }+}++function applySecretUpdate(+ secretStore: CustomAsrSecretStore,+ secretUpdate: Exclude<CustomAsrSecretUpdate, { action: 'none' }>,+): void {+ if (secretUpdate.action === 'set') {+ if (!secretStore.set('voice-asr', secretUpdate.value)) {+ throw new Error('Failed to store the custom ASR API key.');+ }+ return;+ }+ if (!secretStore.remove('voice-asr').success) {+ throw new Error('Failed to remove the custom ASR API key.');+ }+}++function restoreSecret(+ secretStore: CustomAsrSecretStore,+ previousSecret: string | null,+): boolean {+ try {+ return previousSecret === null+ ? secretStore.remove('voice-asr').success+ : secretStore.set('voice-asr', previousSecret);+ } catch {+ return false;+ }+}++/**+ * If compensation cannot restore the previous secret, remove the uncertain+ * value so the old config fails closed instead of pairing with the new key.+ */+function quarantineSecret(secretStore: CustomAsrSecretStore): boolean {+ try {+ return secretStore.remove('voice-asr').success;+ } catch {+ return false;+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 0ec1ebc635..b11f434352 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -31,6 +31,10 @@ import {import { SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL } from '../shared/selectionContextMenu';import { SESSION_ATTENTION_CLEARED_CHANNEL } from '../shared/sessionAttention';import { VOICE_INPUT_POWER_STATE_CHANNEL } from '../shared/voiceInputPowerIpc';+import {+ VOICE_INPUT_TEST_CONNECTION_CHANNEL,+ type VoiceInputConnectionTestResult,+} from '../shared/voiceInputConnectionTest';import {type ApplicationMenuCommand,isApplicationMenuCommand,@@ -155,12 +159,14 @@ type VoiceInputSettingsUpdateResult =| { ok: false; error: string; errorCode?: 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' };type VoiceInputReadinessWire = {ok: boolean;+ serviceMode: 'cindy' | 'byok';provider: VoiceInputProviderKind;providerModel: string;auth: 'api-key' | 'codex';settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;authErrorReason?: string;+ failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';};type VoiceInputModelSelectionWire = {serviceMode: 'cindy' | 'byok';@@ -168,6 +174,15 @@ type VoiceInputModelSelectionWire = {asrProvider: VoiceInputProviderKind;refinerProvider: VoiceInputRefinerProviderKind;refinerModel?: string;+ asrProviderChain: VoiceInputProviderKind[];+ asrProviderChainSource: 'default' | 'configured';+ customAsr?: {+ protocol: 'openai-realtime' | 'qwen-realtime';+ websocketUrl: string;+ model: string;+ };+ refinerProviderChain: VoiceInputRefinerProviderKind[];+ refinerProviderChainSource: 'default' | 'configured';configPath: string;};type VoiceInputModelSelectionResultWire = {@@ -185,12 +200,20 @@ type VoiceInputModelSelectionResultWire = {auth: 'api-key' | 'codex';}>;readiness: VoiceInputReadinessWire;+ customAsrApiKeyConfigured: boolean;};type VoiceInputModelSelectionPatchWire = {serviceMode?: 'cindy' | 'byok' | null;asrProvider?: string | null;refinerProvider?: string | null;refinerModel?: string | null;+ customAsr?: {+ protocol: 'openai-realtime' | 'qwen-realtime';+ websocketUrl: string;+ model: string;+ } | null;+ customAsrApiKey?: string | null;+ refinerProviderChain?: string[] | null;};type DiscordBotSessionAuthCheckWire = {ok: boolean;@@ -964,6 +987,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('voice-input:mute-system-audio'),restoreSystemAudio: (): Promise<{ ok: true } | { ok: false; error: string }> =>ipcRenderer.invoke('voice-input:restore-system-audio'),+ testConnection: (): Promise<VoiceInputConnectionTestResult> =>+ ipcRenderer.invoke(VOICE_INPUT_TEST_CONNECTION_CHANNEL),getReadiness: (): Promise<VoiceInputReadinessWire> => ipcRenderer.invoke('voice-input:get-readiness'),getReadinessCached: (): VoiceInputReadinessWire | null =>ipcRenderer.sendSync('voice-input:get-readiness-cached'),diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsxindex 1b8b0bfcab..2ab51c10f7 100644--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx@@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties,import { useTranslation } from 'react-i18next';import { useSearchParams } from 'react-router-dom';import * as Dialog from '@radix-ui/react-dialog';-import { Check, ChevronDown, Copy, Keyboard, Pencil, Plus, RotateCcw, Search, Sparkles, Trash2, Upload, X } from 'lucide-react';+import { Check, ChevronDown, Copy, Keyboard, Loader2, Pencil, Plus, RotateCcw, Search, Sparkles, Trash2, Upload, X } from 'lucide-react';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import { Switch } from '@/components/ui/switch';@@ -52,6 +52,14 @@ import {type VoiceInputShortcut,} from '@/voice-input/shortcut';import { requestRendererMicrophonePermission } from '@/voice-input/startGuards';+import {+ canReuseVoiceInputCustomAsrCredential,+ MAX_CUSTOM_ASR_API_KEY_CHARS,+ MAX_CUSTOM_ASR_MODEL_CHARS,+ MAX_CUSTOM_ASR_WEBSOCKET_URL_CHARS,+ validateVoiceInputCustomAsrWebsocketUrl,+} from '../../../shared/voiceInputCustomAsr';+import type { VoiceInputConnectionTestFailureReason } from '../../../shared/voiceInputConnectionTest';const LANGUAGE_OPTIONS: ReadonlyArray<VoiceInputLanguage> = ['auto', ...SUPPORTED_LOCALES];const AUTO_MICROPHONE_VALUE = '__auto__';@@ -61,6 +69,24 @@ type DictionaryFilter = (typeof DICTIONARY_FILTERS)[number];type VoiceInputSystemPermissions = ReturnType<typeof window.electronAPI.voiceInput.getSystemPermissionsCached>;type VoiceInputPermissionSnapshot = VoiceInputSystemPermissions['microphone'];type VoiceInputPermissionKind = 'microphone' | 'inputMonitoring' | 'accessibility';+type VoiceInputConnectionTestViewState =+ | { status: 'idle' }+ | { status: 'testing' }+ | { status: 'success' }+ | { status: 'error'; reason: VoiceInputConnectionTestFailureReason };++const VOICE_INPUT_CONNECTION_TEST_FAILURE_KEYS: Record<+ VoiceInputConnectionTestFailureReason,+ string+> = {+ 'credentials-missing': 'settings.voiceInput.serviceSource.connectionTest.failure.credentialsMissing',+ 'authentication-failed': 'settings.voiceInput.serviceSource.connectionTest.failure.authenticationFailed',+ 'route-unavailable': 'settings.voiceInput.serviceSource.connectionTest.failure.routeUnavailable',+ timeout: 'settings.voiceInput.serviceSource.connectionTest.failure.timeout',+ network: 'settings.voiceInput.serviceSource.connectionTest.failure.network',+ 'service-error': 'settings.voiceInput.serviceSource.connectionTest.failure.serviceError',+ 'unsupported-provider': 'settings.voiceInput.serviceSource.connectionTest.failure.unsupportedProvider',+};interface VoiceInputSelectOption<T extends string> {value: T;@@ -344,19 +370,69 @@ function VoiceInputServiceSourceCard() {asrProfiles,refinerProfiles,readiness,+ customAsrApiKeyConfigured,saving,setServiceMode,setAsrProvider,setRefinerProvider,setRefinerFallbackProvider,+ saveCustomAsr,+ clearCustomAsrApiKey,resetToDefault,} = useVoiceInputModelSelection();+ const [customAsrProtocol, setCustomAsrProtocol] = useState<'openai-realtime' | 'qwen-realtime'>('openai-realtime');+ const [customAsrWebsocketUrl, setCustomAsrWebsocketUrl] = useState('');+ const [customAsrModel, setCustomAsrModel] = useState('');+ const [customAsrApiKey, setCustomAsrApiKey] = useState('');+ const [connectionTest, setConnectionTest] = useState<VoiceInputConnectionTestViewState>({ status: 'idle' });+ const connectionTestRequestRef = useRef(0);+ const customAsrFormDirtyRef = useRef(false);const localMode = appMode === 'local';const serviceMode: VoiceInputServiceModeData = localMode? 'byok': (selection?.serviceMode ?? 'cindy');const byok = serviceMode === 'byok';+ const customAsrSelected = selection?.asrProvider === 'custom-realtime-asr';+ const customAsrHasUnsavedChanges = customAsrSelected && (+ !selection?.customAsr+ || customAsrProtocol !== selection.customAsr.protocol+ || customAsrWebsocketUrl.trim() !== selection.customAsr.websocketUrl+ || customAsrModel.trim() !== selection.customAsr.model+ || Boolean(customAsrApiKey.trim())+ );++ useEffect(() => {+ if (customAsrSelected && customAsrFormDirtyRef.current) return;+ customAsrFormDirtyRef.current = false;+ if (!selection?.customAsr) {+ setCustomAsrProtocol('openai-realtime');+ setCustomAsrWebsocketUrl('');+ setCustomAsrModel('');+ setCustomAsrApiKey('');+ return;+ }+ setCustomAsrProtocol(selection.customAsr.protocol);+ setCustomAsrWebsocketUrl(selection.customAsr.websocketUrl);+ setCustomAsrModel(selection.customAsr.model);+ setCustomAsrApiKey('');+ }, [customAsrSelected, selection?.customAsr]);++ useEffect(() => {+ connectionTestRequestRef.current += 1;+ setConnectionTest({ status: 'idle' });+ }, [+ serviceMode,+ selection?.asrProvider,+ selection?.customAsr?.model,+ selection?.customAsr?.protocol,+ selection?.customAsr?.websocketUrl,+ customAsrApiKeyConfigured,+ customAsrProtocol,+ customAsrWebsocketUrl,+ customAsrModel,+ customAsrApiKey,+ ]);const openProvidersTab = useCallback(() => {const next = new URLSearchParams(searchParams);@@ -394,10 +470,17 @@ function VoiceInputServiceSourceCard() {.filter((profile) => profile.mode !== 'batch-http').map((profile) => ({value: profile.id,- label: profile.model,- description: credentialSourceLabel(profile),+ label: profile.id === 'custom-realtime-asr'+ ? t('settings.voiceInput.serviceSource.customAsr.optionLabel')+ : profile.model,+ description: profile.id === 'custom-realtime-asr'+ ? t('settings.voiceInput.serviceSource.customAsr.optionDescription')+ : profile.id === 'openai-realtime-whisper'+ ? t('settings.voiceInput.serviceSource.credential.codexRealtimeUnsupported')+ : credentialSourceLabel(profile),+ disabled: profile.id === 'openai-realtime-whisper',}))- ), [asrProfiles, credentialSourceLabel]);+ ), [asrProfiles, credentialSourceLabel, t]);const refinerOptions = useMemo<ReadonlyArray<VoiceInputSelectOption<string>>>(() => (refinerProfiles.map((profile) => ({@@ -429,6 +512,15 @@ function VoiceInputServiceSourceCard() {// raw main-process message (which is an untranslated profile constant).const byokCredentialErrorText = useMemo(() => {if (!byok || !readiness || readiness.ok) return null;+ if (readiness.failureReason === 'custom-asr-config-missing') {+ return t('settings.voiceInput.serviceSource.credentialError.customAsrConfigMissing');+ }+ if (readiness.failureReason === 'custom-asr-key-missing') {+ return t('settings.voiceInput.serviceSource.credentialError.customAsrKeyMissing');+ }+ if (readiness.failureReason === 'codex-realtime-unsupported') {+ return t('settings.voiceInput.serviceSource.credentialError.codexRealtimeUnsupported');+ }if (readiness.auth === 'codex') return t('settings.voiceInput.serviceSource.credentialError.codexMissing');if (readiness.provider.startsWith('elevenlabs')) {return t('settings.voiceInput.serviceSource.credentialError.elevenlabsMissing');@@ -436,6 +528,57 @@ function VoiceInputServiceSourceCard() {return t('settings.voiceInput.serviceSource.credentialError.gatewayMissing');}, [byok, readiness, t]);+ const customAsrUrlValidationError = validateVoiceInputCustomAsrWebsocketUrl(customAsrWebsocketUrl);+ const customAsrUrlInvalid = Boolean(customAsrWebsocketUrl.trim() && customAsrUrlValidationError);+ const customAsrEndpointRequiresNewKey = customAsrApiKeyConfigured+ && customAsrUrlValidationError === null+ && !canReuseVoiceInputCustomAsrCredential(+ selection?.customAsr?.websocketUrl,+ customAsrWebsocketUrl,+ );+ const customAsrCanSave = customAsrUrlValidationError === null+ && Boolean(customAsrModel.trim())+ && (!customAsrEndpointRequiresNewKey || Boolean(customAsrApiKey.trim()));+ const credentialRecoveryInVoiceSettings = customAsrSelected+ || readiness?.failureReason === 'codex-realtime-unsupported';++ const handleSaveCustomAsr = useCallback(async () => {+ const saved = await saveCustomAsr({+ protocol: customAsrProtocol,+ websocketUrl: customAsrWebsocketUrl,+ model: customAsrModel,+ }, customAsrApiKey);+ if (saved) {+ customAsrFormDirtyRef.current = false;+ setCustomAsrApiKey('');+ }+ }, [+ customAsrApiKey,+ customAsrModel,+ customAsrProtocol,+ customAsrWebsocketUrl,+ saveCustomAsr,+ ]);++ const handleTestConnection = useCallback(async () => {+ const requestId = connectionTestRequestRef.current + 1;+ connectionTestRequestRef.current = requestId;+ setConnectionTest({ status: 'testing' });+ try {+ const result = await window.electronAPI.voiceInput.testConnection();+ if (connectionTestRequestRef.current !== requestId) return;+ setConnectionTest(result.ok+ ? { status: 'success' }+ : { status: 'error', reason: result.reason });+ } catch {+ if (connectionTestRequestRef.current !== requestId) return;+ setConnectionTest({ status: 'error', reason: 'service-error' });+ }+ }, []);++ const connectionTestBusy = connectionTest.status === 'testing';+ const connectionTestDisabled = saving || connectionTestBusy || customAsrHasUnsavedChanges;+const customized = !localMode && Boolean(selection?.serviceModeConfigured);return (@@ -477,6 +620,32 @@ function VoiceInputServiceSourceCard() {<><VoiceInputInlineSettingRowlabel={t('settings.voiceInput.serviceSource.asr.label')}+ labelAction={(+ <button+ type="button"+ disabled={connectionTestDisabled}+ onClick={() => void handleTestConnection()}+ title={customAsrHasUnsavedChanges+ ? t('settings.voiceInput.serviceSource.connectionTest.saveBeforeTest')+ : undefined}+ className={cn(+ 'inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-12 outline-none transition-colors',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',+ 'text-[var(--settings-section-sublabel)]',+ 'hover:border-[var(--settings-input-border-focus)] focus-visible:border-[var(--settings-input-border-focus)]',+ connectionTestDisabled && 'cursor-not-allowed opacity-55',+ )}+ >+ {connectionTestBusy ? (+ <span className="inline-flex animate-spin motion-reduce:animate-none" aria-hidden>+ <Loader2 size={12} />+ </span>+ ) : null}+ {t(connectionTestBusy+ ? 'settings.voiceInput.serviceSource.connectionTest.testing'+ : 'settings.voiceInput.serviceSource.connectionTest.action')}+ </button>+ )}hint={t('settings.voiceInput.serviceSource.asr.hint')}><VoiceInputSelect@@ -487,6 +656,184 @@ function VoiceInputServiceSourceCard() {/></VoiceInputInlineSettingRow>+ {connectionTest.status !== 'idle' ? (+ <div+ role={connectionTest.status === 'error' ? 'alert' : 'status'}+ aria-live="polite"+ className={cn(+ 'flex items-center gap-2 rounded-[10px] border px-3 py-2 text-12 leading-[1.4]',+ connectionTest.status === 'error'+ ? 'border-[var(--error-border)] bg-[var(--error-bg)] text-[var(--error-fg)]'+ : 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-section-sublabel)]',+ )}+ >+ {connectionTest.status === 'success' ? <Check size={13} aria-hidden /> : null}+ {connectionTest.status === 'testing' ? (+ <span className="inline-flex animate-spin motion-reduce:animate-none" aria-hidden>+ <Loader2 size={13} />+ </span>+ ) : null}+ <span>+ {connectionTest.status === 'testing'+ ? t('settings.voiceInput.serviceSource.connectionTest.testingStatus')+ : connectionTest.status === 'success'+ ? t('settings.voiceInput.serviceSource.connectionTest.success')+ : t(VOICE_INPUT_CONNECTION_TEST_FAILURE_KEYS[connectionTest.reason])}+ </span>+ </div>+ ) : null}++ {customAsrSelected ? (+ <div className="flex flex-col gap-3 rounded-[12px] border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] p-3.5">+ <p className="text-12 leading-[1.45] text-[var(--settings-section-sublabel)]">+ {t('settings.voiceInput.serviceSource.customAsr.notice')}+ </p>++ <VoiceInputInlineSettingRow+ label={t('settings.voiceInput.serviceSource.customAsr.protocol.label')}+ hint={t('settings.voiceInput.serviceSource.customAsr.protocol.hint')}+ >+ <VoiceInputSelect+ value={customAsrProtocol}+ options={[+ {+ value: 'openai-realtime',+ label: t('settings.voiceInput.serviceSource.customAsr.protocol.openai'),+ },+ {+ value: 'qwen-realtime',+ label: t('settings.voiceInput.serviceSource.customAsr.protocol.qwen'),+ },+ ]}+ onChange={(value) => {+ customAsrFormDirtyRef.current = true;+ setCustomAsrProtocol(value);+ }}+ ariaLabel={t('settings.voiceInput.serviceSource.customAsr.protocol.ariaLabel')}+ />+ </VoiceInputInlineSettingRow>++ <VoiceInputInlineSettingRow+ label={t('settings.voiceInput.serviceSource.customAsr.websocketUrl.label')}+ hint={t('settings.voiceInput.serviceSource.customAsr.websocketUrl.hint')}+ >+ <input+ type="url"+ value={customAsrWebsocketUrl}+ onChange={(event) => {+ customAsrFormDirtyRef.current = true;+ setCustomAsrWebsocketUrl(event.target.value);+ }}+ placeholder={t('settings.voiceInput.serviceSource.customAsr.websocketUrl.placeholder')}+ maxLength={MAX_CUSTOM_ASR_WEBSOCKET_URL_CHARS}+ spellCheck={false}+ autoComplete="off"+ className={cn(+ 'h-9 w-full rounded-full border px-3 text-13 outline-none transition-colors',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',+ 'placeholder:text-[var(--settings-section-sublabel)] placeholder:opacity-55',+ 'focus:border-[var(--settings-input-border-focus)]',+ )}+ />+ </VoiceInputInlineSettingRow>+ {customAsrUrlInvalid ? (+ <p+ role="alert"+ className="rounded-[10px] border border-[var(--error-border)] bg-[var(--error-bg)] px-3 py-2 text-12 leading-[1.4] text-[var(--error-fg)]"+ >+ {t('settings.voiceInput.serviceSource.customAsr.websocketUrl.invalid')}+ </p>+ ) : null}++ <VoiceInputInlineSettingRow+ label={t('settings.voiceInput.serviceSource.customAsr.model.label')}+ hint={t('settings.voiceInput.serviceSource.customAsr.model.hint')}+ >+ <input+ type="text"+ value={customAsrModel}+ onChange={(event) => {+ customAsrFormDirtyRef.current = true;+ setCustomAsrModel(event.target.value);+ }}+ placeholder={t('settings.voiceInput.serviceSource.customAsr.model.placeholder')}+ maxLength={MAX_CUSTOM_ASR_MODEL_CHARS}+ spellCheck={false}+ autoComplete="off"+ className={cn(+ 'h-9 w-full rounded-full border px-3 text-13 outline-none transition-colors',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',+ 'placeholder:text-[var(--settings-section-sublabel)] placeholder:opacity-55',+ 'focus:border-[var(--settings-input-border-focus)]',+ )}+ />+ </VoiceInputInlineSettingRow>++ <VoiceInputInlineSettingRow+ label={t('settings.voiceInput.serviceSource.customAsr.apiKey.label')}+ hint={t(customAsrEndpointRequiresNewKey+ ? 'settings.voiceInput.serviceSource.customAsr.apiKey.endpointChangedHint'+ : customAsrApiKeyConfigured+ ? 'settings.voiceInput.serviceSource.customAsr.apiKey.savedHint'+ : 'settings.voiceInput.serviceSource.customAsr.apiKey.hint')}+ >+ <input+ type="password"+ value={customAsrApiKey}+ onChange={(event) => {+ customAsrFormDirtyRef.current = true;+ setCustomAsrApiKey(event.target.value);+ }}+ placeholder={t(customAsrEndpointRequiresNewKey+ ? 'settings.voiceInput.serviceSource.customAsr.apiKey.placeholder'+ : customAsrApiKeyConfigured+ ? 'settings.voiceInput.serviceSource.customAsr.apiKey.savedPlaceholder'+ : 'settings.voiceInput.serviceSource.customAsr.apiKey.placeholder')}+ maxLength={MAX_CUSTOM_ASR_API_KEY_CHARS}+ spellCheck={false}+ autoComplete="new-password"+ className={cn(+ 'h-9 w-full rounded-full border px-3 text-13 outline-none transition-colors',+ 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] text-[var(--settings-input-text)]',+ 'placeholder:text-[var(--settings-section-sublabel)] placeholder:opacity-55',+ 'focus:border-[var(--settings-input-border-focus)]',+ )}+ />+ </VoiceInputInlineSettingRow>++ <div className="flex flex-wrap justify-end gap-2">+ {customAsrApiKeyConfigured ? (+ <button+ type="button"+ disabled={saving}+ onClick={() => void clearCustomAsrApiKey()}+ className={cn(+ 'h-8 rounded-full border px-3 text-12 outline-none transition-colors',+ 'border-[var(--settings-input-border)] text-[var(--settings-section-sublabel)]',+ 'hover:border-[var(--settings-input-border-focus)] focus-visible:border-[var(--settings-input-border-focus)]',+ saving && 'cursor-not-allowed opacity-55',+ )}+ >+ {t('settings.voiceInput.serviceSource.customAsr.apiKey.clear')}+ </button>+ ) : null}+ <button+ type="button"+ disabled={saving || !customAsrCanSave}+ onClick={() => void handleSaveCustomAsr()}+ className={cn(+ 'h-8 rounded-full border px-3 text-12 font-medium outline-none transition-colors',+ 'border-[var(--settings-input-border-focus)] bg-[var(--settings-btn-primary-bg)] text-[var(--settings-btn-primary-text)]',+ 'hover:opacity-90 focus-visible:ring-2 focus-visible:ring-[var(--settings-input-border-focus)]',+ (saving || !customAsrCanSave) && 'cursor-not-allowed opacity-55',+ )}+ >+ {t('settings.voiceInput.serviceSource.customAsr.save')}+ </button>+ </div>+ </div>+ ) : null}+<VoiceInputInlineSettingRowlabel={t('settings.voiceInput.serviceSource.refiner.label')}hint={t('settings.voiceInput.serviceSource.refiner.hint')}@@ -521,7 +868,7 @@ function VoiceInputServiceSourceCard() {<p className="min-w-0 text-12 leading-[1.4] text-[var(--error-fg)]">{byokCredentialErrorText}</p>- <button+ {!credentialRecoveryInVoiceSettings ? <buttontype="button"onClick={openProvidersTab}className={cn(@@ -532,7 +879,7 @@ function VoiceInputServiceSourceCard() {)}>{t('settings.voiceInput.serviceSource.manageProviders')}- </button>+ </button> : null}</div>) : null}</>diff --git a/apps/desktop/src/renderer/hooks/useVoiceInputModelSelection.ts b/apps/desktop/src/renderer/hooks/useVoiceInputModelSelection.tsindex faba49e9ec..a86dcaab62 100644--- a/apps/desktop/src/renderer/hooks/useVoiceInputModelSelection.ts+++ b/apps/desktop/src/renderer/hooks/useVoiceInputModelSelection.ts@@ -24,11 +24,18 @@ export function useVoiceInputModelSelection(): {asrProfiles: ModelSelectionResult['asrProfiles'];refinerProfiles: ModelSelectionResult['refinerProfiles'];readiness: ModelSelectionResult['readiness'] | null;+ customAsrApiKeyConfigured: boolean;saving: boolean;setServiceMode: (mode: VoiceInputServiceModeData) => Promise<void>;setAsrProvider: (provider: string) => Promise<void>;setRefinerProvider: (provider: string) => Promise<void>;setRefinerFallbackProvider: (provider: string) => Promise<void>;+ saveCustomAsr: (config: {+ protocol: 'openai-realtime' | 'qwen-realtime';+ websocketUrl: string;+ model: string;+ }, apiKey?: string) => Promise<boolean>;+ clearCustomAsrApiKey: () => Promise<void>;resetToDefault: () => Promise<void>;refresh: () => Promise<void>;} {@@ -64,12 +71,14 @@ export function useVoiceInputModelSelection(): {try {const next = await window.electronAPI.voiceInput.setModelSelection(patch);if (mountedRef.current) setResult(next);+ return true;} catch (error) {const message = error instanceof Error ? error.message : String(error);log.warn('voice input model selection save failed', { message });toast.error(t('settings.voiceInput.saveFailed', { message }));// Re-sync so the UI never renders an optimistic value main rejected.await refresh();+ return false;} finally {if (mountedRef.current) setSaving(false);}@@ -96,10 +105,30 @@ export function useVoiceInputModelSelection(): {await applyPatch({ refinerProviderChain: provider ? [provider] : null });}, [applyPatch]);+ const saveCustomAsr = useCallback(async (+ config: {+ protocol: 'openai-realtime' | 'qwen-realtime';+ websocketUrl: string;+ model: string;+ },+ apiKey?: string,+ ) => {+ return applyPatch({+ customAsr: config,+ ...(apiKey?.trim() ? { customAsrApiKey: apiKey } : {}),+ });+ }, [applyPatch]);++ const clearCustomAsrApiKey = useCallback(async () => {+ await applyPatch({ customAsrApiKey: null });+ }, [applyPatch]);+const resetToDefault = useCallback(async () => {await applyPatch({serviceMode: null,asrProvider: null,+ customAsr: null,+ customAsrApiKey: null,refinerProvider: null,refinerModel: null,refinerProviderChain: null,@@ -112,11 +141,14 @@ export function useVoiceInputModelSelection(): {asrProfiles: result?.asrProfiles ?? [],refinerProfiles: result?.refinerProfiles ?? [],readiness: result?.readiness ?? null,+ customAsrApiKeyConfigured: result?.customAsrApiKeyConfigured ?? false,saving,setServiceMode,setAsrProvider,setRefinerProvider,setRefinerFallbackProvider,+ saveCustomAsr,+ clearCustomAsrApiKey,resetToDefault,refresh,};diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 1d7732bf5e..41d57c99e2 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -715,22 +715,38 @@},"serviceSource": {"label": "Voice service",- "hint": "Uses the Cindy voice service by default; switch to your own key and models if you prefer.",- "localHint": "Local mode does not use Cindy account services; configure your own key and models.",+ "hint": "Uses the Cindy voice service by default. You can instead connect a realtime ASR service with separate voice credentials.",+ "localHint": "Local mode does not use Cindy account services; connect a realtime ASR service with separate voice credentials.","ariaLabel": "Voice service source","options": {"cindy": "Cindy official service",- "byok": "Custom (your own key)"+ "byok": "Custom voice service"},"optionDescriptions": {"cindy": "Uses your Cindy sign-in, no keys to configure",- "byok": "Uses your own keys and models, billed to your account"+ "byok": "Uses an ASR-capable service and its own voice credentials"},"asr": {"label": "Recognition model","hint": "ASR model used for speech-to-text.","ariaLabel": "Speech recognition model"},+ "connectionTest": {+ "action": "Test connection",+ "testing": "Testing",+ "testingStatus": "Connecting to the selected realtime ASR service…",+ "success": "Connected. The selected realtime ASR route is available.",+ "saveBeforeTest": "Save the custom ASR changes before testing the connection.",+ "failure": {+ "credentialsMissing": "Required credentials are missing. Complete the setup first.",+ "authenticationFailed": "Authentication failed. Check the credentials for this service.",+ "routeUnavailable": "The AI gateway does not support or has not enabled this realtime ASR route.",+ "timeout": "Connection timed out. Check the network and service status, then try again.",+ "network": "Could not connect. Check the network, address, and certificate settings.",+ "serviceError": "The service handshake failed. Try again later or check the service setup.",+ "unsupportedProvider": "Connection testing is not supported for this recognition model."+ }+ },"refiner": {"label": "Refinement model","hint": "Model used to clean up dictated text.",@@ -743,15 +759,52 @@"none": "No fallback","noneDescription": "Keep the raw transcript when the primary model fails"},+ "customAsr": {+ "optionLabel": "Custom realtime ASR",+ "optionDescription": "Uses a dedicated speech-recognition WebSocket and API key",+ "notice": "Enter the complete WebSocket address from an ASR-capable service. Cindy will not reuse or append paths to your chat model endpoint.",+ "protocol": {+ "label": "Realtime protocol",+ "hint": "Choose the message format implemented by the ASR service.",+ "ariaLabel": "Custom realtime ASR protocol",+ "openai": "OpenAI transcription",+ "qwen": "Qwen realtime ASR"+ },+ "websocketUrl": {+ "label": "WebSocket URL",+ "hint": "A complete wss:// URL. Local loopback services may use ws://.",+ "placeholder": "wss://asr.example.com/v1/realtime",+ "invalid": "Enter a valid wss:// URL without embedded credentials. Only local loopback services may use ws://."+ },+ "model": {+ "label": "ASR model",+ "hint": "The exact speech-recognition model accepted by this service.",+ "placeholder": "Speech-recognition model ID"+ },+ "apiKey": {+ "label": "ASR API key",+ "hint": "Stored locally with system encryption and used only for this voice service.",+ "savedHint": "A key is stored locally. Leave this field blank to keep it.",+ "endpointChangedHint": "The service origin changed. Enter a new key, or remove the saved key before saving.",+ "placeholder": "Enter the ASR API key",+ "savedPlaceholder": "Key saved — enter a new value to replace it",+ "clear": "Remove key"+ },+ "save": "Save voice service"+ },"credential": {- "gatewayKey": "Uses your AI gateway key",+ "gatewayKey": "Requires your AI gateway to support this realtime ASR route","codexLogin": "Uses your Codex sign-in",- "elevenlabsKey": "Uses your ElevenLabs key (environment variable)"+ "elevenlabsKey": "Uses your ElevenLabs key (environment variable)",+ "codexRealtimeUnsupported": "Unavailable: Codex sign-in is not an OpenAI API Realtime credential"},"credentialError": {"gatewayMissing": "No AI gateway key found; this model is unavailable.","codexMissing": "Codex is not signed in; this model is unavailable.",- "elevenlabsMissing": "No ElevenLabs key configured (environment variable); this model is unavailable."+ "elevenlabsMissing": "No ElevenLabs key configured (environment variable); this model is unavailable.",+ "customAsrConfigMissing": "Complete and save the realtime ASR service settings before starting voice input.",+ "customAsrKeyMissing": "Add and save an API key for the custom realtime ASR service.",+ "codexRealtimeUnsupported": "Codex sign-in cannot be used for realtime speech recognition. Choose a supported ASR service."},"manageProviders": "Open model providers","reset": "Reset to default"@@ -2045,6 +2098,7 @@"prefs": {"agentLabel": "Agent","modelLabel": "Model",+ "effortLabel": "Reasoning effort","permissionLabel": "Permission mode","providerSlack": "Slack","providerTelegram": "Telegram",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex ff34f08203..a287be31a5 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -715,22 +715,38 @@},"serviceSource": {"label": "音声サービス",- "hint": "既定では Cindy 提供の音声サービスを使用します。自分のキーとモデルに切り替えることもできます。",- "localHint": "ローカルモードでは Cindy アカウントサービスを使用しません。自分のキーとモデルを設定してください。",+ "hint": "既定では Cindy 音声サービスを使用します。リアルタイム ASR 対応サービスと専用の音声認証情報に切り替えることもできます。",+ "localHint": "ローカルモードでは Cindy アカウントサービスを使用しません。リアルタイム ASR 対応サービスと専用の音声認証情報を設定してください。","ariaLabel": "音声サービスソースの選択","options": {"cindy": "Cindy 公式サービス",- "byok": "カスタム(自分のキー)"+ "byok": "カスタム音声サービス"},"optionDescriptions": {"cindy": "Cindy のログイン情報を使用し、キーの設定は不要です",- "byok": "自分のキーとモデルを使用し、費用は自分のアカウントに計上されます"+ "byok": "ASR 対応サービスと専用の音声認証情報を使用します"},"asr": {"label": "認識モデル","hint": "音声をテキストに変換する ASR モデル。","ariaLabel": "音声認識モデルの選択"},+ "connectionTest": {+ "action": "接続をテスト",+ "testing": "テスト中",+ "testingStatus": "選択したリアルタイム ASR サービスに接続しています…",+ "success": "接続に成功しました。選択したリアルタイム ASR ルートを利用できます。",+ "saveBeforeTest": "接続をテストする前に、カスタム ASR の変更を保存してください。",+ "failure": {+ "credentialsMissing": "必要な認証情報がありません。先に設定を完了してください。",+ "authenticationFailed": "認証に失敗しました。このサービスの認証情報を確認してください。",+ "routeUnavailable": "AI ゲートウェイがこのリアルタイム ASR ルートをサポートしていないか、有効にしていません。",+ "timeout": "接続がタイムアウトしました。ネットワークとサービスの状態を確認して再試行してください。",+ "network": "サービスに接続できません。ネットワーク、アドレス、証明書の設定を確認してください。",+ "serviceError": "サービスとのハンドシェイクに失敗しました。後でもう一度試すか、サービス設定を確認してください。",+ "unsupportedProvider": "この認識モデルでは接続テストを利用できません。"+ }+ },"refiner": {"label": "整えモデル","hint": "話し言葉のテキストを整えるモデル。",@@ -743,15 +759,52 @@"none": "フォールバックなし","noneDescription": "メインモデルが失敗した場合は元の認識テキストを保持"},+ "customAsr": {+ "optionLabel": "カスタムリアルタイム ASR",+ "optionDescription": "専用の音声認識 WebSocket と API キーを使用",+ "notice": "ASR 対応サービスが提供する完全な WebSocket URL を入力してください。Cindy はチャットモデルの URL を再利用せず、音声用パスも追加しません。",+ "protocol": {+ "label": "リアルタイムプロトコル",+ "hint": "ASR サービスが実装しているメッセージ形式を選択します。",+ "ariaLabel": "カスタムリアルタイム ASR プロトコル",+ "openai": "OpenAI 文字起こし",+ "qwen": "Qwen リアルタイム ASR"+ },+ "websocketUrl": {+ "label": "WebSocket URL",+ "hint": "完全な wss:// URL。ローカルのループバックサービスでは ws:// も使用できます。",+ "placeholder": "wss://asr.example.com/v1/realtime",+ "invalid": "認証情報を含まない有効な wss:// URL を入力してください。ws:// はローカルのループバックサービスだけで使用できます。"+ },+ "model": {+ "label": "ASR モデル",+ "hint": "サービスが受け付ける音声認識モデル ID を入力します。",+ "placeholder": "音声認識モデル ID"+ },+ "apiKey": {+ "label": "ASR API キー",+ "hint": "システム暗号化でローカルに保存し、この音声サービスだけに使用します。",+ "savedHint": "キーはローカルに保存されています。空欄のままなら変更しません。",+ "endpointChangedHint": "接続先のオリジンが変更されました。新しいキーを入力するか、保存済みのキーを削除してから保存してください。",+ "placeholder": "ASR API キーを入力",+ "savedPlaceholder": "キーは保存済みです。新しい値で置き換えられます",+ "clear": "キーを削除"+ },+ "save": "音声サービスを保存"+ },"credential": {- "gatewayKey": "AI ゲートウェイキーを使用",+ "gatewayKey": "AI ゲートウェイが選択したリアルタイム ASR ルートに対応している必要があります","codexLogin": "Codex ログインを使用",- "elevenlabsKey": "ElevenLabs キーを使用(環境変数)"+ "elevenlabsKey": "ElevenLabs キーを使用(環境変数)",+ "codexRealtimeUnsupported": "利用不可:Codex ログインは OpenAI API Realtime の認証情報ではありません"},"credentialError": {"gatewayMissing": "利用可能な AI ゲートウェイキーが見つからないため、このモデルは使用できません。","codexMissing": "Codex にログインしていないため、このモデルは使用できません。",- "elevenlabsMissing": "ElevenLabs キー(環境変数)が未設定のため、このモデルは使用できません。"+ "elevenlabsMissing": "ElevenLabs キー(環境変数)が未設定のため、このモデルは使用できません。",+ "customAsrConfigMissing": "音声入力を開始する前に、リアルタイム ASR サービスの設定をすべて入力して保存してください。",+ "customAsrKeyMissing": "カスタムリアルタイム ASR サービスの API キーを入力して保存してください。",+ "codexRealtimeUnsupported": "Codex ログインはリアルタイム音声認識には使用できません。対応する ASR サービスを選択してください。"},"manageProviders": "モデルプロバイダーを開く","reset": "既定に戻す"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 1669c753b8..218c27d6a6 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -715,22 +715,38 @@},"serviceSource": {"label": "음성 서비스",- "hint": "기본적으로 Cindy가 제공하는 음성 서비스를 사용합니다. 자신의 키와 모델로 전환할 수도 있습니다.",- "localHint": "로컬 모드에서는 Cindy 계정 서비스를 사용하지 않습니다. 자신의 키와 모델을 설정하세요.",+ "hint": "기본적으로 Cindy 음성 서비스를 사용합니다. 실시간 ASR 지원 서비스와 별도의 음성 인증 정보로 전환할 수도 있습니다.",+ "localHint": "로컬 모드에서는 Cindy 계정 서비스를 사용하지 않습니다. 실시간 ASR 지원 서비스와 별도의 음성 인증 정보를 설정하세요.","ariaLabel": "음성 서비스 소스 선택","options": {"cindy": "Cindy 공식 서비스",- "byok": "사용자 지정(내 키 사용)"+ "byok": "사용자 지정 음성 서비스"},"optionDescriptions": {"cindy": "Cindy 로그인 정보를 사용하며 키 설정이 필요 없습니다",- "byok": "자신의 키와 모델을 사용하며 비용은 내 계정으로 청구됩니다"+ "byok": "ASR 지원 서비스와 별도의 음성 인증 정보를 사용합니다"},"asr": {"label": "인식 모델","hint": "음성을 텍스트로 변환하는 ASR 모델.","ariaLabel": "음성 인식 모델 선택"},+ "connectionTest": {+ "action": "연결 테스트",+ "testing": "테스트 중",+ "testingStatus": "선택한 실시간 ASR 서비스에 연결하는 중…",+ "success": "연결되었습니다. 선택한 실시간 ASR 경로를 사용할 수 있습니다.",+ "saveBeforeTest": "연결을 테스트하기 전에 사용자 지정 ASR 변경 사항을 저장하세요.",+ "failure": {+ "credentialsMissing": "필요한 인증 정보가 없습니다. 먼저 설정을 완료하세요.",+ "authenticationFailed": "인증에 실패했습니다. 이 서비스의 인증 정보를 확인하세요.",+ "routeUnavailable": "AI 게이트웨이가 이 실시간 ASR 경로를 지원하지 않거나 활성화하지 않았습니다.",+ "timeout": "연결 시간이 초과되었습니다. 네트워크와 서비스 상태를 확인한 후 다시 시도하세요.",+ "network": "서비스에 연결할 수 없습니다. 네트워크, 주소 및 인증서 설정을 확인하세요.",+ "serviceError": "서비스 핸드셰이크에 실패했습니다. 나중에 다시 시도하거나 서비스 설정을 확인하세요.",+ "unsupportedProvider": "이 인식 모델은 연결 테스트를 지원하지 않습니다."+ }+ },"refiner": {"label": "정리 모델","hint": "구어체 텍스트를 정리하는 모델.",@@ -743,15 +759,52 @@"none": "대체 모델 없음","noneDescription": "기본 모델이 실패하면 원본 인식 텍스트를 유지"},+ "customAsr": {+ "optionLabel": "사용자 지정 실시간 ASR",+ "optionDescription": "전용 음성 인식 WebSocket과 API 키 사용",+ "notice": "ASR 지원 서비스에서 제공하는 전체 WebSocket 주소를 입력하세요. Cindy는 채팅 모델 주소를 재사용하거나 음성 경로를 자동으로 추가하지 않습니다.",+ "protocol": {+ "label": "실시간 프로토콜",+ "hint": "ASR 서비스가 구현한 메시지 형식을 선택하세요.",+ "ariaLabel": "사용자 지정 실시간 ASR 프로토콜",+ "openai": "OpenAI 전사",+ "qwen": "Qwen 실시간 ASR"+ },+ "websocketUrl": {+ "label": "WebSocket URL",+ "hint": "전체 wss:// URL입니다. 로컬 루프백 서비스는 ws://를 사용할 수 있습니다.",+ "placeholder": "wss://asr.example.com/v1/realtime",+ "invalid": "인증 정보가 포함되지 않은 올바른 wss:// URL을 입력하세요. ws://는 로컬 루프백 서비스에서만 사용할 수 있습니다."+ },+ "model": {+ "label": "ASR 모델",+ "hint": "서비스가 허용하는 정확한 음성 인식 모델 ID를 입력하세요.",+ "placeholder": "음성 인식 모델 ID"+ },+ "apiKey": {+ "label": "ASR API 키",+ "hint": "시스템 암호화로 로컬에 저장되며 이 음성 서비스에만 사용됩니다.",+ "savedHint": "키가 로컬에 저장되어 있습니다. 비워 두면 기존 키를 유지합니다.",+ "endpointChangedHint": "서비스 주소의 출처가 변경되었습니다. 새 키를 입력하거나 저장된 키를 제거한 후 저장하세요.",+ "placeholder": "ASR API 키 입력",+ "savedPlaceholder": "키 저장됨 — 새 값을 입력하면 교체됩니다",+ "clear": "키 삭제"+ },+ "save": "음성 서비스 저장"+ },"credential": {- "gatewayKey": "AI 게이트웨이 키 사용",+ "gatewayKey": "AI 게이트웨이가 선택한 실시간 ASR 경로를 지원해야 합니다","codexLogin": "Codex 로그인 사용",- "elevenlabsKey": "ElevenLabs 키 사용(환경 변수)"+ "elevenlabsKey": "ElevenLabs 키 사용(환경 변수)",+ "codexRealtimeUnsupported": "사용 불가: Codex 로그인은 OpenAI API Realtime 인증 정보가 아닙니다"},"credentialError": {"gatewayMissing": "사용 가능한 AI 게이트웨이 키가 없어 이 모델을 사용할 수 없습니다.","codexMissing": "Codex에 로그인하지 않아 이 모델을 사용할 수 없습니다.",- "elevenlabsMissing": "ElevenLabs 키(환경 변수)가 설정되지 않아 이 모델을 사용할 수 없습니다."+ "elevenlabsMissing": "ElevenLabs 키(환경 변수)가 설정되지 않아 이 모델을 사용할 수 없습니다.",+ "customAsrConfigMissing": "음성 입력을 시작하기 전에 실시간 ASR 서비스 설정을 모두 입력하고 저장하세요.",+ "customAsrKeyMissing": "사용자 지정 실시간 ASR 서비스의 API 키를 입력하고 저장하세요.",+ "codexRealtimeUnsupported": "Codex 로그인은 실시간 음성 인식에 사용할 수 없습니다. 지원되는 ASR 서비스를 선택하세요."},"manageProviders": "모델 제공자 열기","reset": "기본값으로 복원"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 369d6c62be..22637b24a0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -715,22 +715,38 @@},"serviceSource": {"label": "语音服务",- "hint": "默认使用 Cindy 提供的语音服务;也可以切换为自己的 Key 与模型。",- "localHint": "本地模式不使用 Cindy 账号服务;请配置自己的 Key 与模型。",+ "hint": "默认使用 Cindy 语音服务;也可以连接支持实时 ASR 的服务,并使用独立的语音凭证。",+ "localHint": "本地模式不使用 Cindy 账号服务;请连接支持实时 ASR 的服务并配置独立语音凭证。","ariaLabel": "语音服务来源选择","options": {"cindy": "Cindy 官方服务",- "byok": "自定义(用自己的 Key)"+ "byok": "自定义语音服务"},"optionDescriptions": {"cindy": "使用 Cindy 账号登录态,无需配置任何密钥",- "byok": "使用你自己的密钥与模型,费用计入你的账户"+ "byok": "使用具备 ASR 能力的服务及其独立语音凭证"},"asr": {"label": "识别模型","hint": "语音转文字使用的 ASR 模型。","ariaLabel": "语音识别模型选择"},+ "connectionTest": {+ "action": "测试连接",+ "testing": "测试中",+ "testingStatus": "正在连接所选实时 ASR 服务…",+ "success": "连接成功,所选实时 ASR 路由可用。",+ "saveBeforeTest": "请先保存自定义 ASR 的修改,再测试连接。",+ "failure": {+ "credentialsMissing": "缺少所需凭证,请先完成配置。",+ "authenticationFailed": "鉴权失败,请检查当前服务的凭证。",+ "routeUnavailable": "AI 网关不支持或未启用所选实时 ASR 路由。",+ "timeout": "连接超时,请检查网络和服务状态后重试。",+ "network": "无法连接服务,请检查网络、地址和证书配置。",+ "serviceError": "服务握手失败,请稍后重试或检查服务配置。",+ "unsupportedProvider": "当前识别模型不支持连接测试。"+ }+ },"refiner": {"label": "润色模型","hint": "整理口语文本使用的模型。",@@ -743,15 +759,52 @@"none": "不使用备选","noneDescription": "主模型失败时直接保留原始识别文本"},+ "customAsr": {+ "optionLabel": "自定义实时 ASR",+ "optionDescription": "使用独立的语音识别 WebSocket 和 API Key",+ "notice": "请填写 ASR 服务提供的完整 WebSocket 地址。Cindy 不会复用对话模型地址,也不会自动拼接语音路径。",+ "protocol": {+ "label": "实时协议",+ "hint": "请选择 ASR 服务实际实现的消息格式。",+ "ariaLabel": "自定义实时 ASR 协议",+ "openai": "OpenAI 转写协议",+ "qwen": "Qwen 实时 ASR"+ },+ "websocketUrl": {+ "label": "WebSocket 地址",+ "hint": "填写完整的 wss:// 地址;本机回环服务可以使用 ws://。",+ "placeholder": "wss://asr.example.com/v1/realtime",+ "invalid": "请输入不包含凭证的有效 wss:// 地址;只有本机回环服务可以使用 ws://。"+ },+ "model": {+ "label": "ASR 模型",+ "hint": "填写该服务实际接受的语音识别模型 ID。",+ "placeholder": "语音识别模型 ID"+ },+ "apiKey": {+ "label": "ASR API Key",+ "hint": "使用系统加密保存在本机,仅供这个语音服务使用。",+ "savedHint": "本机已保存 Key;留空可保持不变。",+ "endpointChangedHint": "服务地址已切换到新的来源。请填写新的 Key,或先移除已保存的 Key。",+ "placeholder": "输入 ASR API Key",+ "savedPlaceholder": "Key 已保存;输入新值可替换",+ "clear": "移除 Key"+ },+ "save": "保存语音服务"+ },"credential": {- "gatewayKey": "使用 AI 网关 Key",+ "gatewayKey": "需要 AI 网关支持所选实时 ASR 路由","codexLogin": "使用 Codex 登录",- "elevenlabsKey": "使用 ElevenLabs Key(环境变量)"+ "elevenlabsKey": "使用 ElevenLabs Key(环境变量)",+ "codexRealtimeUnsupported": "不可用:Codex 登录不是 OpenAI API Realtime 凭证"},"credentialError": {"gatewayMissing": "未找到可用的 AI 网关 Key,当前模型无法使用。","codexMissing": "Codex 未登录,当前模型无法使用。",- "elevenlabsMissing": "未配置 ElevenLabs Key(环境变量),当前模型无法使用。"+ "elevenlabsMissing": "未配置 ElevenLabs Key(环境变量),当前模型无法使用。",+ "customAsrConfigMissing": "请先完整填写并保存实时 ASR 服务配置,再开始语音输入。",+ "customAsrKeyMissing": "请为自定义实时 ASR 服务填写并保存 API Key。",+ "codexRealtimeUnsupported": "Codex 登录不能用于实时语音识别,请选择受支持的 ASR 服务。"},"manageProviders": "前往模型供应商","reset": "恢复默认"diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex eb6a6d305d..3a1e3e5f91 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -15,6 +15,8 @@ type AnalyticsSettingsPayload = import('../shared/analyticsSettings').AnalyticsStype RsbWindowCommand = import('../shared/rightSidebarWindow').RsbWindowCommand;type VoiceInputPowerStatePayload =import('../shared/voiceInputPowerIpc').VoiceInputPowerStatePayload;+type VoiceInputConnectionTestResult =+ import('../shared/voiceInputConnectionTest').VoiceInputConnectionTestResult;type DesktopLoginAction = import('../shared/authIpc').DesktopLoginAction;type DesktopLoginActionResult = import('../shared/authIpc').DesktopLoginActionResult;type UtilityTextFailure = import('../shared/utilityTextResult').UtilityTextFailure;@@ -183,6 +185,13 @@ type VoiceInputModelSelectionResultData = {serviceMode: VoiceInputServiceModeData;serviceModeConfigured: boolean;asrProvider: VoiceInputProviderKindData;+ asrProviderChain: VoiceInputProviderKindData[];+ asrProviderChainSource: 'default' | 'configured';+ customAsr?: {+ protocol: 'openai-realtime' | 'qwen-realtime';+ websocketUrl: string;+ model: string;+ };refinerProvider: VoiceInputRefinerProviderKindData;refinerModel?: string;/** Effective refiner chain, head first; length 1 = no fallback (BYOK default). */@@ -209,7 +218,9 @@ type VoiceInputModelSelectionResultData = {auth: 'api-key' | 'codex';settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;+ failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';};+ customAsrApiKeyConfigured: boolean;};type LocalThemeOpenDirResult = import('../shared/local-themes').LocalThemeOpenDirResult;type LocalThemesResult = import('../shared/local-themes').LocalThemesResult;@@ -1261,9 +1272,12 @@ interface ElectronAPI {openInputMonitoringSettings: () => Promise<VoiceInputGlobalResult>;muteSystemAudio: () => Promise<{ ok: true } | { ok: false; error: string }>;restoreSystemAudio: () => Promise<{ ok: true } | { ok: false; error: string }>;+ testConnection: () => Promise<VoiceInputConnectionTestResult>;getReadiness: () => Promise<{ok: boolean;+ serviceMode: VoiceInputServiceModeData;provider:+ | 'custom-realtime-asr'| 'elevenlabs-scribe-realtime'| 'openai-realtime-whisper'| 'litellm-gpt-realtime-whisper'@@ -1275,11 +1289,14 @@ interface ElectronAPI {settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;authErrorReason?: string;+ failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';}>;getReadinessCached: () =>| {ok: boolean;+ serviceMode: VoiceInputServiceModeData;provider:+ | 'custom-realtime-asr'| 'elevenlabs-scribe-realtime'| 'openai-realtime-whisper'| 'litellm-gpt-realtime-whisper'@@ -1291,6 +1308,7 @@ interface ElectronAPI {settingsTab: 'api-keys' | 'connections' | 'providers';error?: string;authErrorReason?: string;+ failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';}| null;getModelSelection: () => Promise<VoiceInputModelSelectionResultData>;@@ -1299,6 +1317,12 @@ interface ElectronAPI {asrProvider?: string | null;refinerProvider?: string | null;refinerModel?: string | null;+ customAsr?: {+ protocol: 'openai-realtime' | 'qwen-realtime';+ websocketUrl: string;+ model: string;+ } | null;+ customAsrApiKey?: string | null;/** BYOK fallback tail; null clears the override (primary runs alone). */refinerProviderChain?: string[] | null;}) => Promise<VoiceInputModelSelectionResultData>;diff --git a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsxindex 344957d610..f09a4681a0 100644--- a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx+++ b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx@@ -502,15 +502,15 @@ export function VoiceInputOverlay() {log.warn('global voice input start failed:', message);await stopEngine();await restoreSystemAudioForRecording();- const modelSelection = await window.electronAPI.voiceInput.getModelSelection().catch((selectionError) => {+ const readiness = await window.electronAPI.voiceInput.getReadiness().catch((readinessError) => {log.warn(- 'read voice input model selection after start failure failed:',- selectionError instanceof Error ? selectionError.message : String(selectionError),+ 'read voice input readiness after start failure failed:',+ readinessError instanceof Error ? readinessError.message : String(readinessError),);return null;});- const readinessRecovery = modelSelection && !modelSelection.readiness.ok- ? resolveVoiceInputReadinessRecovery(modelSelection.readiness, modelSelection.selection.serviceMode)+ const readinessRecovery = readiness && !readiness.ok+ ? resolveVoiceInputReadinessRecovery(readiness, readiness.serviceMode): null;if (startAttemptIdRef.current !== failureAttemptId) return;const promptReason = authErrorReason ?? message;diff --git a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.tsindex e1b87153e5..acec081418 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts@@ -26,4 +26,39 @@ describe('VoiceInputSection shortcut recording gate', () => {expect(source).toContain('syncVoiceInputGlobalShortcut(getVoiceInputSettings().shortcut)');expect(source).toContain('}, [recordingShortcut]);');});++ it('clears stale custom ASR form fields when the saved config is removed', () => {+ const source = readFileSync(+ new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),+ 'utf8',+ );++ expect(source).toContain('if (!selection?.customAsr) {');+ expect(source).toContain("setCustomAsrProtocol('openai-realtime')");+ expect(source).toContain("setCustomAsrWebsocketUrl('')");+ expect(source).toContain("setCustomAsrModel('')");+ expect(source).toContain("setCustomAsrApiKey('')");+ });++ it('preserves a dirty custom ASR endpoint and key across unrelated selection refreshes', () => {+ const source = readFileSync(+ new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),+ 'utf8',+ );++ expect(source).toContain('if (customAsrSelected && customAsrFormDirtyRef.current) return;');+ expect(source).toContain('}, [customAsrSelected, selection?.customAsr]);');+ expect(source).toContain('customAsrFormDirtyRef.current = true;');+ });++ it('invalidates a previous connection result when any local custom ASR field changes', () => {+ const source = readFileSync(+ new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),+ 'utf8',+ );++ expect(source).toMatch(+ /setConnectionTest\(\{ status: 'idle' \}\);[\s\S]*customAsrProtocol,[\s\S]*customAsrWebsocketUrl,[\s\S]*customAsrModel,[\s\S]*customAsrApiKey,/,+ );+ });});diff --git a/apps/desktop/src/renderer/voice-input/__tests__/overlayErrors.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/overlayErrors.test.tsindex cec539d9b8..6932db495e 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/overlayErrors.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/overlayErrors.test.ts@@ -9,6 +9,7 @@ describe('voice input overlay error classification', () => {expect(isVoiceInputServiceConnectionError('WebSocket connection timed out')).toBe(true);expect(isVoiceInputServiceConnectionError('fetch failed')).toBe(true);expect(isVoiceInputServiceConnectionError('network socket disconnected before secure TLS connection was established')).toBe(true);+ expect(isVoiceInputServiceConnectionError('unable to verify the first certificate')).toBe(true);});it('does not classify ordinary user-facing errors as service connection errors', () => {diff --git a/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.tsindex b67d19a2f3..8b8bc9dd0b 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts@@ -20,4 +20,10 @@ describe('voice input overlay retry gate', () => {expect(overlaySource).toContain('disabled={stopInFlight}');expect(overlaySource).toContain('if (!text) {\n stateRef.current = \'done\';\n commitUsageStats();');});++ it('uses the overlay-safe readiness IPC to build the recovery action', () => {+ expect(overlaySource).toContain('window.electronAPI.voiceInput.getReadiness()');+ expect(overlaySource).toContain('resolveVoiceInputReadinessRecovery(readiness, readiness.serviceMode)');+ expect(overlaySource).not.toContain('window.electronAPI.voiceInput.getModelSelection()');+ });});diff --git a/apps/desktop/src/renderer/voice-input/__tests__/readinessRecovery.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/readinessRecovery.test.tsindex 8b02c22a5a..af9df9a443 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/readinessRecovery.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/readinessRecovery.test.ts@@ -62,4 +62,50 @@ describe('resolveVoiceInputReadinessRecovery', () => {settingsTab: 'providers',});});++ it('routes incomplete custom ASR setup back to voice input settings', () => {+ expect(+ resolveVoiceInputReadinessRecovery(+ {+ auth: 'api-key',+ provider: 'custom-realtime-asr',+ failureReason: 'custom-asr-config-missing',+ },+ 'byok',+ ),+ ).toEqual({+ messageKey: 'settings.voiceInput.serviceSource.credentialError.customAsrConfigMissing',+ settingsTab: 'voice-input',+ });++ expect(+ resolveVoiceInputReadinessRecovery(+ {+ auth: 'api-key',+ provider: 'custom-realtime-asr',+ failureReason: 'custom-asr-key-missing',+ },+ 'byok',+ ),+ ).toEqual({+ messageKey: 'settings.voiceInput.serviceSource.credentialError.customAsrKeyMissing',+ settingsTab: 'voice-input',+ });+ });++ it('explains why Codex sign-in cannot power realtime ASR', () => {+ expect(+ resolveVoiceInputReadinessRecovery(+ {+ auth: 'codex',+ provider: 'openai-realtime-whisper',+ failureReason: 'codex-realtime-unsupported',+ },+ 'byok',+ ),+ ).toEqual({+ messageKey: 'settings.voiceInput.serviceSource.credentialError.codexRealtimeUnsupported',+ settingsTab: 'voice-input',+ });+ });});diff --git a/apps/desktop/src/renderer/voice-input/overlayErrors.ts b/apps/desktop/src/renderer/voice-input/overlayErrors.tsindex 82df70b841..a6c6967558 100644--- a/apps/desktop/src/renderer/voice-input/overlayErrors.ts+++ b/apps/desktop/src/renderer/voice-input/overlayErrors.ts@@ -1,5 +1,5 @@const VOICE_INPUT_SERVICE_CONNECTION_ERROR_PATTERN =- /\b(ENOTFOUND|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENETUNREACH|EAI_AGAIN)\b|getaddrinfo|network|websocket|timed out|fetch failed/i;+ /\b(ENOTFOUND|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENETUNREACH|EAI_AGAIN|TLS)\b|getaddrinfo|network|websocket|timed out|fetch failed|certificate|self[- ]signed/i;export function isVoiceInputServiceConnectionError(message: string): boolean {return VOICE_INPUT_SERVICE_CONNECTION_ERROR_PATTERN.test(message);diff --git a/apps/desktop/src/renderer/voice-input/readinessRecovery.ts b/apps/desktop/src/renderer/voice-input/readinessRecovery.tsindex 70d127c58d..eb59bc0f99 100644--- a/apps/desktop/src/renderer/voice-input/readinessRecovery.ts+++ b/apps/desktop/src/renderer/voice-input/readinessRecovery.ts@@ -5,13 +5,17 @@ export type VoiceInputReadinessRecovery = {| 'voiceInputOverlay.cindyServiceUnavailable'| 'settings.voiceInput.serviceSource.credentialError.codexMissing'| 'settings.voiceInput.serviceSource.credentialError.elevenlabsMissing'- | 'settings.voiceInput.serviceSource.credentialError.gatewayMissing';+ | 'settings.voiceInput.serviceSource.credentialError.gatewayMissing'+ | 'settings.voiceInput.serviceSource.credentialError.customAsrConfigMissing'+ | 'settings.voiceInput.serviceSource.credentialError.customAsrKeyMissing'+ | 'settings.voiceInput.serviceSource.credentialError.codexRealtimeUnsupported';settingsTab: VoiceInputRecoverySettingsTab;};type VoiceInputReadinessLike = {auth: 'api-key' | 'codex';provider: string;+ failureReason?: 'custom-asr-config-missing' | 'custom-asr-key-missing' | 'codex-realtime-unsupported';};/**@@ -29,6 +33,24 @@ export function resolveVoiceInputReadinessRecovery(settingsTab: 'voice-input',};}+ if (readiness.failureReason === 'custom-asr-config-missing') {+ return {+ messageKey: 'settings.voiceInput.serviceSource.credentialError.customAsrConfigMissing',+ settingsTab: 'voice-input',+ };+ }+ if (readiness.failureReason === 'custom-asr-key-missing') {+ return {+ messageKey: 'settings.voiceInput.serviceSource.credentialError.customAsrKeyMissing',+ settingsTab: 'voice-input',+ };+ }+ if (readiness.failureReason === 'codex-realtime-unsupported') {+ return {+ messageKey: 'settings.voiceInput.serviceSource.credentialError.codexRealtimeUnsupported',+ settingsTab: 'voice-input',+ };+ }if (readiness.auth === 'codex') {return {messageKey: 'settings.voiceInput.serviceSource.credentialError.codexMissing',diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.tsindex 4bdd2ba6ad..aa6cb1bc91 100644--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts@@ -59,6 +59,7 @@ import { resolveVoiceInputStartGuards } from './startGuards';import { getVoiceInputWorkletUrl } from './workletUrl';import { buildRefinementPreviewText } from './refinementPreviewText';import { isVoiceInputEventScopeActive, shouldHandleVoiceInputEvent } from './eventScope';+import { isVoiceInputServiceConnectionError } from './overlayErrors';import {VOICE_INPUT_DICTIONARY_LEARNING_TRACK_TIMEOUT_MS,} from '../../shared/voiceInputDictionaryLearning';@@ -372,6 +373,12 @@ export function useVoiceInput(return message;}, [t]);+ const formatVoiceInputStartError = useCallback((message: string): string => {+ return isVoiceInputServiceConnectionError(message)+ ? t('voiceInputOverlay.asrServiceUnavailable')+ : message;+ }, [t]);+const appendAudioChunk = useCallback((chunk: PcmChunk) => {sentAudioMsRef.current += chunk.trace.durationMs;window.electronAPI.voiceInput.appendAudio(chunk);@@ -1189,7 +1196,18 @@ export function useVoiceInput(return;}if (!guards.readiness.ok) {- const readinessError = guards.readiness.error ?? 'Voice input is not configured.';+ let readinessError = guards.readiness.error ?? 'Voice input is not configured.';+ switch (guards.readiness.failureReason) {+ case 'custom-asr-config-missing':+ readinessError = t('settings.voiceInput.serviceSource.credentialError.customAsrConfigMissing');+ break;+ case 'custom-asr-key-missing':+ readinessError = t('settings.voiceInput.serviceSource.credentialError.customAsrKeyMissing');+ break;+ case 'codex-realtime-unsupported':+ readinessError = t('settings.voiceInput.serviceSource.credentialError.codexRealtimeUnsupported');+ break;+ }const authErrorReason = guards.readiness.authErrorReason;if (guards.readiness.auth === 'codex' && authErrorReason && isCodexSessionExpiredError(authErrorReason)) {promptCodexSessionExpired(authErrorReason);@@ -1314,7 +1332,7 @@ export function useVoiceInput(insertionRangeRef.current = null;setVoiceState('error');promptCodexSessionExpired(result.authErrorReason ?? result.error);- reportVoiceInputError(result.error);+ reportVoiceInputError(formatVoiceInputStartError(result.error));restoreEditorFocusAfterVoiceInput();return;}@@ -1345,6 +1363,7 @@ export function useVoiceInput(createStartReadyState,disabled,failActiveRecording,+ formatVoiceInputStartError,formatMicrophoneFallbackMessage,formatMicrophoneStartError,invalidateStartAttempt,@@ -1357,6 +1376,7 @@ export function useVoiceInput(restoreSystemAudioForRecording,setVoiceState,stopEngine,+ t,voiceInputSettings.language,voiceInputSettings.microphoneDeviceId,voiceInputSettings.fastActivationEnabled,@@ -1440,7 +1460,7 @@ export function useVoiceInput(resolveStopCompletion();setVoiceState('error');promptCodexSessionExpired(startResult.authErrorReason ?? startResult.error);- reportVoiceInputError(startResult.error);+ reportVoiceInputError(formatVoiceInputStartError(startResult.error));restoreEditorFocusAfterVoiceInput();throw new Error(startResult.error);}@@ -1504,7 +1524,7 @@ export function useVoiceInput(setVoiceState('done');restoreEditorFocusAfterVoiceInput();}- }, [commitUsageStats, dismissInlineError, drainAndStopEngine, drainQueuedAudioToMain, invalidateStartAttempt, reportVoiceInputError, resolveStopCompletion, restoreEditorFocusAfterVoiceInput, restoreSystemAudioAndNotifyEndCue, setVoiceState, waitForBusyCompletion, waitForStartReadyWhileStopping]);+ }, [commitUsageStats, dismissInlineError, drainAndStopEngine, drainQueuedAudioToMain, formatVoiceInputStartError, invalidateStartAttempt, reportVoiceInputError, resolveStopCompletion, restoreEditorFocusAfterVoiceInput, restoreSystemAudioAndNotifyEndCue, setVoiceState, waitForBusyCompletion, waitForStartReadyWhileStopping]);const stopWithGate = useCallback(async (options?: VoiceInputStopOptions) => {if (stopInFlightPromiseRef.current) return stopInFlightPromiseRef.current;diff --git a/apps/desktop/src/shared/__tests__/voiceInputCustomAsr.test.ts b/apps/desktop/src/shared/__tests__/voiceInputCustomAsr.test.tsnew file mode 100644index 0000000000..248d2e04df--- /dev/null+++ b/apps/desktop/src/shared/__tests__/voiceInputCustomAsr.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';++import { validateVoiceInputCustomAsrWebsocketUrl } from '../voiceInputCustomAsr.js';++describe('custom ASR WebSocket URL validation', () => {+ it.each(['sig', 'signature', 'password', 'X-Amz-Signature'])(+ 'rejects credential query parameter %s',+ (key) => {+ expect(validateVoiceInputCustomAsrWebsocketUrl(`wss://asr.example.test/stream?${key}=secret`))+ .toContain('unsupported query parameters');+ },+ );++ it('allows known non-secret protocol and tenant routing query parameters', () => {+ expect(validateVoiceInputCustomAsrWebsocketUrl(+ 'wss://asr.example.test/stream?model=qwen3-asr-flash-realtime&intent=transcription&tenant=one',+ )).toBeNull();+ });++ it('rejects unknown and signed URL query parameters', () => {+ expect(validateVoiceInputCustomAsrWebsocketUrl(+ 'wss://asr.example.test/stream?X-Goog-Signature=secret',+ )).toContain('unsupported query parameters');+ expect(validateVoiceInputCustomAsrWebsocketUrl(+ 'wss://asr.example.test/stream?custom-routing=value',+ )).toContain('unsupported query parameters');+ });++ it('allows loopback ws IPv6 literals', () => {+ expect(validateVoiceInputCustomAsrWebsocketUrl('ws://[::1]/stream')).toBeNull();+ });++ it('allows valid loopback IPv4 and rejects out-of-range octets', () => {+ expect(validateVoiceInputCustomAsrWebsocketUrl('ws://127.0.0.1/stream')).toBeNull();+ expect(validateVoiceInputCustomAsrWebsocketUrl('ws://127.255.255.255/stream')).toBeNull();+ expect(validateVoiceInputCustomAsrWebsocketUrl('ws://127.999.999.999/stream')).not.toBeNull();+ });+});diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.tsindex e298a157e1..7b32a796c2 100644--- a/apps/desktop/src/shared/providerSecrets.ts+++ b/apps/desktop/src/shared/providerSecrets.ts@@ -8,7 +8,8 @@* ("api_key" / "mivo_api_key")指代存储键名,随供应商增多容易散落、写错。本模块* 把「providerId → safeStorage 存储键名」收敛成唯一映射:* - main 端经 providerSecretStore 读写;- * - renderer 端用本模块解析键名后走通用 safeStorage IPC。+ * - renderer 端默认通过通用 safeStorage IPC 访问键;明确列出的 main-only 键除外,不得通过 generic bridge+ * 读取、覆盖或删除。动态 custom provider / MCP 键也依赖这一兼容策略。** 新增供应商:在 ProviderSecretId 加 id、在 STORAGE_KEYS 加映射即可。* - xd / mivo 沿用历史键名,避免迁移已有用户本机已存的 key;@@ -17,7 +18,7 @@*//** 供应商密钥的稳定标识。新增供应商时在此扩展。 */-export type ProviderSecretId = 'xd' | 'mivo' | 'brave' | 'tavily' | 'xai';+export type ProviderSecretId = 'xd' | 'mivo' | 'brave' | 'tavily' | 'xai' | 'voice-asr';/*** providerId → safeStorage 存储键名(.enc 文件名,不含后缀)。@@ -33,6 +34,9 @@ const STORAGE_KEYS: Record<ProviderSecretId, string> = {tavily: 'tavily_api_key',// xAI(SuperGrok)OAuth 凭证 blob(JSON:access/refresh/expires),供 responses-bridge 直连 api.x.ai。xai: 'provider_key_xai',+ // Voice input's user-configured realtime ASR credential is intentionally+ // isolated from chat/model gateway keys.+ 'voice-asr': 'voice_input_asr_api_key',// 未来新增示例(届时在 ProviderSecretId 与此处同步添加):// anthropic: 'provider_key_anthropic',// openai: 'provider_key_openai',@@ -46,6 +50,18 @@ export function providerSecretStorageKey(id: ProviderSecretId): string {return STORAGE_KEYS[id];}+const MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS = new Set<string>([+ STORAGE_KEYS['voice-asr'].toLowerCase(),+]);++/**+ * Whether the generic Renderer safeStorage bridge may access this logical+ * key. Main-only credentials use dedicated IPC that never returns plaintext.+ */+export function isRendererAccessibleSafeStorageKey(storageKey: string): boolean {+ return !MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS.has(storageKey.toLowerCase());+}+/*** 用户自定义供应商**某 runtime** 的密钥 safeStorage 存储键名(`provider_key_<id>_<agent>`)。*diff --git a/apps/desktop/src/shared/voiceInputAsrProfiles.ts b/apps/desktop/src/shared/voiceInputAsrProfiles.tsindex 772bc34140..8527f3eebe 100644--- a/apps/desktop/src/shared/voiceInputAsrProfiles.ts+++ b/apps/desktop/src/shared/voiceInputAsrProfiles.ts@@ -64,6 +64,7 @@ export const LITELLM_VOLCENGINE_SAUC_ASR_ENDPOINT_PATH = '/volcengine/api/v3/sauexport const LITELLM_VOLCENGINE_SAUC_ASR_RESOURCE_ID = 'volc.seedasr.sauc.duration';export const LITELLM_VOLCENGINE_SAUC_ASR_PCM_SAMPLE_RATE = 16_000;export const LITELLM_TRANSCRIPTION_MODEL = 'elevenlabs/scribe_v2';+export const CUSTOM_REALTIME_ASR_DISPLAY_MODEL = 'Custom realtime ASR';export const DEFAULT_VOICE_INPUT_PROVIDER_KIND = 'litellm-volcengine-sauc-asr';@@ -84,6 +85,20 @@ export const DEFAULT_VOICE_INPUT_ASR_PROVIDER_CHAIN = [// to the profile. Only add provider code when the upstream WebSocket protocol// is not covered by an existing `protocolProfile`.export const VOICE_INPUT_ASR_PROFILES = {+ 'custom-realtime-asr': {+ id: 'custom-realtime-asr',+ model: CUSTOM_REALTIME_ASR_DISPLAY_MODEL,+ auth: 'api-key',+ settingsTab: 'providers',+ mode: 'realtime-websocket',+ realtime: {+ pcmSampleRate: 24_000,+ protocolProfile: 'openai-transcription-manual',+ prewarmable: true,+ },+ missingCredentialMessage: 'Configure the realtime ASR WebSocket URL, model, protocol, and API key.',+ errorFallbackMessage: 'Custom realtime speech recognition failed.',+ },'elevenlabs-scribe-realtime': {id: 'elevenlabs-scribe-realtime',model: SCRIBE_REALTIME_MODEL,@@ -225,6 +240,9 @@ const VOICE_INPUT_PROVIDER_ALIASES: Record<string, VoiceInputProviderKind> = {'scribe-realtime': 'elevenlabs-scribe-realtime',scribe_v2_realtime: 'elevenlabs-scribe-realtime','elevenlabs-scribe-realtime': 'elevenlabs-scribe-realtime',+ custom: 'custom-realtime-asr',+ 'custom-realtime': 'custom-realtime-asr',+ 'custom-realtime-asr': 'custom-realtime-asr',};export function resolveVoiceInputProviderKindAlias(value: string): VoiceInputProviderKind | null {diff --git a/apps/desktop/src/shared/voiceInputConnectionTest.ts b/apps/desktop/src/shared/voiceInputConnectionTest.tsnew file mode 100644index 0000000000..2b5c592268--- /dev/null+++ b/apps/desktop/src/shared/voiceInputConnectionTest.ts@@ -0,0 +1,25 @@+import type { VoiceInputProviderKind } from './voiceInputAsrProfiles.js';++export const VOICE_INPUT_TEST_CONNECTION_CHANNEL = 'voice-input:test-connection';++export type VoiceInputConnectionTestFailureReason =+ | 'credentials-missing'+ | 'authentication-failed'+ | 'route-unavailable'+ | 'timeout'+ | 'network'+ | 'service-error'+ | 'unsupported-provider';++export type VoiceInputConnectionTestResult =+ | {+ ok: true;+ provider: VoiceInputProviderKind;+ providerModel: string;+ }+ | {+ ok: false;+ provider: VoiceInputProviderKind;+ providerModel: string;+ reason: VoiceInputConnectionTestFailureReason;+ };diff --git a/apps/desktop/src/shared/voiceInputCustomAsr.ts b/apps/desktop/src/shared/voiceInputCustomAsr.tsnew file mode 100644index 0000000000..6886d82b58--- /dev/null+++ b/apps/desktop/src/shared/voiceInputCustomAsr.ts@@ -0,0 +1,140 @@+export type VoiceInputCustomAsrProtocol = 'openai-realtime' | 'qwen-realtime';++export type VoiceInputCustomAsrConfig = {+ protocol: VoiceInputCustomAsrProtocol;+ websocketUrl: string;+ model: string;+};++export const MAX_CUSTOM_ASR_WEBSOCKET_URL_CHARS = 2_048;+export const MAX_CUSTOM_ASR_MODEL_CHARS = 200;+export const MAX_CUSTOM_ASR_API_KEY_CHARS = 8_192;+const ALLOWED_CUSTOM_ASR_QUERY_KEYS = new Set([+ 'model',+ 'model_id',+ 'api-version',+ 'api_version',+ 'deployment',+ 'intent',+ 'tenant',+ 'language',+ 'language_code',+ 'audio_format',+ 'commit_strategy',+ 'vad_silence_threshold_secs',+]);++/**+ * Credential scope for a custom ASR endpoint. Paths may change without+ * exposing the key to a different server, while scheme/host/port changes+ * require an explicit credential update.+ */+export function voiceInputCustomAsrCredentialScope(websocketUrl: string): string | null {+ try {+ return new URL(websocketUrl).origin;+ } catch {+ return null;+ }+}++export function canReuseVoiceInputCustomAsrCredential(+ currentWebsocketUrl: string | undefined,+ nextWebsocketUrl: string,+): boolean {+ if (!currentWebsocketUrl) return false;+ const currentScope = voiceInputCustomAsrCredentialScope(currentWebsocketUrl);+ return currentScope !== null+ && currentScope === voiceInputCustomAsrCredentialScope(nextWebsocketUrl);+}++/**+ * Qwen's realtime protocol selects its model in the WebSocket query rather+ * than the session.update payload. The form's model field remains the source+ * of truth and overrides a stale model query already present in the URL.+ */+export function resolveVoiceInputCustomAsrWebsocketUrl(+ config: VoiceInputCustomAsrConfig,+): string {+ if (config.protocol !== 'qwen-realtime') return config.websocketUrl;+ const websocketUrl = new URL(config.websocketUrl);+ websocketUrl.searchParams.set('model', config.model);+ return websocketUrl.toString();+}++export function validateVoiceInputCustomAsrWebsocketUrl(value: string): string | null {+ const websocketUrl = value.trim();+ if (!websocketUrl || websocketUrl.length > MAX_CUSTOM_ASR_WEBSOCKET_URL_CHARS) {+ return 'customAsr.websocketUrl is required and must be at most 2048 characters';+ }++ let parsedUrl: URL;+ try {+ parsedUrl = new URL(websocketUrl);+ } catch {+ return 'customAsr.websocketUrl must be a valid URL';+ }+ const loopbackHost = parsedUrl.hostname === 'localhost'+ || parsedUrl.hostname === '::1'+ || parsedUrl.hostname === '[::1]'+ || isLoopbackIpv4(parsedUrl.hostname);+ if (parsedUrl.protocol !== 'wss:' && !(parsedUrl.protocol === 'ws:' && loopbackHost)) {+ return 'customAsr.websocketUrl must use wss, or ws on a loopback host';+ }+ if (parsedUrl.username || parsedUrl.password) {+ return 'customAsr.websocketUrl must not contain credentials';+ }+ const containsDisallowedQuery = [...parsedUrl.searchParams.keys()].some((key) => (+ !ALLOWED_CUSTOM_ASR_QUERY_KEYS.has(key.toLowerCase())+ ));+ if (containsDisallowedQuery) {+ return 'customAsr.websocketUrl contains unsupported query parameters; only documented routing parameters are allowed';+ }+ if (parsedUrl.hash) {+ return 'customAsr.websocketUrl must not contain a fragment';+ }+ return null;+}++function isLoopbackIpv4(hostname: string): boolean {+ const octets = hostname.split('.');+ return octets.length === 4+ && octets[0] === '127'+ && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255);+}++export function validateVoiceInputCustomAsrConfig(+ value: unknown,+): { ok: true; value: VoiceInputCustomAsrConfig } | { ok: false; error: string } {+ if (!isPlainObject(value)) return { ok: false, error: 'customAsr must be an object' };++ const protocol = typeof value.protocol === 'string' ? value.protocol.trim().toLowerCase() : '';+ if (protocol !== 'openai-realtime' && protocol !== 'qwen-realtime') {+ return { ok: false, error: 'customAsr.protocol must be openai-realtime or qwen-realtime' };+ }++ const websocketUrl = typeof value.websocketUrl === 'string' ? value.websocketUrl.trim() : '';+ const websocketUrlError = validateVoiceInputCustomAsrWebsocketUrl(websocketUrl);+ if (websocketUrlError) return { ok: false, error: websocketUrlError };++ const model = typeof value.model === 'string' ? value.model.trim() : '';+ const hasControlCharacter = [...model].some((character) => {+ const codePoint = character.codePointAt(0) ?? 0;+ return codePoint <= 0x1f || codePoint === 0x7f;+ });+ if (!model || model.length > MAX_CUSTOM_ASR_MODEL_CHARS || hasControlCharacter) {+ return { ok: false, error: 'customAsr.model is required and must be at most 200 characters' };+ }++ return {+ ok: true,+ value: {+ protocol,+ websocketUrl,+ model,+ },+ };+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}